# Question
Title: Is there a way to have the LED switch on after 10 readings or say a minute?
I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.

I have tried doing various if loop much to my failure, below is the code I am currently using:

```
#include <RFID.h>
#include <SPI.h>
#define SS_PIN 10
#define RST_PIN 9
#define LED_PIN A0

RFID rfid(SS_PIN, RST_PIN);
int serNum[5];
String cardno;
int interval = 15000; // millisec
long now = 0;
long lasttime = millis();
// change Reader ID to your name
String readerID = "Reader_001";

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
  pinMode(A0, OUTPUT);
}

void loop() {
  now = millis();
  if (now > lasttime + interval) {
    lasttime = now;
    Serial.print(readerID);
    Serial.print(":");
    Serial.println("I am alive");
  }
  if (rfid.isCard()) {
    if (rfid.readCardSerial()) {
      lasttime = now;
      cardno = String(rfid.serNum[0]) +
               String(rfid.serNum[1]) +
               String(rfid.serNum[2]) +
               String(rfid.serNum[3]) +
               String(rfid.serNum[4]);

      Serial.print(readerID);
      Serial.print(":");
      Serial.println(cardno);
    }
  }
  rfid.halt();
  delay(10000);
}

```

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

# Answer
You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:

Inside your `void loop()` function you use the `millis()` coding style (refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is \>=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:

```
#define READ_INTERVAL 10000
int read_counter = 0;
unsigned long read_timestamp=0;
String last_identifier="";
void loop(){
    if(millis()-read_timestamp>READ_INTERVAL){
        // Read the chip
        if(card_identifier == last_identifier)
            read_counter++;
        else
            read_counter = 1;
        if(read_counter>=12){
            digitalWrite(LED_PIN, HIGH);
        }
    }
}

```

Be sure to use `unsigned long` with the `millis()` function, to prevent it from overflowing to a negative value.
> 1 votes

---
Tags: arduino-uno, led, rfid
---


# Question
Title: Optimizing for speed using const, static, constexpr etc in a function
In an ISR I want to keep things quick. At the same time I want to limit variable scope. Storage space is not a factor.

I have this line:

```
const char trigs[] = "aAbBcCdDeEfFgGhHiIjJ";

```

When this is global, the resulting compile stats show:

```
Sketch uses 3418 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

```

When it's inside the function (to limit scope) I get:

```
Sketch uses 3470 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

```

The extra program space is 52 bytes, which is more than the size of the variables, so there must be extra code in there. That might be something to do with initialization checks... but why? Isn't a `const` already known? If there's a difference in where it's stored, why doesn't global variable space change?

If I prefix this as `static const` I'm back to the first behavior `(3418 / 431)`.

So the immediate answer is just to use `static const`, I suppose. But I'm still curious what's going on. Can someone elucidate?

# Answer
> 0 votes
`const char trigs[]` is an auto - it's allocated on the stack at function entry time - and must be initialized at each invocation. The literal used to do that is stored in globals space, which is why the globals allocation doesn't change.

`static const char trigs[]` is allocated in globals space and used in place. The symbols' scope is still local, though, so `trigs[]` isn't visible outside the function.

So why does code space increase by 52 bytes? That seems a lot for copying a string from place to another. So I'll take a guess that the need to copy a string loads a library module that includes it and a few other functions as well.

---
Tags: c++, code-optimization, constants
---


# Question
Title: Why can't I switch off the LED immediately using this sketch?
I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.

```
const int buttonPin = 2;
const int ledPin = 9;
const int fadingDelay = 20000;
int buttonState = 0;
boolean fadingState = false;
void setup() {

// initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check whether the button was pressed
  if (buttonState == HIGH) {
    buttonState = LOW;
    // check the current LED status (on/off)
    if (fadingState == false) {
      // turn on the LED
        for (int i = 255; i >= 0; i -= 5) {
          if (buttonState == HIGH && fadingState == true) {
          analogWrite(ledPin, 0); //immediately off
          i=-1;
          }
        analogWrite(ledPin, i);
             delay(fadingDelay);

    }
    fadingState = false;  // save the current LED state (on/off)
  }
}
}

```

# Answer
I can't see anywhere where you are assigning `fadingState as true`.I can't understand this part

```
if (fadingState == false) {
      // turn on the LED
        for (int i = 255; i >= 0; i -= 5) {
          if (buttonState == HIGH && fadingState == true) {
          analogWrite(ledPin, 0); //immediately off
          i=-1;
          }
    analogWrite(ledPin, i);
    delay(fadingDelay);
    }

```

If you are entering in a `if` condition with statement `fadingState as false`. Then in `for loop` you are having a `if condition` in which `statement` is `fadingState == true`.If you are entering in as a False then why are you looking for True Condition.

Then if you manage to sort that add `break;` in that `if` condition so that when LED turns OFF you will exit that `for Loop`.

And Here you are setting the button state as low `buttonState = LOW` if first If condition, then in that nested `if` without reading the `buttonState` you still looking for it as `HIGH`.
> 0 votes

---
Tags: arduino-uno, led
---


title: Gps with Lora (E32 433T30D)

text:
# Question
Title: Gps with Lora (E32 433T30D)
I want to receive data from GPS Neo 6m to Arduino and want to sent through LoRa (E32 433T30D).

GPS RECEIVE AND LORA SEND code

```
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

static const int RXPin = 4, TXPin = 5;
static const int loraRXPin = 2, loraTXPin = 3;
static const uint32_t GPSBaud = 9600;
static const uint32_t loraBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
SoftwareSerial lora(loraRXPin, loraTXPin);

void setup(){
  Serial.begin(9600);
  ss.begin(GPSBaud);
  ss.println("KATHE");
  lora.begin(loraBaud);
  lora.println("ASHOK");
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0){
    gps.encode(ss.read());
    if (gps.location.isUpdated()){
      ss.listen();
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);
      lora.listen();
      lora.print("Latitude= ");
      lora.print(gps.location.lat(), 6);
      lora.print(" Longitude= ");
      lora.println(gps.location.lng(), 6);
    }
  }

  }

LORA RECEIVE CODE is

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    //Serial.println(" ");
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());

  }
}

```

Here I'm not getting gps data to the LoRa receiver. Please help me to overcome this problem.

# Answer
Lora we can connect directly to the arduino serial ports(0,1)- Lora Tx is connected to the arduino Rx and Lora Rx is connected to the arduino Tx. (this is for receiving data from arduino and must be connected these pins after uploading the code). (2,3) of other arduino to receive data to arduino from Lora. For sending there is no code like Bluetooth. And for receiving the following code helps you..

# include SoftwareSerial mySerial(2,3); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native j for the SoftwareSerial port mySerial.begin(9600); mySerial.println("Hello, world?"); } void loop() { // run over and over if (mySerial.available()) { Serial.write(mySerial.read()); //Serial.println(" "); } if (Serial.available()) { mySerial.write(Serial.read()); } }
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to get average of 16bit ADC readings?
I have an Adafruit ADS1115 analog-to-digital converter, configured in single ended mode. I want to average over 3 sensor readings to increase the reading stability.

```
  //initialize variables
  int16_t rawData, ambient;
  int i=0;

  // start loop
  while(i<3) {
      rawData = ads.readADC_SingleEnded(0); //read from ADC
      // divide sensor reading by three
      // (doing so after summation will lead to an overflow)
      rawData=rawData/3;
      Serial.println(rawData); // print data to serial for debugging (OK)
      ambient+=rawData;
      i+=1;
      delay(100);
      Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
  }

  // Print signal (NOT OK)
  Serial.print("Ambient is ");
  Serial.println(ambient);

```

The "rawData" is printed correctly on the serial monitor. However, the value for "ambient" can be crazy: the resulting output is over an order of magnitude higher. Somehow, the summation doesn't seem to be performed correctly.

# Answer
> 2 votes
If you are trying to average out three sensor ADC reading first you need to store and add them all then divide it by 3.

```
 int16_t rawData =0;
 int32_t avg=0,ambient=0;
  int i=0;

 while(i<3) {
      rawData = ads.readADC_SingleEnded(0); //read from ADC
      // divide sensor reading by three
      // (doing so after summation will lead to an overflow)
     Serial.println(rawData); // print data to serial for debugging (OK)
     avg += rawData;
      i++;
      delay(100);
      Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
  }
  abmient = avg /3;
  avg = 0;
  // Print signal (NOT OK)
  Serial.print("Ambient is ");
  Serial.println(ambient);

```

# Answer
> 2 votes
You forgot to initialize `ambient` to zero, so it got whatever happened to be in that place of memory when it got instantiated. Some unpredictable, seemingly random data.

---
Tags: arduino-uno, i2c, adc, mathematics
---


# Question
Title: Is SPI a good way to connect two rfid modules on separate arduino boards?
RFID access control

I have two separate rfid projects on separate arduino, the first project requires 2 minutes of contact between the tag and the reader after which it turns the LED on. the second project is a simple rfid access control, but on this access can only be granted if the conditions on the first tag were met. I am trying to use SPI for this but do not know if it would work, any suggestions on any other way of communication between two arduino boards?

# Answer
Its very easy.

1. Set one PIN of ARDUINO as ouput pin. You will write that PIN HIGH when your conditions are matched in ARDUINO1 then SET LOW after 1 mS.
2. Connect that PIN of ARDUINO1 to external Interrupt PIN of ARDUINO2.
3. Write a CODE for ARDUINO2 such that when EXTERNAL INTERRUPT OCCURS it will set variable high indicating that Conditions is Matched in ARDUINO1.
4. While providing access to on ARDUNO2 check that variable status if it is HIGH grant access and SET it LOW.

This is the basic Structure you can follow using interrrupt.
> -1 votes

---
Tags: arduino-uno, led, rfid
---


# Question
Title: Play computer *.wav files through Arduino
I am doing mice behavioral training. I have an arduino-controlled box for that. The sounds are play using Mp3 player controlled b the arduino. However, the mp3 player is not good enough for my needs.

I need two clear sounds of 10 msec duration and freqiencies of 5000Hrz and 1000Hrz. (I prefer pure sine waves but can compromise on triangle or, for now, even square). The problem is that the mp3 is not fast enough and the volume is too low for 10 msec durations. When I tried to build gain circuit it became too noisy.

I tried to use the Tone function but it is again not good for 10 msec sounds. espacially in the jigj frequency/

I created the wavefiles in Matlab. The PC plays the file in the right volume with no nose. However, I don't know how to make the arduino play the files from the computer.

Is there a relative simple way to do it, without bying extra hardware? If now, is there ANY way of doing it?

or another option, Is there a way for the arduino to play files from a wave generator? (I have these in my lab)

Thanks!

# Answer
Two options:

1. Write software for the PC to react to serial commands sent by the Arduino, or
2. Use a more powerful Arduino-like board with a DAC and do wavetable synthesis.

The Arduino Due and many of the other smaller ARM-based boards (like M0 boards) are a good candidate for option 2 because they are faster than a traditional Arduino and have a built-in DAC. However, a proper I2S CODEC chip attached to a powerful MCU would be the preferred method for high-quality playback.

Note that your amplification system is of critical importance. It's common for many cheap amplifiers to limit higher frequencies. You need an amplifier with a good flat response over and above the maximum frequency you want to reproduce. Just slapping together any old "gain" circuit is probably not going to be good enough. Most op-amp based solutions have a ratio (*Gain Bandwidth Product*) that reduces the bandwidth as the gain increases.
> 1 votes

# Answer
This code will create a steady 20 KHz output. Adjust the duration to reflect the period of your frequencies.

```
byte triggerOut = 19;

unsigned long currentMicros;
unsigned long nextMicros;
unsigned long duration = 25UL; // flip every 50uS = 20KHz pulse
unsigned long elapsedMicros;

void setup() {
  pinMode (triggerOut, OUTPUT);
}
void loop() {
  while (1) {
    currentMicros = micros();
    elapsedMicros = currentMicros - nextMicros;
    if (elapsedMicros >= duration) {
      nextMicros = nextMicros + duration;
      PINC = PINC | 0b00111111; // toggle D19 output by writing it input port.
    }
  }
}

```

Add some lines to start the output after a button push, and count the number of cycles to only output the time duration you want. 10,000 KHz = 0.1mS period, 10ms/0.1ms = 100 cycles.

Divide the 0 to 5V output down to 1V, and drive a computer self powered speaker to create the noise you want.
> 1 votes

---
Tags: audio, sound, wave
---


# Question
Title: ArduinoJSON v6 - Passing buffer as function parameter
I'm new to ArduinoJSON - so perhaps it is a newbie's question.... but I wish to pass a `StaticJsonDocument` into a function as a parameter ( later on it should be implemented in a library ).

exmaple below shows `test_1` what I wish to obtain, but by duplicating `StaticJsonDocument`, which I don't want to do.

How can `test_1` should be written (as I tried in `test_2`)?

```
#include <ArduinoJson.h>

StaticJsonDocument<200> doc;

void createJSON() {
        doc["sensor"] = "gps";
        doc["time"] = 1351824120;

        JsonArray data = doc.createNestedArray("data");
        data.add(48.756080);
        data.add(2.302038);

        // Generate the minified JSON and send it to the Serial port.
        serializeJson(doc, Serial);
        Serial.println("JSON is created:");

        // Generate the prettified JSON and send it to the Serial port.
        serializeJsonPretty(doc, Serial);

}

bool test_1(StaticJsonDocument<100> _doc){
        serializeJson(_doc, Serial);
        return true;
}

bool test2(const JsonObject& _doc){
        Serial.println("HI");
        serializeJson(_doc, Serial);
}

void setup() {
        Serial.begin(9600);

        createJSON();
        test_1(doc);

}

void loop() {
        // not used in this example
}

```

# Answer
The `StaticJsonDocument` is a template class. The template value in \<\> is here only the size of the internal buffer, but every size used generates a different class. (memory usage!)

To have the parameter of the function take an `StaticJsonDocument` version instance, it must be the same version or a common base class. In this case the base class is `JsonDocument`.

If you don't use the reference symbol `&` the parameter is copied. In this case `StaticJsonDocument<200> _doc` or `JsonDocument _doc` would create a copy and that copy would be modified in the function. The object used as parameter value would be unchanged - empty.

So use

```
void test2(const JsonDocument& _doc) {
  Serial.println("HI");
  serializeJson(_doc, Serial);
}

```
> 7 votes

---
Tags: pointer, json
---


# Question
Title: Sending mouseX and mouseY from Processing to Arduino
I'm new to serial communication and trying to send `mouseX` and `mouseY` from Processing to Arduino. Serial monitor doesn't show anything.

**Processing code:**

```
import processing.serial.*;
Serial port;
void setup() {
  size(500,300);
  port = new Serial(this , Serial.list()[0], 9600);
}

void draw() {
   text("X Y mouse",250,50);
   if (port.available() > 0) {
    port.write(str(mouseX)+' '+str(mouseY));
   }
}

```

**Arduino code:**

```
int x = 0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    x = Serial.read();
    Serial.print("I received: ");
    Serial.println(x);
  }
}

```

when I close Processing window and enter "ok" in Arduino serial monitor I see:

# Answer
> 1 votes
Since you can't use the serial monitor to "see" the incoming data from Processing, here are 2 test sketches that may help you determine if data is received on the Arduino.

Upload the Arduino sketch first. Leave the serial monitor **closed**. Now run the Processing sketch.

I'm using `frameRate(1)` in the Processing sketch to send the data once per second, so the mouse X/Y values in the Processing window will be slow to update.

You should see the LED on the Arduino flash on then off quickly as the data is received. If you have a I2C LCD available, you could connect it to the Arduino and print out the incoming data.

As chrisl mentions in the comments, there is still much work to be done to get the raw data in the format you require.

**Arduino**

```
int x = 0;
const byte ledPin = 2;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  if(Serial.available() > 0){
    x = Serial.read();
    digitalWrite(ledPin, HIGH);
  }
  else{
    digitalWrite(ledPin, LOW);
  }
}

```

**Processing**

```
import processing.serial.*;
Serial port;
void setup() {
  size(500,300);
  background(148);
  try{
    port = new Serial(this , Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }
  frameRate(1);
}

void draw() {
  background(148);
  //@chrisl comment: Finish your data, that you send with \n (newline).
  port.write(str(mouseX)+' '+str(mouseY) + "\n");
  text(mouseX,250,50);
  text(mouseY,250,70);
}

```

**EDIT**

Here is a second Arduino sketch that will display the mouse X/Y values sent from Processing on a LCD. You could change the Processing sketch's `frameRate()` value to 10.

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

char inputBuffer[32 + 1];

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup(){
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
}

void loop(){
  if(Serial.available() > 0){
    lcd.print("                ");
    Serial.readBytesUntil('\n', inputBuffer, 32);
    lcd.setCursor(0, 0);
    lcd.print(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}

```

---
Tags: arduino-uno, serial, processing-lang
---


# Question
Title: How to filter the power supply for an Arduino in a vehicle (car, motorcycle)?
I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics). I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).

Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.

For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.

Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.

I guess I have the following options:

a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.

b) Use another regulator to 5V

c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.

What is the proper solution and what are suitable values for the capacitors?

I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

# Answer
The solution depend on what causes the reset.

It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.

If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.

Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.
> 1 votes

---
Tags: power
---


# Question
Title: STM32YYXX chip series is not defined in boards.txt
The STM32YYXX chip series is not defined in `boards.txt`? How can I solve this? I am using Windows 10 with Arduino IDE 1.6.6

# Answer
### Overview

Following the guide Getting Started on the STM32 page on Github: Arduino core support for STM32 based boards:

> This repo is available as a package usable with Arduino Boards Manager.
>
> Use this link in the "Additional Boards Managers URLs" field:
>
> `https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json`
>
> For full instructions on using the "Boards Manager", see the Getting Started page.

Thanks to Juraj's comment for the tip

> this is not the current STM boards package. ST Microelectronic took over the development github.com/stm32duino/Arduino\_Core\_STM32 stm32duino.com/viewtopic.php?f=16&t=4671

### Step by Step

The process is as follows (screenshots from OS X, but on Windows/Linux the process is the same):

Adding the URL in the preferences dialog (one URL per line)

>

Boards Manager menu

>

Boards Manager dialog

>

Boards Manager dialog - STM32 Core Boards installed

>

Boards Manager dialog - Boards installing

>

Boards Manager dialog - Boards installed

>

Here are the newly installed boards in the menu

>

As a comparison, these are the boards installed using the deprecated manual process described below:

>

---

### Deprecated method

From STM32 - installation

> ### Prerequisites
>
> If your STM32 board does not have a bootloader yet and you want to be able to program it over USB, you'll have to upload the STM32duino bootloader to flash memory. See Burning the bootloader.
>
> ### Arduino and Arduino\_STM32
>
> * Download and install the official Arduino IDE. Versions 1.6.10 till 1.8.5 have been reported to work fine.
>     + If you already have the Arduino IDE installed and it's a newer version, see the Boards Manager package method of installation.
>         - Note: this method is deprecated and not supported in forum!
> * Run Arduino IDE, and open the menu **Tools -\> Boards -\> Boards Manager**. Install the "Arduino SAM Boards" package (includes the Arduino Due) from the list of available boards. This installs compiler support for ARM Cortex-M3.
> * Download a zip file containing the Arduino STM32 files from here.
> * Unzip the content of the zip file, and place the Arduino\_STM32 folder to `[Arduino sketches folder]/[hardware]/[Arduino_STM32]`. Create the '`hardware`' folder if it does not exist yet.
>
> Example how the path should look like: `C:\Users\<user>\Documents\Arduino\hardware\Arduino_STM32`

---

As an aside, for anyone using OS X, from Installation on OSX

> ### Installation on OSX
>
> * `Arduino_STM32` folder must be placed inside `~/Documents/Arduino/hardware` (note. if the hardware folder doesn't exist you will need to create it)
> * So you should get `~/Documents/Arduino/hardware/Arduino_STM32`
> * Note. DFU util binaries have now been added to the repo, in `tools/macosx/dfu-util`, so there is no longer a need to install Homebrew to then install `dfu-util`, or to compile `dfu-util` from source.
> 1 votes

---
Tags: programming
---


# Question
Title: Need help with wire connections and code
I am currently working on a keypad door lock mechanism (Similar to this project, Keypad door lock).

The issues with the code I have is that the keypad attached to my board does not allow me to type the full password. Only the first value displayed on the LCD screen moves but no value is excepted. Also the buttons used to open and close the servo motor do not operate as intended.

Fritzing diagram

Photo of breadboard

Below is the code I currently have:

```
//LCD config
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

#include <Servo.h>
#include <Keypad.h>

//Variables
int mot_min = 90;   //min servo angle  (set yours)
int mot_max = 180; //Max servo angle   (set yours)
int character = 0;
int activated = 0;
char Str[16] = {' ', ' ', ' ', ' ', ' ', ' ', '-', '*', '*', '*', ' ', ' ', ' ', ' ', ' ', ' '};
//               0    1    2    3    4    5    6    7    8    9    10   11  12    13   14  15

//Pins
Servo myservo;
int buzzer = 11;   //pin for the buzzer beep
int external = 12; //pin to inside open
int internal = 13; //pin to inside close

//Keypad config
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1', '4', '7', '*'},
  {'2', '5', '8', '0'},
  {'3', '6', '9', '#'},
  {'A', 'B', 'C', 'D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {
  myservo.attach(10); //attach the servo to pin D10
  pinMode(buzzer, OUTPUT);
  pinMode(external, INPUT);
  pinMode(internal, INPUT);
  //Init the screen and print the first text
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("    PASSWORD");
  lcd.setCursor(0, 1);
  lcd.print("      -***     ");
  //put the servo in the close position first
  myservo.write(mot_min);

}

void loop() {
  ///////////////EMERGENCY OPEN/CLOSE/////////
  if (digitalRead(external) == LOW) // if (digitalRead(external))
  {
    myservo.write(mot_max);
    lcd.clear();
    lcd.setCursor(2, 0);
    lcd.print("INSIDE  OPEN");
    activated = 2;
    analogWrite(buzzer, 240);
    delay(250);
    analogWrite(buzzer, 200);
    delay(250);
    analogWrite(buzzer, 180);
    delay(250);
    analogWrite(buzzer, 250);
    delay(250);
    analogWrite(buzzer, LOW);

    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("WELLCOME");

    lcd.setCursor(2, 1);
    lcd.print("ELECTRONOOBS");

    lcd.clear();
    lcd.setCursor(3, 0);
    lcd.print("DOOR  OPEN");
    lcd.setCursor(2, 1);
    lcd.print("ELECTRONOOBS");
    delay(500);

  }

  if (digitalRead(internal) == LOW) // if (digitalRead(internal))
  {
    myservo.write(mot_min);
    activated = 0;
    character = 0;
    Str[6] = '-';
    Str[7] = '*';
    Str[8] = '*';
    Str[9] = '*';
    Str[10] = ' ';
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("    PASSWORD");
    lcd.setCursor(0, 1);
    lcd.print(Str);
  }

  ///////////////KEYPAD OPEN/CLOSE////////////
  char customKey = customKeypad.getKey(); //this function reads the presed key

  if (customKey != NULL) { // if (customKey)

    if (character == 0)
    {
      Serial.println(customKey);
      Str[6] = customKey;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("    PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print(Str);

    }

    if (character == 1)
    {
      Serial.println(customKey);
      Str[7] = customKey;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("    PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print(Str);

    }

    if (character == 2) {
      {
        Serial.println(customKey);
        Str[8] = customKey;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }

      if (character == 3)
      {
        Serial.println(customKey);
        Str[9] = customKey;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }

      if (character == 4)
      {
        Serial.println(customKey);
        Str[10] = customKey;
        activated = 1;

      }
      character = character + 1;
    }

    if (activated == 1)
    {
      /*Change your password below!!!
        Change each of Str[6], Str[7], Str[8], Str[9]*/

      // if (Str[10] = 'A' && ...)
      if (Str[10] == 'A' && character == 5 && Str[6] == '3' && Str[7] == '0' && Str[8] == '0' && Str[9] == '7' )
      {
        myservo.write(mot_max);
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("ACCEPTED");
        activated = 2;
        analogWrite(buzzer, 240);
        delay(250);
        analogWrite(buzzer, 200);
        delay(250);
        analogWrite(buzzer, 180);
        delay(250);
        analogWrite(buzzer, 250);
        delay(250);
        analogWrite(buzzer, LOW);
        delay(1000);

        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("WELLCOME");
        delay(500);
        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");
        delay(1000);

        lcd.clear();
        lcd.setCursor(3, 0);
        lcd.print("DOOR  OPEN");
        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");

      }
      else
      {
        lcd.clear();
        lcd.setCursor(1, 0);
        lcd.print("PASSWORD ERROR");
        lcd.setCursor(3, 1);
        lcd.print("TRY  AGAIN");
        analogWrite(buzzer, 150);
        delay(3000);
        analogWrite(buzzer, LOW);
        character = 0;
        Str[6] = '-';
        Str[7] = '*';
        Str[8] = '*';
        Str[9] = '*';
        Str[10] = ' ';
        activated = 0;
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);
      }
    }
    if (activated == 2)
    {
      if (customKey == 'B' )
      {
        myservo.write(mot_min);
        activated = 0;
        character = 0;
        Str[6] = '-';
        Str[7] = '*';
        Str[8] = '*';
        Str[9] = '*';
        Str[10] = ' ';
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }
    }
  }
}

```

To re-iterate, With this code now the LCD screen displays `PASSWORD` but when I enter the password into the keypad only the first number changes value and it does not move to the second value.

# Answer
> 1 votes
You would appear to have an excess of `{` here:

```
if (character ==2) {
{    <<<< Remove this

```

and then remove the excess `}` at the end of the code.

It would seem that this is affecting the logic of your code, as you've ended up inadvertently grouping some `if`s within another `if`.

---

To avoid this type of situation, you need to be much more consistent with your code style (i.e. formatting/indentation).

Either use:

```
if (character ==2) {

```

or

```
if (character ==2)
{

```

but *don't mix them*. Otherwise you'll end up in a right old muddle.

If you keep your coding style consistent, then you'll see, in a flash, something that is out of place - merely by quickly scrolling through the code.

---

In addition, use the `Tools ► Auto Format` menu item in the Arduino IDE to correctly format your code and make it easy to read.

---
Tags: arduino-uno, c++
---


title: Using Pro Micro without soldering pin

text:
# Question
Title: Using Pro Micro without soldering pin
I'm a total newbie. I bought a Pro Micro but I didn't know that it can't be used, if you don't solder things in his holes. I found this picture on Google:

And it seems that exists those stuffs (green and white) to test the circuit before soldering.

Do you know where can I buy them? Or do you know their name?

Thanks.

# Answer
Perhaps you are looking for items like these from from a well established seller adafruit.com. However, what you are proposing is not cheap when compared to soldering. I would recommend you learn soldering as it will likely be the way you want to assemble your final Arduino project.
> 2 votes

# Answer
If you're just getting started and are not comfortable with soldering I would suggest getting one of the larger boards that has headers on it. (An Uno or a Mega, for example). You can use one of those and a breadboard to experiment without having to solder at all.

MicroCenter (A US retailer) sells 100% compatible Arduino Mega 2560 knockoffs for $10 US.

I suggest using a board like that when you are first starting out. (And learn how to solder. It's very useful for electronics repair and various other things.)
> 0 votes

---
Tags: arduino-micro
---


title: Byte text file to array

text:
# Question
Title: Byte text file to array
I'm trying to display a bitmap on gLCD 128x64, I stored the bitmap into txt file `1.txt` in a SD card this is a part of bit map as following:

0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00.......

I want to convert the content of this text into array: `Unsigned char logo[]` with making a split on "`,`".

Any help please

# Answer
The most efficient way is to read the file byte-by-byte into a small character array until you get a comma or the end of file - ignoring any characters that aren't of interest (line feeds, etc).

Then for each chunk that you read you then convert it to an integer.

For example (untested):

```
char temp[5] = {0}; // should be more than enough
int pos = 0;
int bno = 0;

const char *hexchars = "0123456789abcdefABCDEFx";

while ((int ch = myFile.read()) >= 0) {
    if (ch == ',') { // We found a comma
        logo[bno++] = strtoul(temp, NULL, 16); // Base 16 conversion
        pos = 0;
        temp[0] = 0;
    } else if (strchr(hexchars, ch) != NULL) {
        if (pos < 4) {
            temp[pos++] = ch;
            temp[pos] = 0;
        }
    }
}

```

Of course, you have to know how big the `logo` array has to be beforehand.

One does, though, have to ask "Why are you storing a graphical logo as a textual representation of binary data" in the first place? It would be far easier to just store it as a simple binary file and read the data directly into the `logo` array with a single `File::read(void *buf, size_t nbyte);` function call. Using text as an intermediate format is both wasteful and needlessly increases complexity massively.
> 1 votes

---
Tags: arduino-uno, arduino-ide, lcd, sd-card
---


# Question
Title: compare char receive from Slave writer to Master reader with I2C
Im trying to send data from slave (writer) to master (reader) then compare it to declared 'char p\[\]' to turn on the lights but somehow i cant make it work.

```
////master reader

    #include <Wire.h>

int LED = 13;
char p[] = "YES...";

void setup() {
  pinMode(LED, OUTPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

}

void loop() {
  Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c= Wire.read(); // receive a byte as character

  Serial.print(c);         // print the character

  if(c == p){

  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)

    }else{

  digitalWrite(LED, LOW);   // turn the LED on (HIGH is the voltage level)

          }

  }

  delay(1500);

```

**Slave**

```
//////////////     Slave       ///////////////////////

    #include <Wire.h>

const int pingPin = 8; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 9; // Echo Pin of Ultrasonic Sensor

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8

}

void loop() {
   long duration, inches, cm;
   pinMode(pingPin, OUTPUT);
   digitalWrite(pingPin, LOW);
   delayMicroseconds(2);
   digitalWrite(pingPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(pingPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(1500);

if( inches <= 4){

  Wire.onRequest(requestEvent); // register event
   Serial.print("Obstacle detected");
   Serial.println();
  }
  else
  {

  Wire.onRequest(requestEvent1); // register event
   Serial.print("Nothing Detected");
   Serial.println();

    }

}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {

  Wire.write("YES..."); // respond with message of 6 bytes
  // as expected by master
}
void requestEvent1() {

  Wire.write("NO...."); // respond with message of 6 bytes
  // as expected by master
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

```

# Answer
1. Improve you indentation.
2. If you want to compare two strings use `strcmp` function for that.
3. Your master part has some brackets left in your `void loop()` function, correct them.
4. In I2C you are receiving one `byte` at time. You should receive data till the last `byte` in received.
5. You should have some identification in your message, which is you are sending from slave to master indicating that this is last character. It helps you come out of Data reception loop in Master side.
> 1 votes

---
Tags: i2c
---


# Question
Title: error when trying to upload code to esp8266
Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes. Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes. error: Failed to open COM1 error: espcomm\_open failed error: espcomm\_upload\_mem failed

---

please help me to fix this issue.

# Answer
Try holding down the flash button when uploading the code to the board.

The ESP8266 and the ESP32 need certain buttons held down to open the COM port to upload code.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Transmit image file thougth the TX TR serial line
I have a digital camera with a USB port for image dowload from the camera SD card.

I will like to be able to capture this image files store in the camera SD card using the Arduino TX TR lines (serial) then transmit this image file to the computer from the USB connection from Arduino to Computer.

The reason need this scenario responds to that the camera dissables the shutter when sensing a USB cable conneted to computer. I do not knwo why this happens but I suspect is an underdeveloped feature of the camera.

Basically, I will like to use Arduino as a USB hub for external devices but at the same time to power down the line when no longer need the device using the Arduino TX and TX line . This will give tha camera a sense that the camera is been unplugged.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 1 votes
You cannot. The TX and RX lines are UART. UART is *not* USB. USB is a very complicated protocol, and you need a proper understanding of how it works. It's not a simple serial protocol like UART.

Add to that the fact that the Arduino can in no way handle the amount of data involved in video, and you're already on a non-starter.

---
Tags: usbasp, camera
---


# Question
Title: Class help - Same Object types seem to mix values with each other
I'm having issues with two objects of the same class type. I have a LED class, which has functions to fade in and out, a LED. In my code, I create two objects of this class, and on the board, I fade them in and out.

Code is in my FadingLED.h file, which I #include.

I instantiate these classes - and then in my setup(), I call an Init function on the classes to initialise them and pass all the parameters I need.

And then in the loop, I just keep calling an Update method, which internally, uses Millis() to handle updating the brightness of the LED.

But I think I am having cross contamination of the objects. Because if I trigger them both to fadein and out at the same time, only the first LED fades. If I stagger them, the 2nd LED works, but it's timing seems to be out. It seems like maybe I'm somehow mixing member variables within the class. I'm new to this, so it's probably an obvious fault?

My calling code:

```
// This #include statement was automatically added by the Particle IDE.
#include "Buzzer.h"
#include "FadingLED.h"

// Pins being used by devices.
int LED1_PIN = A4;
int LED2_PIN = A5;
int PIR_PIN = 3;
int BUZZER_PIN = 0;

// Instantiate the objects
FadingLED LED_1;
FadingLED LED_2;
Buzzer buzzer;

// Setup global variables.
bool AllStill = true;

// Setup.
void setup() {
    // Initialise the two LEDs
    LED_1.Init(LED1_PIN, 500, 0, true);
    LED_2.Init(LED2_PIN, 500, 250, true);
    // Set the PIR pinmode.
    pinMode(PIR_PIN, INPUT);
    Particle.publish("Device","Board initialised", PUBLIC);
    buzzer.Beep(100, 2200);
}

// Function to check if movement has been detected.
bool CheckMovement() {
    // Read the pin value.
    int val = digitalRead(PIR_PIN);

    // Has a new movement been detected?
    if(val==true && AllStill==true) {
        buzzer.Beep(200, 2200);
        AllStill = false;
        Particle.publish("Device", "Movement Detected", PUBLIC);
    }
    AllStill = !val; // All still is false if we have movement.

    return val != 0;
}

void loop() {
    // Check for moment.
    bool val = CheckMovement();
    // Update connected devices.
    LED_1.Update(val);
    LED_2.Update(val);
    buzzer.Update();
}

```

And then the class it's self.

```
/*
 * A class that manages a fading LED. This needs to be on PWM pin.
 */
class FadingLED {
  int             delayedStart = 0;               // Period to wait before starting.
  int             ledPin = -1;                    // The pin to control - Note, as we're fading, we must use an ANALOG pin.
  long            fadePeriod = 0;                 // The time to do a full light and dim cycle.
  unsigned long   previousMillis = 0;             // The previous millis value.
  bool            debug = false;                  // Should we output stuff?
  float           fadeChangeGap = 0;              // Calculated gap between brightness changes.
  unsigned long   firstMillis = -1;

public:
  void Init(int LedPin, int FadePeriod, int DelayedStart, bool Debug) {
    ledPin = LedPin;
    fadePeriod = FadePeriod;
    delayedStart = DelayedStart;
    debug = Debug;
    pinMode(ledPin, OUTPUT);
    Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
  }

  void Update(bool isOn) {

      // Get the current millis since the board was started.
      unsigned long currentMillis = millis();

      // Is this the first time this code is running?
      if(firstMillis == -1)
        firstMillis = currentMillis; // Set the first time this class was run.

      // Adjust the current time to be based on the current time since the object was created.
      currentMillis = currentMillis - firstMillis;

      // Calculate the difference bwteen the last update and now.
      unsigned long diff = currentMillis - previousMillis;

      int brightness = 0;

      // Check if we have a delay set. If so, don't light up yet.
      if(delayedStart > 0 && currentMillis < delayedStart) {
        Particle.publish("LED", "In Delay Start...", PUBLIC);
         previousMillis = currentMillis;
        return;
      }

      // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
      // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
      int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

      // Check if we should be bringtning, or fading...
      if(b > 255) {
        brightness = 255 - (b-255);
      }
      else
      {
        brightness = b;
      }

      if(isOn == false) {
        brightness = 0;
      }
      // Set the brightness.
      analogWrite(ledPin, brightness);

      // And then save the timestamp.
      if(currentMillis - previousMillis >= fadePeriod) {
         previousMillis = currentMillis;
      }
  }
};

```

Is there an error with how I am defining the class (I'd expect to use the 'new' keyword, but don't). Maybe in the class it's self, there is a way to say the field are private to that object only?

If I try:

```
FadingLED LED_1 = new FadingLED();

```

I get:

> conversion from 'FadingLED\*' to non-scalar type 'FadingLED' requested

Any assistance or advice would be great.

# Answer
> 1 votes
I combined the `FadingLED` class with your "calling code" sketch, then removed the references to libraries that I don't have. The first error I received was regarding the seven lines of code immediately under the **"class FadingLED {"** line.

My answer will only address the issues with the way the class is written. As Jot and Michel Keijzers have mentioned in their comments to your question, there may be other issues that need to be fixed.

The following sketch uses a slightly modified version of the `FadingLED` class. There are 2 constructors. One is a "no argument" constructor, and the other accepts 4 arguments. Both constructors call the private function `initStuff()` to initialize other variables, pinModes, etc.

```
/*
 * A class that manages a fading LED. This needs to be on PWM pin.
 */
class FadingLED {

  private:

    int             delayedStart;     // Period to wait before starting.
    int             ledPin;           // The pin to control - Note, as we're fading, we must use an ANALOG pin.
    long            fadePeriod;       // The time to do a full light and dim cycle.
    unsigned long   previousMillis;   // The previous millis value.
    bool            debug;            // Should we output stuff?
    float           fadeChangeGap;    // Calculated gap between brightness changes.
    unsigned long   firstMillis;

    void initStuff(){
      previousMillis = 0;
      fadeChangeGap = 0;
      firstMillis = -1;
      pinMode(ledPin, OUTPUT);
      //Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
    }

  public:

    FadingLED(): delayedStart(0), ledPin(-1), fadePeriod(0), debug(false){
      initStuff();
    }

    FadingLED(int LedPin, int FadePeriod, int DelayedStart, bool Debug):
      delayedStart(DelayedStart),
      ledPin(LedPin),
      fadePeriod(FadePeriod),
      debug(Debug){
      initStuff();
    }

    void Update(bool isOn) {

        // Get the current millis since the board was started.
        unsigned long currentMillis = millis();

        // Is this the first time this code is running?
        if(firstMillis == -1)
          firstMillis = currentMillis; // Set the first time this class was run.

        // Adjust the current time to be based on the current time since the object was created.
        currentMillis = currentMillis - firstMillis;

        // Calculate the difference bwteen the last update and now.
        unsigned long diff = currentMillis - previousMillis;

        int brightness = 0;

        // Check if we have a delay set. If so, don't light up yet.
        if(delayedStart > 0 && currentMillis < delayedStart) {
          //Particle.publish("LED", "In Delay Start...", PUBLIC);
          previousMillis = currentMillis;
          return;
        }

        // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
        // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
        int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

        // Check if we should be bringtning, or fading...
        if(b > 255) {
          brightness = 255 - (b-255);
        }
        else
        {
          brightness = b;
        }

        if(isOn == false) {
          brightness = 0;
        }
        // Set the brightness.
        analogWrite(ledPin, brightness);

        // And then save the timestamp.
        if(currentMillis - previousMillis >= fadePeriod) {
           previousMillis = currentMillis;
        }
    }
};

// This #include statement was automatically added by the Particle IDE.
//#include "Buzzer.h"
//#include "FadingLED.h"

// Pins being used by devices.
int LED1_PIN = A4;
int LED2_PIN = A5;
int PIR_PIN = 3;
int BUZZER_PIN = 0;

// Instantiate the objects
FadingLED LED_1(LED1_PIN, 500, 0, true);
FadingLED LED_2(LED2_PIN, 500, 250, true);
//Buzzer buzzer;

// Setup global variables.
bool AllStill = true;

// Setup.
void setup() {
    // Set the PIR pinmode.
    pinMode(PIR_PIN, INPUT);
    //Particle.publish("Device","Board initialised", PUBLIC);
    //buzzer.Beep(100, 2200);
}

// Function to check if movement has been detected.
bool CheckMovement() {
    // Read the pin value.
    int val = digitalRead(PIR_PIN);

    // Has a new movement been detected?
    if(val==true && AllStill==true) {
        //buzzer.Beep(200, 2200);
        AllStill = false;
        //Particle.publish("Device", "Movement Detected", PUBLIC);
    }
    AllStill = !val; // All still is false if we have movement.

    return val != 0;
}

void loop() {
    // Check for moment.
    bool val = CheckMovement();
    // Update connected devices.
    LED_1.Update(val);
    LED_2.Update(val);
    //buzzer.Update();
}

```

---
Tags: arduino-uno, c++, class, loop
---


# Question
Title: Servo motor not working properly with arduino
I have some problem with my fyp, which is auto serving of food using train.

I have 4 servo motors, first servo motor's function is to connect the track to table no.1, and second motor for table no.2 and third and fourth motor for table no.3.

All the motors are performing well at first time.. but when I reset and give command for second or third table, motors behavior changes and they start rotating in arbitrary directions which are not defined in code. but sometimes it works good and sometimes motors are not performing as expected.

I have check all the grounds and powers. they are all good.

Please help me, as I have my final submission in two days.

The code is given below.. Please check and tell me if I have a logical error in my code or any other issue regarding to hardware also tell me is their any cache in arduino, which I need to clean or something like that.

```
#include <Servo.h>

Servo motor;  // create servo object to control a servo
// twelve servo objects can be created on most boards

const int button1 = A1;
const int button2 = A2;
const int button3 = A3;

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;

void setup() {

  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  servo1.attach(9);
  servo2.attach(11);
  servo3.attach(6);
  servo4.attach(5);

  Serial.begin(9600);
}

void loop() {

  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);

  if (buttonState1 == HIGH) {
    int pos1 = 180;
    int pos2 = 180;
    int pos3 = 90;
    int pos4 = 90;

    for (int pos2=90; pos2 <= 180; pos2 += 1) {
      servo2.write(pos2);
      delay(0);
    }
    for (int pos1=90; pos1 <= 180; pos1 += 1) {
      servo1.write(pos1);
      delay(50);
    }

    while (pos1 >= 0 && pos2 >= 0 && pos3 >= 0 && pos4 <= 180) {
//      servo1.writeMicroseconds (1000);

//      servo1.write(pos1);
//      servo2.write(pos2);
      servo3.write(pos3);
      servo4.write(pos4);
      delay(200000);                // 500ms delay
    }

  }
  else if (buttonState2 == HIGH) {

    int pos5 = 90;
    int pos6 = 0;

    for (int pos5=90; pos5 >= 0; pos5 -= 1) {
      servo1.write(pos5);
      delay(0);
    }
    for (int pos6=90; pos6 >= 0; pos6 -= 1) {
      servo2.write(pos6);
      delay(50);
    }

    while ( pos6 <= 180 && pos5 <= 180) {

//      servo2.write(pos6);
//      servo1.write(pos5);
      delay(200);
    }
//      while ( pos5 <= 180) {
//        servo1.write(pos5);
//        delay(200);
//      }

  }
  else if (buttonState3 == HIGH) {
    int pos9 = 90;
    int pos10 = 180;
    int pos11 = 0;
    int pos12 = 180;

    for (int pos10=90; pos10 <= 180; pos10 += 1) {
      servo2.write(pos10);
      delay(0);
    }
    for (int pos9=90; pos9 >= 0; pos9 -= 1) {
      servo1.write(pos9);
      delay(0);
    }
    for (int pos11=90; pos11 >= 0; pos11 -= 1) {
      servo3.write(pos11);
      delay(30);
    }
    for (int pos12=90; pos12 <= 180; pos12 += 5) {
      servo4.write(pos12);
      delay(50);
    }

    while ( pos9 <= 180 && pos10 >= 0 && pos11 >= 0 && pos12 >= 0) {

//      servo1.write(pos9);
//      servo2.write(pos10);
//      servo3.write(pos11);
//      servo4.write(pos12);
//      delay(200);
    }
//      while ( pos9 <= 180) {
//        servo1.write(pos9);
//        delay(200);
//      }
  }

}

```

# Answer
I think reason for which you are not getting the expected result is because of you `while loops` in you `if condition`.

As you loops doesn't have any termination condition. In case of `first button` pressed you will get what you want because you have only single not terminating while loop, while in you Case of `button 2 and button 3` there are two while loop's and both are not terminating.

In that case if you logic goes in first while loop, then it never comes out of it and won't go for second loop.

I don't know what are you up to so can't suggest on logic changes, but add termination in while loop might get you expected results.
> 1 votes

---
Tags: motor, servo
---


# Question
Title: Esp8266 not responding to GET request from Android app created using MIT App Inventor
I hope I am posting this question in the right section. I am making a Smart Home Project for my college semester finals. I am using an Atmega328p microcontroller along with an ESP8266 (Esp 01). The Atmega328p controls all the sensors and actuators and sends the data to Esp01 via serial communication.

I have created a web server on the Esp01 which I plan to access by creating an app using MIT App Inventor. My GET request is of the format "http://192.168.43.42/4" where the digit at the end is data I want to send to the server and the response I get from the server is of the format "12&0&34.8" where the '&' is used to separate different values.

My problem is , when I access the server from Chrome in my laptop I get the desired response but when I access it using the App , I get an error "Error 1101 :Cannot find the specified URL". The Esp01 is connecting to a hotspot from my phone and I have checked the IP assigned to the Esp01 to ensure my GET request is correct.

The code for Esp01 in Arduino IDE is here : https://gist.github.com/TheMagicSmoke/467d6227d670697464038056e22f302d

The blocks for the app made in App Inventor is below:

The GET request URL when entered from Chrome in laptop returns a blank page at first but upon refreshing Chrome I get the desired response I told earlier. And in the app , I have used a timer which queries the server with the same GET request every 2 seconds. But when I open the App the error keeps on popping up. Please suggest me a solution, I have googled this without any success.

# Answer
I have found out the solution to this problem. The code that I had written in the Arduino IDE for the Esp8266 was not correct for handling the GET request. It only accepted data as a simple Web Server and not as a HTTP server. I am posting the modified code below .

https://gist.github.com/TheMagicSmoke/adaae1e4d92f258c88184c8690e68f08
> 1 votes

---
Tags: arduino-uno, esp8266, web-server, android
---


# Question
Title: Multiple slave(sender) to one master (receiver)
I beg your help to my project I wish to send the data from slave to master but only one data is receive out of two slaves.

```
//master

#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output

}

void loop() {
  Wire.requestFrom(8, 1);    // request 6 bytes from slave device #8

  while (Wire.available()) { // slave may send less than requested
    char c= Wire.read(); // receive a byte as character
    char q= Wire.read();

  Serial.print(c);         // print the character
  Serial.print(q);
  }

  delay(1500);
}

```

////slave 1

```
#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop(){
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Q');
  Serial.println("Sent");
}

```

////slave 2

```
#include <Wire.h>

void setup() {
  Serial.begin(9600); // Starting Serial Terminal
  Wire.begin(8);                // join i2c bus with address #8
}

void loop() {
  Wire.onRequest(requestEvent); // register event

  delay(1500);
}
void requestEvent() {

  Wire.write('Y');
  Serial.println("Sent");
}

```

# Answer
> 3 votes
You cannot have 2 devices with the same address at the I2C bus. If they both try to send at the same time with different data, the data will either get corrupted, or one of the slaves will stop to send. You cannot request data from more than 1 device at once with I2C.

You have to give the slaves different addresses. Then you have to do the requests sequentially, first a request (with the corresponding read) to the first slave and after that is done, you can start a second request (with the corresponding read).

---

Besides that, the reading code is not good. You are testing in the condition of the `while` loop, if there is anything to read (which can be only 1 byte), but then you read 2 bytes. In your case you only have to read 1 byte, since you also request only 1 byte. In the case, when you request more than 1 byte, you can either check, if there are enough bytes in the buffer (with something like `if(Wire.available()>=2)` ), or you can just work through the buffer byte by byte (with `while(Wire.available()){ data = Wire.read();}` , note the single read in the while loop).

---
Tags: i2c
---


title: Programming the serial description

text:
# Question
Title: Programming the serial description
Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?

It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.

I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.

This finds a general Arduino device:

```
for port in serial.tools.list_ports.comports():
    if "Arduino" in port.description:
        print "Arduino device!"

```

But I want something like this:

```
for port in serial.tools.list_ports.comports():
    if "proximity_sensor" in port.description:
        print "My specific Arduino program!"

```

# Answer
On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.

However (*shameless self-promotion coming here...*) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:

```
USBFS usbDevice;
USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
CDCACM USBSerial;

void setup() {
    USB.addDevice(USBSerial);
    USB.begin();
}

void loop() {
    USBSerial.println(millis());
    delay(1000);
}

```

Which results in:

```
[  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
[  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
[  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  661.458619] usb 2-1.2.7: Product: My Little Widget
[  661.458621] usb 2-1.2.7: Manufacturer: Espentech
[  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
[  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device

```
> 1 votes

---
Tags: serial, usb, python, windows
---


# Question
Title: Using 18650 batteries with a 3.7v to 5v boost converter
I'm looking to set up a 1-meter strip of WS2812B LEDs (60 LEDs) with an off-the-shelf RF LED controller with a remote. The LEDs want a 5V supply - I've tried running them off 3.7v but the colour accuracy goes out the window and they start flickering and doing all sorts of other nonsense.

To work around that I'm considering using a DC boost converter like one of these pololu ones. I'll wire up a couple 18650 batteries in parallel to supply the voltage and my plan is to hook them up to the LEDs via the boost converter.

Idiot question time: is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground? Or am I doing something dumb?

Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

# Answer
> is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground?

Yes. That is the normal way of using them.

> Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

That is the simplest option, yes. You shouldn't charge Li-Poly / Li-Ion batteries whilst using them - the load messes with the charge termination detection and can cause your batteries to over-charge and explode.

> Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

That gets around the problem of charging while running, yes. A proper charger like that should bypass the battery when charging so the load is running from the incoming charge power rather than the battery.

One option you haven't considered though is to *not* use step-up. Step-up is harder to manage with heavy loads. As you can see that first step-up module you link to has an upper limit of only 1.2A. If you have 60 LEDs per meter, and 1 meter of LED strip, that's a maximum of 3.6A (60 * 0.02 * 3) which is 3x what that module can provide.

A better solution would be to use two batteries in *series*, not parallel, to give you about 7.2V. Then you can use a step-down switching regulator to give you your 5V and have far higher current limits. Looking for a "UBEC" or "SBEC" in a model RC supplier shop is usually a good bet. For example:

These are all designed for use with two or more LiPoly batteries in series.
> 1 votes

---
Tags: led, adafruit, battery, led-strip, ws2812
---


title: Where this function is defined?

text:
# Question
Title: Where this function is defined?
This is the code for timer example in esp8266..(got from a website)

My doubt is where the function timer1\_enable(TIM\_DIV16, TIM\_EDGE, TIM\_SINGLE) is defined ?? I am look in Ticker.cpp, but not found.

```
#include < ESP8266WiFi.h>
#include < Ticker.h >

Ticker blinker;

#define LED 2  //On board LED

//=======================================================================
void ICACHE_RAM_ATTR onTimerISR(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
    timer1_write(600000);//12us
}

void setup()
{
    Serial.begin(115200);
    Serial.println("");

    pinMode(LED,OUTPUT);

    //Initialize Ticker every 0.5s
    timer1_attachInterrupt(onTimerISR);
    timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
    timer1_write(600000); //120000 us
}

void loop()
{
}

```

# Answer
> 2 votes
Those functions have nothing to do with the Ticker library. Those functions are defined in the ESP8266 core.

The example you cite has this at the top of it:

> Hardware Timer0 is used by WiFi Functions. We can use only Timer1. **Use of timer instead of Ticker** gives advantage of precision timing and You can get timer interrupt in micro seconds.

Note the use of "instead of Ticker" there. That says that the code below has nothing to do with Ticker.

---
Tags: esp8266
---


# Question
Title: Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on
I'm connecting a button to ESP8266. Connection goes like this: 3v to one side of button, other side connected with GND and pin number 2 (no resistor).

Every time I connect the ESP both built in LED's stay on until I press the button, they turn off until I let go (even though code states otherwise). Plus, When I monitor the serial, gibberish runs while ignoring my print commands, until I press the button then the serial stops outputting altogether.

When I run the serial without the button, everything works fine. Am I connecting it wrong, or is the button damaged, or any other problem source? Thanks in advance.

EDIT: I added the pinMode(BTN\_PIN, INPUT\_PULLUP) to take the resistor role; to the code, still not helping.

# Answer
When pin 2 is connected to ground as you have done it puts the chip into an invalid boot mode. It will be spewing out messages at 74880 baud complaining about the boot mode being invalid.

You must not connect pin 2 to ground. It must, at boot time, be connected to 3.3V through a resistor (which is should be provided by the board for you if you use a development board not a bare module).

By connecting the button between 3.3V and GND you are causing a short circuit that removes the power from the module and risks damaging the power supply on your board.

The proper way of wiring a button is to use:

```
pinMode(2, INPUT_PULLUP);

```

and then connect the GPIO pin to ground *through* the button.

The `INPUT_PULLUP` acts like the required pullup resistor keeping the input HIGH while "idle", and the button connects the input to GND when you want to "activate" it, making it LOW.

Those are the only connections you should make. If you want to use an external resistor *instead of* the internal one with `INPUT_PULLUP`, then that goes between the input pin and 3.3V.

Never ever cause 3.3V to be directly connected to GND.
> 1 votes

---
Tags: serial, esp8266, button
---


title: HX711 Soft WDT Reset

text:
# Question
Title: HX711 Soft WDT Reset
I am using the following code to check if the value is 0 e.g there is no weights placed and if so, it will ignore this value and do nothing with it. The code runs correctly but keeps outputting the following:

> Soft WDT reset
>
> > > > stack\>\>\>
>
> ctx: cont sp: 3ffffd70 end: 3fffffc0 offset: 01b0 3fffff20: 00000050 00000000 31310010 36323439 3fffff30: 00000000 00000000 00000010 00000001 3fffff40: 3ffee408 00000000 00000000 40202927 3fffff50: 4022dff2 a0000000 bf2cc404 3ffe84dc 3fffff60: 3ffee408 bf2cc404 3ffee408 40202962 3fffff70: 3ffeeb9c 40202c00 3ffee408 40202996
> 3fffff80: 3ffee448 bf2cc404 3ffee408 40202664 3fffff90: 3fffdad0 fffe2d7e 3ffee448 3ffee4b0 3fffffa0: 3fffdad0 00000000 3ffee480 40203848 3fffffb0: feefeffe feefeffe 3ffe8514 40100a41
> \<\<

If I remove if(reading \< 0.01){ the code runs fine. What could be causing this?

```
#include "HX711.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define DOUT  D3
#define CLK  D2
const char* ssid = "Curtis";
const char* password = "password";

HX711 scale(DOUT, CLK);
float calibration_factor = -118470; //-7050 worked for my 440lb max scale setup
void joinwifi(){
    WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");
   while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("success!");
  Serial.print("IP Address is: ");
  Serial.println(WiFi.localIP());
}
void setup() {
  Serial.begin(9600);
  joinwifi();
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}
void loop() {
  while (WiFi.status() == WL_CONNECTED)
  {
    scale.set_scale(calibration_factor); //Adjust to this calibration factor
    float reading = scale.get_units(1);
    if(reading < 0.01){
      Serial.print("no need");
       Serial.println();
    }
    else{
      Serial.print("Reading: ");
      Serial.print(reading);
      Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();
      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }
  }
  while (WiFi.status() != WL_CONNECTED)
  {
    joinwifi();
  }

}

```

# Answer
Because your code is all running in a `while` inside your loop (which is redundant - loop() loops, hence its name), and you have no delays or `yield()` calls, you are not giving the watchdog the required kick that it needs to stay alive.

Either remove your whiles and turn them into ifs instead, or add `yeild()` calls inside your `while` loops.
> 2 votes

---
Tags: arduino-uno, esp8266, arduino-ide
---


# Question
Title: ESP-12F responds only to a few basic AT commands
I previously read a few guides and tutorials about the ESP8266 and i just started using the ESP-12F module as i think that it is a terrific replacement for Arduino with the added benefit of Wi-Fi. I only have the module itself which is basically a metal casing so, i wired up the ESP-12F module according to this schematic.

My USB-TTL board is operating at 3 V for its VCC and also for the TX and RX logic levels. I use Arduino IDE 1.8.9 (i made sure that i am using the latest stable version) and then set the COM port to the USB-TTL RS232 connected to the ESP12F and typed "AT" and got a response "OK". Then, i tried, "AT+RST" and got a big bunch of text which proved that there is successful communication with the ESP module. But then, i tried to connect the ESP-12F to my Wi-Fi network, so i entered: AT+CWJAP\_CUR="SSID","password" replacing the SSID and password with my own and it gave the response "ERROR", so i tried the old format AT+CWJAP="SSID","password" and again i got "ERROR". So, what am i doing wrong? How to fix this? I was thinking that maybe the firmware on my ESP is old and needs to be updated, so i entered "AT+GMR" and i got this info:

```
19:07:27.560 -> ready
19:07:27.560 -> AT+GMR
19:07:27.560 -> AT version:1.2.0.0(Jul  1 2016 20:04:45)
19:07:27.560 -> SDK version:1.5.4.1(39cb9a32)
19:07:27.560 -> Ai-Thinker Technology Co. Ltd.
19:07:27.560 -> Dec  2 2016 14:21:16
19:07:27.560 -> OK

```

Do i need to update my module to be able to connect it to my Wi-Fi? If yes, how? I want to update it as safely as possible as this is my only ESP module and i don't want to inadvertently damage it.

# Answer
You can't connect to an access point until you put the module into Station mode.

```
AT+CWMODE=1

```

That will put it in STA mode. You can alternatively make it an access point (AP mode) with:

```
AP+CWMODE=2

```
> 1 votes

---
Tags: esp8266, wifi
---


# Question
Title: avrdude: stk500_getsync(): not in sync: resp=0xyy ... where to find the response values?
Last week I retried some of my Arduinos and one Mega was working without a problem, but two Uno's didn't work anymore. The error I got was something like:

```
avrdude: stk500_getsync(): not in sync: resp=0xyy

```

Where yy where all different kind of values (I cannot copy/paste it as I'm not near the Arduino's).

Does anybody know where to find a document what the response values mean?

# Answer
They don't mean anything.

AVRDude sends a packet, and expects a certain response. When it gets something that it's not expecting it tells you it's "out of sync", and tells you what the actual response was it got. That is, what byte it received over the serial port. That could be something that your sketch is sending, or complete garbage if you're communicating with a floating serial input, or anything at all.
> 1 votes

---
Tags: arduino-uno, arduino-ide, error
---


# Question
Title: I have a problem with my nano arduino and the nrf24l01 as receiver
Hello I have a problem with my nano arduino and the nrf24l01 as receiver . I'm trying to upload my code to my board, but it say that my code have this mistake:

Receiver:45:10: error: void value not ignored as it ought to be

exit status 1 void value not ignored as it ought to be

the complet code is:

```
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>

//Receiver Code (Hand)

#include <Servo.h>    //the library which helps us to control the servo motor
#include <SPI.h>      //the communication interface with the modem
#include "RF24.h"     //the library which helps us to control the radio modem

//define the servo name
Servo myServo1;
Servo myServo3;
Servo myServo4;
Servo myServo2;
Servo myServo5;

RF24 radio(9,10);     /*This object represents a modem connected to the Arduino.
                      Arguments 9 and 10 are a digital pin numbers to which signals
                      CE and CSN are connected.*/

const uint64_t pipe = 0xE8E8F0F0E1LL; //the address of the modem,that will receive data from the Arduino.

int msg[5];

void setup(){

  //define the servo input pins
  myServo1.attach(15); //A1
  myServo2.attach(16); //A2
  myServo3.attach(17); //A3
  myServo4.attach(18); //A4
  myServo5.attach(19); //A5

  radio.begin();                    //it activates the modem.
  radio.openReadingPipe(1, pipe);   //determines the address of our modem which receive data.
  radio.startListening();           //enable receiving data via modem
  }

void loop(){
  if(radio.available()){
    bool done = false;
    while (!done){
    done = radio.read(msg, sizeof(msg));

    myServo1.write(msg[2]); //A1
    myServo2.write(msg[4]); //A2
    myServo3.write(msg[3]); //A3
    myServo4.write(msg[1]); //A4
    myServo5.write(msg[0]); //A5
    }
  }
}

```

and the problen is here:

done = radio.read(msg, sizeof(msg));

I don't know hoy to make that comes out as a code. I'm sorry. I'm trying to program a bionic hand but i have just started to work with arduino boards and their respective prongram. If someone can help me I would be very grateful. thanks

# Answer
> 1 votes
`radio.read()` does not return a value. You can't assign "no value" to a boolean.

If `radio.available()` is true then `radio.read()` *will* succeed. There is no need to test if it worked or not.

---
Tags: c++, arduino-nano, nrf24l01+
---


title: Fan regulator control from Arduino

text:
# Question
Title: Fan regulator control from Arduino
I'm trying to control my ~230 V fan from the Arduino.

Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

# Answer
To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.

This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has a library for the module.

**EDIT**:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an arduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

```
#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

```

**EDIT 2** version with triac activated by 'pwm' pin

```
const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // 8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

void setup() {
  Serial.begin(115200);
  Serial.println("START");

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1; // full off
  // WGM mode 14 - Fast PWM w/TOP=ICR1
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

```

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

**EDIT 3:**

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.
> 7 votes

# Answer
Its not exactly what you are looking for but it will help Arduino-controlled-light-dimmer-The-circuit.

Here is the sample project in which TRIAC is used with arduino for controlling the flow of current to the light. In your case Light or better we can say load is FAN. This will help you in controlling the FAN Speed. Relay only act as switch and it won't control FAN Speed.
> 1 votes

# Answer
Finally i found it as a product available here with the thyristor circuit and *electrical-contactless* ***servo (PWM or ANALOG input) motor*** ( to drive the input) will helps to drive the output from 0 to 220V. **smooth fan regulator can also do this with servo motor and without any external electrical component requirement** . If it is not efficient way with low cost design command or answer your way. :-).
> 1 votes

# Answer
There is also the issue of isolation here, to keep the controller side from being connected to the mains for reasons of noise and safety. The previous posters' comments about doing this with triacs or mosfets, and phase angle control are all true. It is nearly impossible to control the speed of a single phase induction motor. Anyway, the most elegant solution is to get a 3 phase fan motor and a variable frequency drive with low-voltage DC control input. Run the pwm output from the Arduino through an opto-isolator (drive the internal led). Use the DC reference on the speed control to power the output of the opto-isolator. Run that through an rc lowpass filter to the speed control voltage input. I think you could get out of this for around 200$US. Check surpluscenter.com. there are many motors and drives out there. -Hugh
> 1 votes

# Answer
It depends on the motor.

To quote MarkT from this post:

> The simple advice is you can't. Standard induction motors in domestic appliances cannot safely be speed-controlled (some can be a little, but its not easy to find out by how much).
> Get a DC fan

To quote dc42, from this post:

> What sort of motors do the fans have? If they use induction motors, then you won't be able to control the speed much using phase angle switching - the speed is tied to the supply frequency. If they are series-wound motors with brushes, then phase angle switching should work.
>
> The results you reported when you tried to use the velleman kit suggests to me that the fans may have induction motors.

---

For more information, read:
> -1 votes

---
Tags: arduino-uno, relay, remote-control, home-automation
---


# Question
Title: Parsing Integers from Serial data stream
I'm trying to send sensor data from my Remote Control to my Bot via Bluetooth. It's 6 numbers that I would like to have read as integers on the other side. I'm printing them to Serial on the Remote side with the numbers separated by commas. I've also added a start marker "\<" and an end marker "\>".

The incoming data from the remote looks like this in the Bots Serial Monitor:

\<1,1,1,1,1,512\>
\<1,1,1,1,1,512\>
\<1,1,1,1,1,513\>
\<1,1,1,1,1,512\>
\<1,1,1,1,1,512\>
etc

Before adding in the markers I was trying to use Serial.parseInt() to do this, but I kpet getting out of order numbers (probably from no start marker?).

```
if (Serial1.available() > 0) {

 trig1 = Serial.parseInt();
 trig2 = Serial.parseInt();
 trig3 = Serial.parseInt();
 trig4 = Serial.parseInt();
 trig5 = Serial.parseInt();
 pot = Serial.parseInt();

if (Serial.read() == '\n') {
}
}

```

But now that I have the markers I don't know the best way to initialize the code. Anyone have any ideas on how to parse these 6 numbers into usable integers?

EDIT: I've wrote a code based on VE7JRO's comments.

```
uint16_t myArray[6] = {};
int counter = 0;

void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available() > 0) {
  char* pch = strtok(Serial.read,"<>,\r\n");
   }
while(pch != NULL){
  myArray[counter] = atoi(pch);
  pch = strtok(NULL, "<>,\r\n");
  counter += 1;
 }

 trig1 = myArray[0];
 trig2 = myArray[1];
 trig3 = myArray[2];
 trig4 = myArray[3];
 trig5 = myArray[4];
 pot   = myArray[5];

 Serial.print (trig1);
 Serial.print (", ");
 Serial.print (trig2);
 Serial.print (", ");
 Serial.print (trig3);
 Serial.print (", ");
 Serial.print (trig4);
 Serial.print (", ");
 Serial.print (trig5);
 Serial.print (", ");
 Serial.println(pot);
 }

```

I'm getting this error code: invalid use of non-static member function
for this line:

```
      char* pch = strtok(Serial.read,"<>,\r\n");

```

Other than that. I subbed out the test input that VE7JRO put in and inserted "Serial.read". Not sure if that is the correct way to do this. Any ideas?

I tried your second sketch. It kind of worked. The data that printed to the serial monitor looked like this:

1, 1, 1, 1, 1, 519 518, 1, 1, 1, 1, 519 1, 1, 1, 1, 19, 9 1, 1, 1, 1, 1, 519 1, 1, 1, 1, 1, 519 1, 1, 1, 1, 1, 518 1, 1, 519, 518, 1, 518 1, 1, 519, 518, 1, 518 1, 1, 518, 518, 1, 518 1, 1, 1, 1, 1, 8 1, 1, 1, 1, 1, 519 1, 1, 518, 1, 1, 1 8, 1, 518, 1, 1, 1 1, 1, 519, 1, 1, 1 1, 1, 1, 519, 1, 1 1, 1, 1, 519, 1, 1 1, 1, 1, 1, 1, 519 1, 1, 1, 1, 1, 518 1, 1, 1, 1, 519, 8 1, 1, 1, 1, 1, 518 1, 1, 1, 1, 1, 519 1, 1, 1, 1, 1, 518 1, 1, 1, 1, 1, 518 1, 1, 1, 1, 1, 520

it should have all been 1, 1, 1, 1, 1, 518(ish).

# Answer
> 1 votes
Here is a sketch that uses strtok() and atoi() to parse the data and store the results in an `integer` array.

```
char testInput[] = "<1,2,3,4,5,512>\r\n";
uint16_t myArray[6] = {};

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(testInput,"<>,\r\n");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "<>,\r\n");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }

}

void loop(){}

```

**EDIT**

Based on your comments, I have another sketch for you to try.

```
// Sample input: <1,2,3,4,5,512>
char testInput[40];
uint16_t myArray[6] = {};
int counter = 0;

void setup(){
  Serial.begin(9600);
}

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', testInput, 40);

    char* pch = strtok(testInput,"<>,\r\n");

    while(pch != NULL){
      myArray[counter] = atoi(pch);
      pch = strtok(NULL, "<>,\r\n");
      counter += 1;
    }

    Serial.print (myArray[0]);
    Serial.print (", ");
    Serial.print (myArray[1]);
    Serial.print (", ");
    Serial.print (myArray[2]);
    Serial.print (", ");
    Serial.print (myArray[3]);
    Serial.print (", ");
    Serial.print (myArray[4]);
    Serial.print (", ");
    Serial.println(myArray[5]);

    counter = 0;
  }
}

```

---
Tags: serial
---


# Question
Title: How do I start a task and have it run for a set amount of time?
I have a project where I need to turn a 24V solenoid on for a set amount of time, then have it turn off. I am rather new to Arduino and not certain how to do this or really where to start. Ideally the time would be displayed on a LCD screen as well but this is purely aesthetic. Any advice, help, examples ect would be appreciated. Thanks!

# Answer
Use `millis();`

Record `millis()` in a `long` variable like below when the solenoid starts `StartTime = millis();`

to switch off solenoid after 60 seconds you may do

```
if ( (millis() - StartTime)/1000 ) >  60
{
   // switch off solenoid
}

```

enjoy coding.

There are other ways as well to achieve this... but this is being easiest and you don't have to wait caused by using `delay();`
> 1 votes

---
Tags: timers, time
---


title: fail to pass a value in constructor

text:
# Question
Title: fail to pass a value in constructor
I'm making a JSON lib dedicated for my own needs, based on `ArduinoJSON` v6.

I try to define `StaticJsonDocument<_docSize> doc` in a parametric way but I get this error and I cant find the reason for it:

```
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp: In constructor 'myJSON::myJSON(char*, int, bool)':
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:28: sorry, unimplemented: use of the value of the object being constructed in a constant expression
         StaticJsonDocument<_docSize> doc;
                            ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: error: 'this' is not a constant expression
         StaticJsonDocument<_docSize> doc;
                                    ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: note: in template argument for type 'unsigned int'
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:41: error: invalid type in declaration before ';' token
         StaticJsonDocument<_docSize> doc;
                                         ^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

```

I paste only relevant part of the code

`myJSON.h` :

```
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
int _docSize=100;
bool useSerial;
char _filename[30];

public:
myJSON(char *filename, int docsize, bool useserial=false);
bool file_exists();//char *file=_filename);
bool file_remove();
bool format ();

};
#endif

```

`myJSON.cpp`:

```
#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

myJSON::myJSON(char *filename, int docsize, bool useserial) {

        _docSize = docsize;
        useSerial = useserial;

        StaticJsonDocument<_docSize> doc;

        if (useSerial) {
                Serial.begin(9600);
        }
        if (!SPIFFS.begin()) {
                if (useSerial) {
                        Serial.println("Failed to mount file system");
                }
        }
        else{
                sprintf(_filename,"%s",filename);
        }
}

```

# Answer
> 1 votes
A class that uses `<...>` is called a *template* class. That class uses a form of substitution at compile time to create a *concrete* class with those values and tokens substituted.

It is then that *concrete* class that is used to instantiate your object(s).

However, you are trying to use a runtime variable to convert a *template* class into a *concrete* class, and that can't be done at compile time - and there is no such thing as a *runtime template* in C++.

You need to re-think your implementation methodology.

---
Tags: library
---


title: 'Var' does not name a type!

text:
# Question
Title: 'Var' does not name a type!
I don't have much experience in C++ programming. I'm getting this error

`'z' does not name a type!!!`

which I have't seen in MATLAB or python... What's wrong??? It is so simple!!!

```
float x=10; float y=50; float z;
z=x*y;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

```

# Answer
You cannot put an expression statement outside a function. Only the variable declarations can be placed outside functions (and those variables are called globals/global variables).

Try the following:

```
float x=10; float y=50; float z;

void setup() {
  // put your setup code here, to run once:
  z=x*y;
}

void loop() {
  // put your main code here, to run repeatedly:
}

```

**Update**

What even is easier and also works (thanks to Ruslan and Juraj):

```
float x=10; float y=50; float z=x*y;

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

```
> 5 votes

---
Tags: arduino-uno, programming, c++, error
---


# Question
Title: How to upload and store settings/variables from computer on the arduino?
I'm literally as green of a noob as I can be at this moment. Been watching a ton of tuts as I plan my project, but can't seem to find anything about settings being uploaded from an external source, and then stored on the arduino.

I want to create a board with multiple buttons. I want these buttons to then transmit MIDI PC/CC based on customizable settings uploaded via a computer. So, I'll create an app that can "create" the settings (json?) for each button. Ideally, I'd just connect the board, create the settings, then upload it to the device.

I've been reading about storing things like this in EEPROM, but that has a limited life span (which scares me). So, do I store these variables in EEPROM, or do I just compile and upload the app that has the new values in the variables?

I'm just looking for a possible direction and links for research.

Thanks in advance.

# Answer
> 1 votes
Your question is quite broad, so I will give you some directions for the different parts.

1. **Communication with the PC to receive settings:** For the Arduino Uno you are basically left with the Serial (UART) interface to communicate with the PC. For wired communication you can simply use the USB port. On your PC you need a program to send the settings over the serial com port to the Arduino. You can either use any serial terminal program or you can write your own. That depends on your needs. On the Arduino you need code to parse the serial communication to get the settings. It seems, that your can be rather complex (not just simple numbers of the same type). So you should implement a basic message protocol. It is common to use the newline character (`\n`) as the delimiter at the end of a message. In your code you read the serial data into a buffer, until you read a newline character. Then you start to process the message in a whole. You can see the implementation of this protocol in the `SerialEvent` example that comes with the Arduino IDE. Then you can use JSON as text based data format to transmit it to the Arduino. There you can use the Arduino JSON library to decode the data and get the settings. If you don't want to use JSON, you can also use a simpler protocol.
2. **Saving the received settings**: Without any further hardware the EEPROM is the way to go. The "life span", that you mention, are the possible number of write cycles, until a cell is not longer garanteed to work correctly. Read cycles don't do any harm here. Atmel gives a number of 100.000 write cycles, but notice, that this is the minimum garanteed number. (Have a look at this question for further info) Do you really change the settings this often? Make a short calculation like this: Imagine that you want to change the settings 10 times a day on every day in the year. Even then you get about 27 years with the EEPROM write cycles, far enough for other components to break. But if you really want to go safe here, you can use wear leveling. With this technique you rotate through different EEPROM cells to save your settings. You use more space in EEPROM, but each individual cell will get only a fraction of the write load. There are even libraries ready to use for this. A quick google search gave me the EEPROMWearLevel library, though I haven't used it myself. Depending on the total size of your settings, you might get a life span multiple times bigger with this. If you still don't want to use EEPROM, you can do as jsotola wrote in his comment: You can by a SD card module for Arduino and a fitting SD card and save the data there. This will lead to more programming overhead, especially, if you want to use a file system to also be able to read and write the SD card on the PC. (Note: The storage chips in SD cards have the same problem with limited write cycles, so they have the wear leveling incorporated into the hardware of the card)

---

You might as well decide, that you don't need the settings to be persistent between resets. Then you can just use variables and fill them with the settings from the Serial interface code.

You yourself have to decide, what the best way to go is here.

---
Tags: arduino-uno, eeprom, midi
---


# Question
Title: A1-A5 pins not declared in this scope error
When I set my board to 'Generic ESP8266 module' then only A0 pin of arduino is working while all other analog pins are coming out of scope , when I set the board to 'arduino /genuino uno' ,
then "Error compiling for board Arduino/Genuino Uno." this error is coming how to set the board such that all analog pins with ESP8266 will work?

# Answer
> 1 votes
If you look at the ESP8266 pinout diagram (for example here), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.

Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.

You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.

---
Tags: arduino-uno
---