# Question
Title: Syntax for declaring more than one serial pins of Arduino mega?
How can I declare multiple serial ports for Arduino Mega as it has been in the example below?

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(18,19); // RX, TX  //how this syntax can be modified for multiple Rx module?

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

void loop(){
   Serial.write(45);    // send a byte with the value 45

   int bytesSent = Serial.write(â€œhelloâ€); //send the string â€œhelloâ€ and return the length of the string.
}

```

# Answer
> 5 votes
If you mean the built in serial ports then just user the other objects that are pre-declared as per:

https://www.arduino.cc/en/Serial/Begin

# Answer
> 5 votes
From the official docs on serial:

> The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).

Which means, you use `Serial1` for serial on pins 19 and 18 instead of `Serial`:

```
void setup(){
   Serial1.begin(9600);
}

void loop(){
   Serial1.write(45);    // send a byte with the value 45

   int bytesSent = Serial1.write("hello"); //send the string "hello" and return the length of the string.
}

```

---
Tags: arduino-mega
---


# Question
Title: Running two stepper motors with two rotary encoders
I'm really bad with this coding part of using two rotary encoders to control two stepper motors \[using 28BYJ-48 stepper motor with the ULN2003 board\]. This code works fine using one rotary encoder for one stepper motor using this off brainy-bits.com:

https://brainy-bits.com/blogs/tutorials/stepper-motor-rotary-encoder-p1

When I slightly modify the code for two encoders and two stepper motors I'm using this: However I'm not getting the results I expected. The two motors just don't respond.

```
#include "Stepper.h"
#define STEPS 32   // Number of steps for one revolution of Internal shaft
// 2048 steps for one revolution of External shaft

volatile boolean TurnDetected;  // need volatile for Interrupts
volatile boolean rotationdirection;  // CW or CCW rotation

const int PinCLK = 2; // Generating interrupts using CLK signal
const int PinDT = 3;  // Reading DT signal
const int PinSW = 4;  // Reading Push Button switch
const int PinCLK2 = 46;
const int PinDT2 = 47;
const int PinSW2 = 48;

int RotaryPosition = 0;  // To store Stepper Motor Position
int RotaryPosition2 = 0;

int PrevPosition;     // Previous Rotary position Value to check accuracy
int PrevPosition2;
int StepsToTake;      // How much to move Stepper
int StepsToTake2;

// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4
Stepper small_stepper(STEPS, 8, 10, 9, 11);
Stepper small_stepper2(STEPS, 40, 41, 42, 43);

// Interrupt routine runs if CLK goes from HIGH to LOW
void isr () {
  delay(4);  // delay for Debouncing
  if (digitalRead(PinCLK))
    rotationdirection = digitalRead(PinDT);
  else
    rotationdirection = !digitalRead(PinDT);
  TurnDetected = true;
  /////I added this
  delay(4);  // delay for Debouncing
  if (digitalRead(PinCLK2))
    rotationdirection = digitalRead(PinDT2);
  else
    rotationdirection = !digitalRead(PinDT2);
  TurnDetected = true;
}
/////up to here

void setup () {
  pinMode(PinCLK, INPUT);
  pinMode(PinDT, INPUT);
  pinMode(PinSW, INPUT);
  digitalWrite(PinSW, HIGH); // Pull-Up resistor for switch
  attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
  pinMode(PinCLK2, INPUT);
  pinMode(PinDT2, INPUT);
  pinMode(PinSW2, INPUT);
  digitalWrite(PinSW2, HIGH); // Pull-Up resistor for switch
  attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
}

void loop () {
  small_stepper.setSpeed(600); //Max seems to be 700
  if (!(digitalRead(PinSW))) {   // check if button is pressed
    if (RotaryPosition == 0) {  // check if button was already pressed
    } else {
      small_stepper.step(-(RotaryPosition * 50));
      RotaryPosition = 0; // Reset position to ZERO
    }
  }

  // Runs if rotation was detected
  if (TurnDetected) {
    PrevPosition = RotaryPosition; // Save previous position in variable
    if (rotationdirection) {
      RotaryPosition = RotaryPosition - 1;
    } // decrase Position by 1
    else {
      RotaryPosition = RotaryPosition + 1;
    } // increase Position by 1

    TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

    // Which direction to move Stepper motor
    if ((PrevPosition + 1) == RotaryPosition) { // Move motor CW
      StepsToTake = 50;
      small_stepper.step(StepsToTake);
    }

    if ((RotaryPosition + 1) == PrevPosition) { // Move motor CCW
      StepsToTake = -50;
      small_stepper.step(StepsToTake);
      small_stepper2.setSpeed(600); //Max seems to be 700
      if (!(digitalRead(PinSW2))) {   // check if button is pressed
        if (RotaryPosition2 == 0) {  // check if button was already pressed
        } else {
          small_stepper2.step(-(RotaryPosition * 50));
          RotaryPosition2 = 0; // Reset position to ZERO
        }
      }

      // Runs if rotation was detected
      if (TurnDetected)
      {
        PrevPosition2 = RotaryPosition2; // Save previous position in variable
        if (rotationdirection) {
          RotaryPosition2 = RotaryPosition2 - 1;
        } // decrase Position by 1
        else {
          RotaryPosition2 = RotaryPosition2 + 1;
        } // increase Position by 1

        TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

        // Which direction to move Stepper motor
        if ((PrevPosition2 + 1) == RotaryPosition2) { // Move motor CW
          StepsToTake = 50;
          small_stepper2.step(StepsToTake);
        }

        if ((RotaryPosition2 + 1) == PrevPosition2) { // Move motor CCW
          StepsToTake = -50;
          small_stepper2.step(StepsToTake);
        }
      }
    }
  }
}

```

# Answer
> -1 votes
simple:

1) write a set of routines that drive your servo motor via interrupts: you will need to specify the on-time for each servo channel.

2) write a set of routines that read the rotary positions.

3) write a set of routines that convert the rotary positions into the on-time parameter.

4) integrate them all.

in your loop, you will simply need to read one rotary position, convert it into the on-time for that channel, and update the on-time parameter. The servo routines will run in the background transparently to your code.

---
Tags: arduino-uno, arduino-mega, arduino-ide
---


# Question
Title: How can I store the received data from nRF24l01+ module in an array (code in description)?
This is my sample RX code for 4 Tx and 1 Rx nRF24l01+ modules. I want to store all the data received from 4 pipes into an array (recArray).

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

RF24 radio(7, 8);

const uint64_t pipes[4] = {0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL, 0xF0F0F0F0E4LL};
char text[32] = {0}; #received data
int recArray[4]={0, 0, 0, 0}; # array to store the received bytes

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, pipes[0]);
  radio.openReadingPipe(2, pipes[1]);
  radio.openReadingPipe(3, pipes[2]);
  radio.openReadingPipe(4, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

```

# Answer
I would suggest to send 2 bytes to this module
the first byte is the pipe number (0xE1,0xE2,0xE3,0xE4)
and in the second byte Data

```
void loop()
{
  if (radio.available())
 {
  radio.read(&text, sizeof(text));
  for (int i=0; i < 4 ; i ++)
   {
     if( text[0] == ((unsigned char *)(&pipes[i]))[0]
        recArray[i] = text[1];
   }
  Serial.println(text[1]);
 }
}

```
> 1 votes

---
Tags: arduino-uno, programming, nrf24l01+, array, pointer
---


# Question
Title: Controlling I2C slave on Arduino with Python
Typically, when I connect my Arduino to a slave device through I2C or SPI, I'll control the slave using instructions coded in the firmware. The output data will be then printed to the Serial port and I'll use Python or MATLAB to read from the serial port and process the data later on.

```
PC <- Arduino <--> Slave

```

Now say I want to control the I2C slave from my computer, i.e. write instructions to the I2C slave. How do I go about it? I thought of writing to the Arduino Serial port, making Arduino read it and hence configuring it but this doesn't seem efficient and I have been racking my head over this for a while.

# Answer
Since you are using an arduino as a partial bridge to a PC, it appears that you already have a solution in hand.

There is a project on Git that is intended to perform this function that you could use for reference. (Disclaimer -- I have not tested this code.)

The cheapest stand alone device that I found was a $15 breakout board from Adafruit.
> 1 votes

---
Tags: i2c, spi, python
---


title: Library using another library

text:
# Question
Title: Library using another library
I'm writing library for smart home arduino DIY project.
i want to use another library(not written by me).
here is the code:

boiler.cpp

```
#include "Boiler.h"

Boiler::Boiler(int pin)
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

```

boiler.h

```
#ifndef BOILER_H_
#define BOILER_H_

// include RF24 libs
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>

// SmartHome Lib Includes
#include "Device.h"
#include "TimerOne.h"
#include "timeSet.h"

class Boiler
{

    private:

        RF24 radio(7, 8);
        RF24Network network(radio);
        RF24Mesh mesh(radio, network);

        int _pin ;

        void timerIsr();
        void DrawSCR();
    public:
        .
        .
        .

        Boiler (int pin );
        void turnOn();
        void turnOff();
};

```

The problem is it's not compiling
the error I get is :
Boiler.h: 32:14: error: expected identifier before numeric constant
RF24 radio(7, 8)

What am i doing wrong? Thanks,

# Answer
I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file

```
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
.
.
.
#include "Boiler.h"

RF24 radio(7, 8);                                   // Init RF24 Radio
RF24Network network(radio);                         // Init RF24 Network
RF24Mesh mesh(radio, network);                      // Init RF24 Mesh

Boiler::Boiler(int pin ,float Rev , String Last )
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

void Boiler::init( char nodeID)
{
    _nodeID = nodeID;
    // Connect to the mesh and set Node ID
    mesh.setNodeID(_nodeID);
    if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
    mesh.begin();

    // init LCD and print init data on LCD
    myGLCD.InitLCD(60);                         // Init LCD 55 contrast
    myGLCD.setFont(SmallFont);                  // Set small font
    myGLCD.clrScr();                            // clr screen
    myGLCD.print("Boiler Device",0,0);          //Print init Data on screen
    myGLCD.print("Rev :" , 0 , 10);
    myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
    myGLCD.print(_last,0,40);
    myGLCD.update();                            // Update display

    turnOff();
}

```

and now it compiles ;-)
> 2 votes

# Answer
> What am i doing wrong?

without seeing those includes, it is hard to tell.

I can say is that your original code, with the includes in boiler.h, is the right approach.

the revised code, which doesn't give you the error message, it not the right approach.

the issue is likely that the associated .h and .cpp files are incorrectly coded. unfortunately, without the actual code, it is hard to tell how and what the fixes should be.
> 1 votes

---
Tags: library, nrf24l01+
---


# Question
Title: Do they make 2.54mm 2P Crimpable Micro JST Female connectors?
This may be a dumb question but I need some (preferably with wires already attached) and I'm unable to find any like this. Everything I find has male crimps and female surface mount. That doesn't work for very well with my project because I do not have room in my project box for another board. I'm already cramped just adding the headers that I was planning to solder these wires to.

Here is what I'm looking for in the 1.25mm variety:

# Answer
I've found this product listing on Amazon:

2.54mm spacing JST extension cable.

It resembles the connector you've shown only slightly, but may be the only option out there.

And to contest the above statement, one that looks more like your objective:

Another 2.54mm spacing JST cable

There may be others. I used "jst 2.54 mm 2 pin female cable" as the search terms specifically in Amazon, other sources may have similar results.

Firing up the old Google again, using the last set of search terms, I've found an eBay listing:

eBay product listing

with the source in china. The photo appears correct, although the listing is for two cables, one male, one female, there is a third photo with the circuit board mount type connector.

This particular listing calls them a 2.5 mm connector, close enough? Perhaps a translation error.
> 1 votes

---
Tags: hardware
---


# Question
Title: Two ints declared simultaneously, one "does not name a type"
I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):

```
  int readButtons(){
  rbuttonState = digitalRead(right);
  lbuttonState = digitalRead(left);
  sbuttonState = digitalRead(sel);
  obuttonState = digitalRead(off);
  nbuttonState = digitalRead(snooze);
  int ret = -1;
  if (rbuttonState != lastrButtonState){
        if (rbuttonState == HIGH) {
            ret = right;
          }
        }
        if (lbuttonState != lastlButtonState){
          if (lbuttonState == HIGH) {
            ret = left;
          }
        }
        if (sbuttonState != lastsButtonState){
          if (sbuttonState == HIGH) {
            ret = sel;
          }
        }
        if (obuttonState != lastoButtonState){
          if (obuttonState == HIGH) {
            ret = off;
          }
        }
        if (nbuttonState != lastnButtonState){
          if (nbuttonState == HIGH) {
            ret = snooze;
          }
        }
  }
  lastrButtonState = rbuttonState;
  lastlButtonState = lbuttonState;
  lastsButtonState = sbuttonState;
  lastoButtonState = obuttonState;
  lastnButtonState = nbuttonState;
  return ret;
}

```

Yet I have the errors that

```
Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
   lastrButtonState = rbuttonState;
   ^
Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
   lastlButtonState = lbuttonState;
   ^
Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
   lastsButtonState = sbuttonState;
   ^
Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
   lastoButtonState = obuttonState;
   ^
Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
   lastnButtonState = nbuttonState;
   ^
Nixie_Clock_0:70: error: expected unqualified-id before 'return'
   return ret;
   ^
Nixie_Clock_0:71: error: expected declaration before '}' token
 }
 ^
exit status 1
'lastrButtonState' does not name a type

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

(The last line of code is line 72). I am at a complete loss. Any help?

# Answer
the following code

1. is properly indented
2. is missing the declarations of the variables for the 'button states' and the 'prior button states'
3. has additional text about a format error
4. is properly indented
5. has the code blocks properly separated by a single blank line

and now the code

```
int readButtons()
{
    rbuttonState = digitalRead(right);
    lbuttonState = digitalRead(left);
    sbuttonState = digitalRead(sel);
    obuttonState = digitalRead(off);
    nbuttonState = digitalRead(snooze);
    int ret = -1;

    if (rbuttonState != lastrButtonState)
    {
        if (rbuttonState == HIGH)
        {
            ret = right;
        }
    }

    if (lbuttonState != lastlButtonState)
    {
        if (lbuttonState == HIGH)
        {
            ret = left;
        }
    }

    if (sbuttonState != lastsButtonState)
    {
        if (sbuttonState == HIGH)
        {
            ret = sel;
        }
    }

    if (obuttonState != lastoButtonState)
    {
        if (obuttonState == HIGH)
        {
        ret = off;
        }
    }

    if (nbuttonState != lastnButtonState)
    {
        if (nbuttonState == HIGH)
        {
        ret = snooze;
        }
    }
}  << extranious closing brace ends the actual function

    lastrButtonState = rbuttonState;
    lastlButtonState = lbuttonState;
    lastsButtonState = sbuttonState;
    lastoButtonState = obuttonState;
    lastnButtonState = nbuttonState;
    return ret;
}

```
> 0 votes

---
Tags: c
---


# Question
Title: Where to connect shield in USB power supply for Arduino?
I'm making a 5 volt portable regulated power supply (using LM7805 regulator IC) for Arduino UNO. I'm planning to use a USB connector as its output socket, this way I can just plug it into the Arduino to power it.

My problem is where do I connect the USB sockets's shield? (Not an Arduino shield - I am talking about the USB cable's shield).

As far as I know it should be connected to the ground if it is a host device - can we consider the power supply as a host device?

# Answer
> 0 votes
A similar question has been asked in the Electrical Engineering Stack Exchange: EMI/ESD protection for USB interface?

> As for the SHIELD connection, you are correct - it is the metal casing of the connector and the braided shield of the USB cable that connects so it, which is likely referenced to protective Earth somewhere on the PC side of things. For EMI reasons it should not be directly tied to the GND signal connection, but should be connected through some impedance. I've seen both parallel resistor / capacitor (as you've shown) and ferrite bead connections between them. --Adam Lawrence

A good technical explanation was written by Ali Chen in his answer to this question:

> Ali Chen's Answer to Structure of a USB 2.0 connector

In the answer, Ali recommends using a 330 ohm resistor in parallel to a 0.1uF capacitor between the digital ground and the protective earth (shield).

simulate this circuit – Schematic created using CircuitLab

# Answer
> 0 votes
If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.

---
Tags: arduino-uno, power, usb
---


# Question
Title: Serial communication with more than two Arduinos
Is my syntax "SoftwareSerial uno1(0,1); // RX, TX" is right to communicate with more than two Arduinos?. How can I communicate with three Unos via single Mega?

```
#include <SoftwareSerial.h>
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

float lt[24]={3530,1580,3880,2780,4040,11260,7935,6655,2100,5100,1450,2200,2200,5900,6180,4230,2405,3560,4535,12635,12085,3500,930,3430};
float gt[24]={0,0,0,0,0,0,6320,5496.9,5948,4124.1,3848.4,3573,3022.2,3297.6,3298.2,3573,4123.2,0,0,0,0,0,0};
float lbt[24]={3530,1580,3880,2780,4040,7960,7935,2655,900,1400,1450,1300,1000,3400,3680,1730,2405,3560,4535,9635,9885,3500,930,3430};
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float lst[24]={0,0,0,0,0,3300,0,4000,1200,3700,0,900,1200,2500,2500,2500,0,0,0,3000,2200,0,0,0};
float les1[24]={0,0,0,0,0,0,0,2000,1200,0,0,0,0,2500,2500,2500,0,0,0,0,1200,0,0,0};
float les2[24]={0,0,0,0,0,3300,0,0,0,0,0,900,1200,0,0,0,0,0,0,2000,0,0,0,0};
float les3[24]={0,0,0,0,0,0,0,2000,0,3700,0,0,0,0,0,0,0,0,0,1000,1000,0,0,0};
float BatCap[24]={405.83,405.83,405.83,305.83,305.83,305.83,305.83,305.83,588.91,576.24,799.08,936.45,1050.87,811.05,570.85,493.19,590.53,637.47,397.47,397.47,397.47,397.47,397.47,397.47};

float Pvpin=41,Batpin=42,Gridpin=43;

void setup() {
// DEFINING THE MODES OF LOADS, OBEVIOUSLY OUTPUT.
  pinMode(Pvpin,OUTPUT);
  pinMode(Batpin,OUTPUT);
  pinMode(Gridpin,OUTPUT);

  Serial.begin(9600);
  uno1.begin(9600);
  uno2.begin(9600);
  uno3.begin(9600);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB
  }
}

void loop()
{
  for (int i=0;i<24;i++)
  {
   if (gt[i]>lt[i])
   {
       uno1.write( "100");
       uno2.write( "100");
       uno3.write( "100");
       digitalWrite(Pvpin,HIGH);
   }
   else if (gt[i]+BatCap[i]>lt[i])
   {
       uno1.write( "110");
       uno2.write( "110");
       uno3.write( "110");
       digitalWrite(Batpin,HIGH);
       digitalWrite(Pvpin,HIGH);
   }
   else
   {
       uno1.write( "001");
       uno2.write( "001");
       uno3.write( "001");
       digitalWrite(Gridpin,HIGH);
   }
  }
}

```

# Answer
> 1 votes
If you want to use 3 `SoftwareSerial` instances, then you need to use 3 different sets of pins. Hence, replace:

```
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

```

with something like:

```
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX

```

Also, since `SoftwareSerial` and `Serial` (hardware) are interchangeable in code, you should take advantage of the hardware Serial of Arduino UNO:

```
HardwareSerial uno1 = Serial;

```

Note that, on UNO, `HardwareSerial` uses pins 0 and 1, hence you should not use these for something else:

```
HardwareSerial uno1 = Serial;
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX

```

---
Tags: arduino-uno, serial, arduino-mega, softwareserial
---


# Question
Title: Is setting AVR TWCR for mega328p TWEN in each function necessary?
I found this useful website explaining for to configure and implement the TWI for mega328p, but what I found not so obvious is that in the website they set TWEN in every function, while in the datasheet C code example, they only set it in START and STOP functions.

I also find another style in Arduino Wire library, that they implement more easier functions for starting and ending the module.

This is the website, could anyone take a look and tell me if setting TWEN in each function is necessary?

Also, is it necessary to check for TWINT after sending STOP command?

http://www.embedds.com/programming-avr-i2c-interface/

Regards,

# Answer
> 1 votes
The big difference is interrupt driven or busy wait implementation of the TWI hardware module protocol. Enabling interrupts is necessary in an interrupt driven implementation while busy wait should not enable interrupts.

A busy wait implementation is much simpler but it cannot be asynchronous. An interrupt driven implementation can be asynchronous and even power down the rest of the MCU during the TWI communication. It should be noted that the Arduino Wire class is interrupt driven but synchronous.

Cheers!

---
Tags: i2c, c, avr
---


title: ESP8266 unstable connection

text:
# Question
Title: ESP8266 unstable connection
I try to flash an ESP12E microcontroller through an FTDI serial converter. It seems like the UART connection is a bit unstable, because when I try to flash it via esptool it often throws "Timed out waiting for packet header" error. Also when I thy to get the flash\_id the same error occures at around 50% of the time. The simplier commands like get\_mac and chip\_id are working well.

I'm using an ESP module with wires soldered to its pads. It is put into a breadboard and it's connected to a USB-UART converter via jumper wires.

What could be the problem?

# Answer
Power supply...

I designed a pcb for the ESP module, it works like a charm since then. Used a TC1262 regulator, a 100n ceramic and a 1000u electrolyte capacitor (maybe 100u would have been enough) very close to the Vcc and GND pins.

Seems like the ESP is really sensitive to the power supply stability.
> 1 votes

---
Tags: esp8266, usb, uart
---


# Question
Title: How does Arduino WiFi Shield connect to Blynk and How can I use ESP Module to connect to blynk?
I was actually quite impressed how easily Blynk gets connected to Arduino. So I had a doubt how does Arduino WiFi Shield allow Arduino Uno to connect to blynk ? And my second doubt is how can I use the ESP boards to connect to blynk using Windows10 ( for steps ) ? Thank You.

# Answer
> 1 votes
> how does Arduino WiFi Shield allow Arduino Uno to connect to blynk

Blynk is just a web service. The WiFi shield connects your board to the internet and sends data to that web service. The Blynk app is just an interface to that web service.

> how can I use the ESP boards to connect to blynk using Windows10?

That makes no sense. You can connect an MCU to Blynk through something like an ESP8266 board (or program the ESP8266 board directly to communicate with Blynk). It is merely a network interface.

Windows 10 is not an MCU, and you already have an internet connection on it. If you want to communicate with Blynk from Windows 10 I suggest you look at the documents to see if there is an API you can use from your own programs, or a web interface you can view in your browser of choice.

Windows 10 and ESP8266 are two completely alien concepts.

---
Tags: esp8266, wifi
---


# Question
Title: How does ESP8266 work as web server with Arduino?
I am trying to learn internet of things with smart home. I will connect an ESP8266 and an Arduino with the IBM Bluemix server to control a circuit from a public IP.

I want to start with the local network for now. I have gone through a couple of links which seem like a great start http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/

They explain how it works, and have source code but no circuit diagram. How should I connect the ESP8266 with Arduino for this example ?

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266(rxPin,txPin);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
}

void loop() {
  Serial.println("Sending an AT commands");
  esp8266.println("AT");
  delay(30);
  while(esp8266.available()) {
    String data = esp8266.readStringUntil('\n');
    Serial.println("Got response from esp8266: " + data);
  }
}

```

# Answer
The exact same way as any other ESP8266 example. The fact that you are using it as a web server doesn't change how you wire it.

For that specific code snippet it even tells you in the comments:

```
// make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3

```
> 1 votes

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


# Question
Title: Waking up async the Arduino while it is sleeping periodically
I´m using `LowPower.h` and `PinChangeInt.h` libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with `LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF)` but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

```
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

```

Can anyone help me? Thanks

# Answer
> 1 votes
My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` then it could be awake using another interrupt instead of the timer.

The `void loop()` method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the `void setup ()` I´ve attached an interrupt using `PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);`

---

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.

---
Tags: interrupt, arduino-pro-mini
---


# Question
Title: Reading SD card with Sparkfun MP3 Shield
So I am using an Arduino Mega with the Sparkfun MP3 shield. And I can't seem to read the µSD card. It's formatted in FAT32 and it has a single .txt file on it. I always get this error:

```
SD initialization failed.
Do not reformat the card!
Is the card correctly inserted?
Is chipSelect set to the correct value?
Is there a wiring/soldering problem?
errorCode: 0x1, errorData: 0xff

```

I have tried chipSelect 8,9 and 10. I've seen all the other forum threads about the error but none apply here as it is a bought board and not self built, so the wiring should be correct. I've tried software that has ran on the same configuration, and I get the same error.

Thanks in advance,

Michidez

The code that I use to try the SD card (QuickStart, from the SdFat Library):

```
// Quick hardware test
#include <SdFat.h>
// Test with reduced SPI speed for breadboards.
// Change spiSpeed to SPI_FULL_SPEED for better performance
// Use SPI_QUARTER_SPEED for even slower SPI bus speed
const uint8_t spiSpeed = SPI_HALF_SPEED;
//------------------------------------------------------------------------------
// Normally SdFat is used in applications in place
// of Sd2Card, SdVolume, and SdFile for root.
Sd2Card card;
SdVolume volume;
SdFile root;

// Serial streams
ArduinoOutStream cout(Serial);

// input buffer for line
char cinBuf[40];
ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf));

// SD card chip select
int chipSelect;

void cardOrSpeed() {
  cout << pstr(
    "Try another SD card or reduce the SPI bus speed.\n"
    "The current SPI speed is: ");
  uint8_t divisor = 1;
  for (uint8_t i = 0; i < spiSpeed; i++) divisor *= 2;
  cout << F_CPU * 0.5e-6 / divisor << pstr(" MHz\n");
  cout << pstr("Edit spiSpeed in this sketch to change it.\n");
}

void reformatMsg() {
  cout << pstr("Try reformatting the card.  For best results use\n");
  cout << pstr("the SdFormatter sketch in SdFat/examples or download\n");
  cout << pstr("and use SDFormatter from www.sdcard.org/consumer.\n");
}

void setup() {
  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo

  cout << pstr(
    "\nSD chip select is the key hardware option.\n"
    "Common values are:\n"
    "Arduino Ethernet shield, pin 4\n"
    "Sparkfun SD shield, pin 8\n"
    "Adafruit SD shields and modules, pin 10\n");
}

bool firstTry = true;
void loop() {
  // read any existing Serial data
  while (Serial.read() >= 0) {}

  if (!firstTry) cout << pstr("\nRestarting\n");
  firstTry = false;

  cout << pstr("\nEnter the chip select pin number: ");
  cin.readline();
  if (cin >> chipSelect) {
    cout << chipSelect << endl;
  } else {
    cout << pstr("\nInvalid pin number\n");
    return;
  }
  if (!card.init(spiSpeed, chipSelect)) {
    cout << pstr(
      "\nSD initialization failed.\n"
      "Do not reformat the card!\n"
      "Is the card correctly inserted?\n"
      "Is chipSelect set to the correct value?\n"
      "Is there a wiring/soldering problem?\n");
    cout << pstr("errorCode: ") << hex << showbase << int(card.errorCode());
    cout << pstr(", errorData: ") << int(card.errorData());
    cout << dec << noshowbase << endl;
    return;
  }
  cout << pstr("\nCard successfully initialized.\n");
  cout << endl;

  uint32_t size = card.cardSize();
  if (size == 0) {
    cout << pstr("Can't determine the card size.\n");
    cardOrSpeed();
    return;
  }
  uint32_t sizeMB = 0.000512 * size + 0.5;
  cout << pstr("Card size: ") << sizeMB;
  cout << pstr(" MB (MB = 1,000,000 bytes)\n");
  cout << endl;

  if (!volume.init(&card)) {
    if (card.errorCode()) {
      cout << pstr("Can't read the card.\n");
      cardOrSpeed();
    } else {
      cout << pstr("Can't find a valid FAT16/FAT32 partition.\n");
      reformatMsg();
    }
    return;
  }
  cout << pstr("Volume is FAT") << int(volume.fatType());
  cout << pstr(", Cluster size (bytes): ") << 512L * volume.blocksPerCluster();
  cout << endl << endl;

  root.close();
  if (!root.openRoot(&volume)) {
    cout << pstr("Can't open root directory.\n");
    reformatMsg();
    return;
  }

cout << pstr("Files found (name date time size):\n");
  root.ls(LS_R | LS_DATE | LS_SIZE);

  if ((sizeMB > 1100 && volume.blocksPerCluster() < 64)
    || (sizeMB < 2200 && volume.fatType() == 32)) {
    cout << pstr("\nThis card should be reformatted for best performance.\n");
    cout << pstr("Use a cluster size of 32 KB for cards larger than 1 GB.\n");
    cout << pstr("Only cards larger than 2 GB should be formatted FAT32.\n");
    reformatMsg();
    return;
  }
  // read any existing Serial data
  while (Serial.read() >= 0) {}
  cout << pstr("\nSuccess!  Type any character to restart.\n");
  while (Serial.read() < 0) {}
}

```

# Answer
Firstly, where did you get the get the SdFat library from? A quick search on GitHub returned 34 results: GitHub search of SdFat. Of those, Greiman and Adafruit were the highest results on Google.

The reason I mention this is that you could be using a library that has issues or requires something specific in the hardware. I would suggest using the Adafruit version, as that would be the most scrutinized and hence the most stable. It appears very similar to the Arduino library (mentioned below).

Arduino has a SD library that comes with the Arduino IDE. It is simply called `SD`. There are 6 example programs:

* `CardInfo`: SD card test - This example shows how use the utility libraries on which the'SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not.
* `ReadWrite`: SD card read/write - shows how to read and write data to and from an SD card file.
* `Files`: SD card basic file example - shows how to create and destroy an SD card file.
* `ListFiles`: Listfiles - This example shows how print out the files in a directory on a SD card.
* `DumpFile`: SD card file dump - shows how to read a file from the SD card using the SD library and send it over the serial port.
* `Datalogger`: SD card datalogger - shows how to log data from three analog sensors.

Use the CardInfo example program to verify that your setup is correct. Then progress to one of the other examples such as `ListFiles` or `Dumpfile`.
> 1 votes

---
Tags: sd-card
---


# Question
Title: WiFi connections being lost on connection reset
Look at the trick in the last few lines of this code:

```
#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "yyyyyyy";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

 int delays = 0;

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
    delay(1);
    delays++;  // First line of trick.
    if (delays > 10) {
       return;
    } // Trick ends.
  }
  ...// Handle some events.
}

```

Code works ok without the trick (only `delay(1);` inside the loop), but the problem is it gets stucked there, if some responses are asked from browser so that tab is closed in between the requests.

One response is for favicon:

```
 if (req.indexOf("favicon.ico") != -1) {
    String s = "HTTP/1.1 404 WTF Favicon !!\r\n";
    client.print(s);
    client.flush();
    return;
 }

```

I had also one similar response starting with 200 OK for certain URLs and then a response of plain json text.

I would like to know why my server gets stucked on this `delay(1);`? Also, when the trick is needed, what is correct `delays` value?

Also I did add a `client.flush();` after every `client.print();`. May that affect anything?

# Answer
> 1 votes
WifiServer class has a bug that is now resolved. It causes a phenomenom described like follows:

> When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.

---
Tags: programming, esp8266, wifi, networking
---


# Question
Title: Can Atmel Studio 6 Simulator simulate SPI?
I am trying to do PAL composite video output with Arduino Nano. I am using Atmel Studio 6, not the Arduino IDE. I am sending out the picture data via SPI. On the TV I could not see the text I tried to produce, so I tried to run my program in the Atmel Studio simulator (to use it as a logic analyzer). But in the resulting stimuli file I also do not see the MOSI pin changing.

I am using the A0 pin (PORTC bit 0) to send out the sync signal, that appears correctly in the output .stim file: PORTC changes exactly at the right time. But PORTB does not change at all.

My program can definitely be buggy, but that is another topic... the question is, **can Atmel Studio Simulator simulate the SPI** at all?

# Answer
> 1 votes
No Atmel Studio cannot simulate SPI.

The fact that you are using SPI makes me think that you are using the MAX7456 IC or even the SparkFun On Screen Display Breakout which uses this same IC.

You can generate composite video just by using a few resistors and an Arduino.

I have found a number of sites on Google who have used the Arduino to output PAL composite video to display the Pong game on an old TV.

---
Tags: atmel-studio
---


# Question
Title: How to use ESP8266 for wireless communication?
I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.

# Answer
I'm not very clear on what you are asking but I think you are saying how do you connect an ESP8266 to an Arduino so the Arduino has wireless(WIFI) access.

I'm sure there are tutorials out there so I won't go in to detail (also I don't know the details), but hopefully you will get some better terms to search with.

The basic idea is you connect the serial connection of the ESP8266 to the serial of the Arduino (via a level shifter and connect Tx to Rx). You then write a series of AT commands to configure the ESP8266 so that what ever is receives over the serial it sends to a TCP endpoint via WIFI (and what it receives is sent to serial).

You can program the ESP via the Arduino IDE, so you could write a 'smarter' version that did all the setup for you, etc. In fact since the ESP8266 is a faster processor with more RAM you could do a lot more on it.

If you are using an UNO or Nano you might want to look at the software serial library to let you keep the main serial port for debug messages. If you are using a Mega then you can use one of the secondary serial ports.
> 2 votes

# Answer
You follow the instructions from blynk.cc/getting-started which include quite simple steps:

> 1 create auth id
>
> 2 download and install blynk library
>
> 3 replace auth id in some example you can find from arduino ide
>
> 4 run code

More details from tutorial.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Can I make existing libraries use external SRAM for the Arduino
I am running out of memory on my Arduino due to the libraries I am using. After I have included all the libraries I need then there is very little in the way of free memory for my own code.

If hook up some external RAM to the Arduino, is there a way I can make existing libraries use the external RAM rather than the SRAM on the arduino or will I need to alter the code in the library to do it.

If I have to modify the code is that a relatively easy thing to do?

# Answer
> 3 votes
> What did programmers do back in the 80-ies when they run out of memory?

There is an old technique called overlays. The same area of memory is used for different phases/steps of a program. Results are naturally saved but any intermediate data is discharged before the next phase/step which reuses the "common" area of memory. Necessary state may be saved to an external storage between execution of the phase/step to increase available local memory.

To compile and link this you have to do some deep diving into the manual and read up on memory sections.

It is possible to abstract this using C++ smart pointers but getting existing libraries to use it will be a very tough challenge. There are a few attempts to support virtual memory such as virtmem.

Cheers!

# Answer
> 4 votes
Making a library use external SRAM is not an easy task. It *can* be cone, but it takes quite a bit of work.

The best start would be to abstract the SRAM into a library that provides simple access to it. Then you would need to use that new library to read and write data in the SRAM instead of accessing variables in the other libraries.

There is no way of simply mapping a variable into external SRAM - for that you need a microcontroller with an MMU and/or an EIB.

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


# Question
Title: Distance Readings Getting Manipulated When Calling Unrelated Function
I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.

To describe exactly what I mean, this is my function:

```
int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
Serial.println(distanceConverted); // Print the distance

```

and it gives me an output of this (which is correct):

```
780 cm
787 cm
790 cm
794 cm
782 cm
787 cm
790 cm
786 cm
790 cm
780 cm
788 cm
784 cm

```

I'm using these distances to control LED lights and a speaker, and call this function to do so:

```
void lights(int distanceConverted)
{
    if (distanceConverted < 1000 && distanceConverted > 500)
    {
      digitalWrite(yellowLEDPin, HIGH);
      delay(20);
      tone(8, 35000, 250);
    }

    else if (distanceConverted <= 500)
    {
      digitalWrite(redLEDPin, HIGH);
      delay(20);
      tone(8, 40000, 250);
    }
}

```

However, when this is called (and I call the function after I print the distance values), these are the results I get:

```
268 cm
267 cm
266 cm
267 cm
269 cm
267 cm
265 cm
267 cm
266 cm
266 cm
267 cm
264 cm
269 cm

```

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:

```
int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

New Values:
2640 cm
2673 cm
2634 cm
2649 cm
2592 cm
2619 cm
2631 cm
2628 cm
2631 cm
2673 cm
2634 cm

```

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.

Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.

```
761 cm <- first value from sensor, correct
312 cm
308 cm
308 cm
309 cm
308 cm
307 cm
307 cm
309 cm
308 cm
308 cm

```

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?

# Answer
The tone function uses timer interrupts to toggle a GPIO pin to make noise. That's quite intense from a CPU point of view and is most likely skewing the timing of the pulseIn function.

I would suggest not using tone if you can help it. Maybe change the frequency of a PWM output to something suitable and use analowWrite to create a 50% duty square wave.

Also learning how to use the Input Capture peripheral of the MCU (read the datasheet) will enable you to perform asynchronous sampling of your pulses and obtain much more accurate results.
> 0 votes

---
Tags: arduino-mega, sensors
---


# Question
Title: Fingerprint sensor code won't work correctly with LCD 16x2
I am doing a fingerprint sensor that works with a 16x2 LCD. The code works correctly for the fingerprint sensor, but when I enter LCD code, the LCD works but the fingerprint stops working.

I am using an Arduino Uno and an Adafruit fingerprint sensor. Both the fingerprint and LCD are wired correctly and work separately. I have enrolled and tested fingerprints and it worked perfectly until I added LCD code.

```
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int getFingerprintIDez();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup() {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
  Serial.begin(9600);
  Serial.println("fingertest");
  // set the data rate for the sensor serial port
  finger.begin(57600);
  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1);
  }
  Serial.println("Waiting for valid finger...");
}

void loop() {
  getFingerprintIDez();
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
   Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  // found a match!
  Serial.print("Found ID #");
  Serial.println(finger.fingerID);
  Serial.print("This Finger print related to : ");
  switch(finger.fingerID){
   case 0:
     Serial.println("Subhy Mesmar");
     break;
   case 1 :
     Serial.println("Amjad Mesmar");
     break;
  }
  return finger.fingerID;
}

```

In this image the fingerprint sensor works without LCD code:

And in this one the LCD works after adding code but the fingerprint sensor stopped working:

# Answer
> 3 votes
You have pins 2 and 3 used by both the LCD and the SoftwareSerial used for the fingerprint sensor.

Use different pins for one or the other.

Worth looking at the Software Serial reference to understand more about how it works.

---
Tags: arduino-uno, lcd, adafruit
---


title: Nested for loop errors

text:
# Question
Title: Nested for loop errors
Ok, I am trying to make 2 LEDs run at two different speeds.

Here is the code I am using:

```
void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
}

for ( ; ; ) {
  for ( ; ; ) {
   digitalWrite(12, HIGH);
   delay(250);
   digitalWrite(12, LOW);
   delay(250);
  }
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
}

```

This code unfortunately returns this error:

```
error: expected unqualified-id before 'for'
 for ( ; ; ) {

```

Thanks for the help!

# Answer
> 0 votes
As Majenko's comments are suggesting you're missing the `loop` function here - which is not just eye candy but essential. It is the basic structure of the sketches to have two methods on the highest (user accessible) level: `void setup()` and `void loop()`. `setup` is run exactly once at the beginning of your program. Following that `loop` is looped (hence the name) forever.

This is what it should look like:

```
void setup() {
  // doing the setup
}

void loop() {
    for ( ; ; ) {
        for ( ; ; ) {
            // something
        }
        // something else
    }
}

```

However (and again Majenko's comment hints it) `something else` is never going to be executed as the inner loop is never exited. This tutorial (per Majenko's comment) should get you started. See also: www.arduino.cc with many more tutorials worth studying.

# Answer
> 0 votes
First of all your question is so basic it means you didn't spend any time to look any example out there, not even after Majenko has clearly pointed out you can find the answer to your question in the many examples out there.

Once that is clear here follow the code you are looking for, but using it as it is without knowing what you are doing is not going to help you. Not to mention not many will be willing to help somebody with the attitude you are demonstrating.

```
#define LED_1 5
#define LED_2 6

void setup() {
  pinMode(LED_1, OUTPUT);
  pinMode(LED_2, OUTPUT);
}

long one, two;
bool led_1, led_2;

void loop() {
  if (millis() - one >= 250) {
    digitalWrite(LED_1, led_1++);
    one = millis();
  }

  if (millis() - two >= 500) {
    digitalWrite(LED_2, led_2++);
    two = millis();
  }
}

```

# Answer
> 0 votes
You have a compiler error because you have executable code outside a function. In particular your first "for" loop.

Second, an infinite loop inside an infinite loop is not particularly useful.

> so how do I make it run both at the same time?

Ah yes, well unless you have multiple CPUs you don't run multiple things "at the same time". You do one thing, and then another thing.

I have an article about this general idea here:

http://www.gammon.com.au/blink

To save having to necessarily go to that link, here is an example from that page which blinks two LEDs at different rates:

```
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

```

In that code, in the main loop, the code uses `millis()` to find the current time, and if sufficient time has elapsed it does something useful. As an analogy, when you are cooking dinner you look at the clock from time to time, and if sufficient time has elapsed since you started cooking, you take the roast from the oven and eat it.

---
Tags: arduino-uno
---


title: Auto Reset during programming Arduino

text:
# Question
Title: Auto Reset during programming Arduino
I know this that when you try to program a pro mini without a DTR pin it will give you a error as the atmega needs to be reset during programming. So I had a doubt why does the microcontroller needs to be reset and clearly at which time you know at which moment does it reset ?

# Answer
> 4 votes
A Reset is necessary to activate the Bootloader and allow programming. Without the DTR signal the Reset button has to be pressed just before starting the upload from the Arduino IDE.

---
Tags: arduino-pro-mini, reset
---


# Question
Title: How to create jumping wire using fritzing tool
I am tying to design my circuit diagram with the help of http://fritzing.org/home/ I designed like below circuit where wires are simply straight.

I want some kinda jumping wires with this tool. Does anyone know how to create these jumping wires ?

# Answer
1. Draw the wires
2. press and hold control button (mouse pointer will appear with a curve symbol)
3. drag the wire using mouse
> 5 votes

---
Tags: arduino-uno
---


title: Building Custom Bootloaders

text:
# Question
Title: Building Custom Bootloaders
Recently I was checking out the Atmel's AVR series and I found the Atmega328PB. I am really familiar with Arduino's environment. So I thought if somehow we could bootloader it with Arduino bootloader. My doubt is how can I make a Arduino bootloader for it.

# Answer
> 2 votes
Here are a couple sources of ATmega328PB bootloaders based on optiboot:

I haven't used either. If you are set on making your own at least they can provide you with a reference.

---
Tags: bootloader, avr
---


# Question
Title: Can I cut the pin holes off of my Arduino board?
I'm making a project, but my arduino pro micro is just slightly too big to fit in it's case.

What would happen if I cut off the pin holes that I don't need? Would it still work? Or would it be ruined?

# Answer
> 1 votes
I guess that one *could* cut (or hone down) parts of the PCB. Obviosly this process devoids the warranty and there is the risk of damaging either the board or some components on it (i.e. by holding or clamping it during the process).

I would not expect any other wiring besides those connecting the pins to run in this part of the PCB. The reference layout (see board layout and using Eagle (free version)) - if the clones follow that layout - confirms that there are no other traces there. So it is mostly important to not cut any other traces and remove any chippings after the cutting to avoid short circuits.

If in doubt buy two or three boards ;) to try and repeat the process.

# Answer
> 1 votes
Rather than trying to modify the board (which I think is a bad idea) why not use a `Pro Mini`.

These are smaller (and cheaper), and almost identical in function, apart from the USB interface. You do need a serial interface (or ICSP) to program.

# Answer
> 0 votes
This is a bad ideas:

* the PCB is made of fiber glass which, when broken, cut or filed, produces a very fine powder; any powder you might breath in during the process wil stay in lungs for a very long time, in the order of decades
* the risk of cracking traces running close to the are of cut, even if they are not directly being cut, is pretty high; the copper traces rely on the fiberglass rigidity, but a crack in the fiberglass propagating under the traces is welcoming a broken trace

Go for a different case, if that's not a viable option go for a barebone arduino. If that is also a non viable option consider the idea of producing a few custom PCBs: they are not that expensive!

# Answer
> 0 votes
You could use a Pro Mini as Milliways suggested, but you don't necessarily need a USB interface to programme it. You can use your Arduino UNO to directly programme the Arduino Pro Mini.

---
Tags: pins, arduino-micro
---


# Question
Title: Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?
I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads here. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

# Answer
> 1 votes
NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.

# Answer
> 1 votes
I went through almost the exact same thing you are going through when I was looking at the ESP8266 boards (the NodeMCU is one of those). I too discovered that the NodeMCU is a micro computer in itself, even more powerful than the Arduino UNO!

You can even code the NodeMCU using the Arduino IDE. As has been said previously, I'd use your NodeMCU directly to accomplish what you want to do.

---
Tags: arduino-mega, esp8266, nodemcu
---


# Question
Title: Mega SPI communication changing between setup and loop
I am attempting to use an arduino MEGA 2560 to control a digital potentiometer (AD5206), but I am getting some strange behavior. I have attached the CLK and MOSI pins (52 and 51, respectively) to an oscilloscope, and have run the following code:

```
#include <SPI.h>
void setup() {
    SPI.begin();
    SPI.transfer(5);
    delay(500);
}

void loop() {
    SPI.transfer(5);
    delay(500);
}

```

When I look at the signal, the transfer in the setup() looks correct (5V x 00000011), but then the transfer in the loop() looks like it's shifted by -5V (-5V x 11111100). Has anyone ever run into this? Is it possible for the MEGA to output a negative voltage?

# Answer
No, there is no problem with SPI on the Mega. If there were it would have been noticed by now.

Instead it's either the way you are measuring it or your method of generating the SPI signals that are at fault (and since you won't show us your *real* code we can't help you with that).

This is a trace of your provided "code" with the delays reduced to allow easier fitting on a single trace:

Clock goes low when `SPI.begin()` is called. Then there are the successive transfers - the first being in `setup()` and the rest in `loop()`. As you can see they are all identical.
> 1 votes

---
Tags: arduino-mega, spi
---


title: Testing an oscilloscope with my Arduino

text:
# Question
Title: Testing an oscilloscope with my Arduino
I bought a very old oscilloscope and although it works, I have my doubts about refreshing the screen (the electron beam fades away very slowly or is not showing up consistently across the screen).

I tested a bit with `digitalWrite` and `anlogWrite`, but this only sends either 0 or 5V out. Is there a way to make a preferably sine or triangle wave of 0 to 5V or -5 to +5V... I guess the Arduino should be capable of it, but so far I only get 0V or 5V out, nothing in between.

According to lesson 8 I should get a variable voltage of 0-5V on a pin with `analogWrite`, but all I get is 0 or 5V.

For what I see:

1. PWM gives with `analogWrite` a pulse signal of 0V or 5V with a duty cycle.
2. non PWM pins give either 0V or 5V (`analogWrite` of 0-127 appr: 0V, \>127: 5V).

# Answer
> 2 votes
You can convert the PWM output of `analogWrite()` into an (approximate) analog voltage by adding a low-pass filter. That is, a resistor in series followed by a capacitor to ground.

The values to choose depend on the frequency response you want.

For anything more complex or accurate you will need a DAC. I often use the MCP4822 SPI DAC chip.

# Answer
> 1 votes
a few ways:

1) you can generate a square wave of a known frequency to test the time base of the scope;

2) you can generate an analog signal to test for the vertical. that can be done via pwm or dds.

---
Tags: arduino-uno, arduino-mega, wave
---


# Question
Title: Sending value from Arduino to MySQL using ESP8266
I am trying to send a value from Arduino to a remote MySQL. I am following this tutorial.

I have tried but no data is received on the server. What is the issue? I am new to Arduino. My code is:

```
int led1=8;
int count=1;
void setup() {
  pinMode(led1, OUTPUT);
  delay(3000);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);
  Serial.println("AT+CWMODE=1");
  delay(1000);
  Serial.println("AT+CWJAP=\"mhboys\",\"mhboys123\"");
  delay(1000);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led1,HIGH);
  // turn the LED on (HIGH is the voltage level)
  delay(1000);  // wait for a second
  if(digitalRead(led1)==LOW) {}
  if(digitalRead(led1)==HIGH) {
    count++;
    //code for sending updated count to mysql
  }
  digitalWrite(led1, LOW);
  // turn the LED off by making the voltage LOW
  delay(1000); // wait for a second
  int adjustedValue = count;
  // print out the value you read:
  Serial.println("AT+CIPSTART=\"TCP\",\"www.onemediagroup.in\",80");
  delay(1000);
  Serial.println("AT+CIPSEND=66");
  delay(1000);
  Serial.print("GET /energy/getUsage.php?currentValue=");
  Serial.print(adjustedValue);
  delay(1000);
  Serial.println("AT+CIPCLOSE");
  digitalWrite(13, HIGH);
  delay(100000); // delay in between reads for stability
}

```

# Answer
> 2 votes
You're sending commands blindly without checking if they actually succeeded. If you're not ready to correctly handle the responses, you're better off using a library like this. The 'HTTP GET' example should help.

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


# Question
Title: Problems with installing MIDI library in UECIDE
I installed UECIDE from Majenko but I couldn't register nor email him so I try it here.

When trying in install the MIDI library from 47 effects (https://github.com/FortySevenEffects/arduino\_midi\_library/releases/tag/4.3.1) I get the following error:

```
Compiling Failed
Analyzing Arduino_MIDI_Library_v4.3.1.zip ...
Unable to detect any valid libraries in the archive.
You may need to manually install it or re-package it properly.

```

How to solve this?

I tried install manually by copying files but that didn't result in anything.

# Answer
The auto-install method only (currently) works with old single-arch style libraries. This one is a new multi-arch style library (though it doesn't use the multi-arch facilities).

You need to install it manually. Simply that means extracting the zip file into "libraries" within your "UECIDE" folder in your documents (My Documents/UECIDE/libraries on Windows, or ~/Documents/UECIDE/libraries on Linux / OS X).

If UECIDE is open at the time you can use "Help -\> Debug -\> Rebuild internal structures" to re-scan the available libraries, or just close it and re-open it.
> 1 votes

---
Tags: uecide
---


# Question
Title: Calculate absolute time based on cycles and RTC
I'm developing a low power data logging device. It samples sensors at the frequency of 20Hz, and also has a real time clock for absolute time (the logged time need to be exact down to ms).

I think that querying time for every samples would be wasteful of energy. One solution is calculate time based on number of cycles, and after a fixed duration (10 minutes) query RTC to update the time.

Here is my attempt:

```
#define INTERVAL 12000 //10 minutes: 10*60*20 samples

int count = 0;
int checkPointMillis;
int checkPointRTC;

// timer interrupt at 20Hz
ISR() {
    int a = analogRead(A0);
    int time = millis() - checkPointMillis + checkPointRTC;

    // write data to a buffer

    if (count > INTERVAL) {
        count = 0;
        checkPointMillis = millis();
        checkPointRTC = getRTCTime();
    }
}

```

Is this a correct approach?

# Answer
In general, the idea is sound. But there are problems with some of the details and tuning.

The most important detail: Use the correct data type for storing and computing with time variables (like `time`, `checkPointMillis` and `checkPointRTC`). The correct data type is `unsigned long` (or, equivalently, `unsigned long int` or `uint32_t`).

A second detail: Rather than storing your calibration correction in two variables which you always use as a difference (in effect, `checkPointRTC-checkPointMillis`) just compute and store the difference. For example:

```
...
unsigned long clockCorrection;
...
unsigned long time = millis() - clockCorrection;
...
clockCorrection = getRTCTime() - checkPointMillis;

```

This will save a few bytes of RAM and a few cycles of computation.

A third detail: If outside of the ISR you will need to access any of the values computed in the ISR, declared their variables `volatile`. Example:

```
volatile unsigned long time;

```

Fourth: If `getRTCTime()` or any of your sensor-reading code use interrupts, you will need to move such code out of the “timer interrupt at 20Hz” section, into (for example) `loop()`, triggered by a volatile variable going true. \[That's the model under which the balance of this answer was conceived; I overlooked, at first, the “timer interrupt at 20Hz” label.\] Note that `millis()` itself does not use interrupts. But if your 20-Hz ISR runs longer than a millisecond, the `millis()` total will drop one millisecond per millisecond of additional ISR time.

By tuning, I refer to the number of measurement intervals to wait between recomputing the clock correction. Under reasonable assumptions, the number of compute cycles is so closely the same with a one second interval versus a ten minute interval, that one probably should use only a second (or at the outside, a minute) interval between clock correction computes.

For example, suppose the total number of cycles awake per second is given by the following equation:

> a = 20\*s + 1000\*t + k * r

where *s* is the number of cycles used per sensor-set reading and recording; *t* is the number of cycles used per clock interrupt; *k* is the number of clock correction computes per second; and *r* is the number of cycles used per clock correction compute.

For example, if *s* is 2000, *t* is 100, and *r* is 200, the equation becomes

> a = 20\*2000 + 1000\*100 + k * 200 = 140000 + k * 200

Now consider three cases: *k* equal to 20, or 1, or 1/600, corresponding to a clock correction compute 20 times per second, or once a second, or every 10 minutes:

```
   k           a
  20        144000
   1        144200
1/600       144000.3

```

As you can see, under the assumptions *s* is 2000, *t* is 100, and *r* is 200, there is no compelling reason to prefer 1/600 corrections per second to one correction per second.

If your RTC can be read reliably and quickly, reading it either every time (ie 20 per second) or every second has other advantages: you compensate more quickly for MCU clock drift (ie, every second, rather than every 10 minutes) and strongly decrease the risk of out-of-order times.

For example, if your MCU clock drifts 2 seconds fast per 10 minutes, readings taken during the first two seconds of each new 10-minute interval would show smaller times than those taken during the last two seconds of the previous interval. With secondly corrections, no such non-monotonic readings will occur.

Here is a slightly more correct analysis of the 2 seconds fast per 10 minutes case: 2 seconds error in 600 seconds is 3.33 milliseconds per second. With sensor readings 50 milliseconds apart, and corrected clock readings not more than 3.33 milliseconds out of whack, non-monotonicity won't occur. However, this does not meet the “logged time needs to be exact down to ms” criterion. To meet that, drift of more than a half millisecond must be prevented. That requires drift correction at least 6.67 times per second. You could accomplish that by making a clock correction compute at every third sensor cycle.

It should be clear from the example calculations of awake cycles that the major contributor to the count is ISR cycles, here taken as 100\*1000, or 100000 cycles per second. You could set up timer 1 to interrupt 20 times per second and turn timer 0 off (which would disable `millis()` and require a different `time = ...` formula). If each timer 1 interrupt took 1000 cycles, that would contribute 20000 cycles instead of 100000 per second.

*Edit 4:* As I noted in a comment to Edgar Bonet's answer, one can change the TOP value used for timer interrupts, to control interrupt rate with better resolution than can be obtained by merely subtracting base values.

According to Gerben's comment, “`getRTCTime` only has 1sec resolution”. As I haven't seen any code for your `getRTCTime()` I don't know if that is true or not; but if so, here is another approach for time-rate correction:

> • At some beginning point coincident with an RTC seconds-change, record `millis()` and an RTC reading, in eg `millibase` and `RTCbase`.
> • At some interval (eg, 10 seconds or a minute, in each case coincident with an RTC seconds-change) measure `millis()` and an RTC reading, in eg `millinow` and `RTCnow`. Compute `RTCdeltaK` as the number of milliseconds from `RTCbase` to `RTCnow`. Compute `millidelta` as `millinow-millibase`.
> • Whenever elapsed time in milliseconds is needed, compute `elapsedms = ((millis()-millibase)*RTCdeltaK)/millidelta`.

The above is an algorithm, and may need some adjustment before use as an implementation. First, the `elapsedms` calculation can be arranged to avoid division, using a scaled multiplicative factor based on `millidelta`, `RTCdeltaK`, and some powers of 2. Secondly, relatively constant clock drift is assumed. If that assumption is incorrect, an average ratio with exponential decay could be used, instead of just a factor equivalent to `RTCdeltaK/millidelta`.
> 3 votes

# Answer
Yours is a classical problem of *clock synchronization*. You have a software clock (your program's idea of the current time) which you want to keep in sync with a reference hardware clock (the RTC). This is typically achieved by using a phase-locked loop, or PLL. It works as follows:

* you measure the difference between your software clock's time and the reference time
* you adjust your software clock based on this measurement.

This is essentially what you are already doing, except that you are fixing your clock by stepping it abruptly, whereas a PLL would usually slew the clock to get it in sync progressively.

Stepping the clock has some undesirable effects: it makes the time discontinuous and, more annoyingly, it can make it non-monotonic. I would thus recommend you try to slew your clock instead.

Here is the approach I would try if I were in your shoes. I am assuming you are using an Arduino Uno, or a similar AVR-based board with a 16-bit Timer 1:

* configure Timer 1 in mode 4: CTC mode with TOP = OCR1A
* set the prescaler to 64 and OCR1A = 12499 in order to get a period of 50 ms; TIMER1\_COMPA\_vect will be your data gathering interrupt
* configure your RTC to generate a 1 Hz output, and route this signal to the input capture pin ICP1 (pin 8 on the Uno)
* run the PLL logic inside TIMER1\_CAPT\_vect.

Since the RTC's 1 Hz period is a multiple of the timer period, you would expect the timer's input capture unit to always capture the same value. The difference between two consecutive captured values is thus a direct measure of your clock's drift in units of 4 ppm (4 µs/s). The ISR would be basically along these lines:

```
ISR(TIMER1_CAPT_vect)
{
    static uint16_t last_capture;
    uint16_t this_capture = ICR1;
    int16_t drift = this_capture - last_capture;
    last_capture = this_capture;

    // Reduce the drift modulo 12500 into [-6250, +6250).
    if (drift >= 6250) drift -= 12500;
    if (drift < -6250) drift += 12500;

    tune_clock(drift);
}

```

where `tune_clock()` is your PLL algorithm responsible for slewing the software clock.

Pay attention to the signedness of the variables. The subtraction of the captured values should be done with unsigned numbers, *then* the result should be made signed.

---

**Edit**: as suggested by James Waldby, I'll give here some suggestions on the implementation of the PLL. It turns out it is not so simple: *measuring* a clock drift is easy, *predicting* it is harder.

Let me restate the problem. You have a “good” clock: the RTC 1 Hz signal, assumed to be perfect, but with a limited resolution of one second. And you have a “bad” clock: Timer 1, which has a 4 µs resolution but suffers from frequency inaccuracy, instability and sensitivity to temperature and supply voltage. You want to combine both clocks into a software clock which tracks the good clock yet has the superior resolution of the bad clock.

I will use the following notations:

* t is the time from the reference clock (the RTC), assumed to be also the physical time
* n = ⌊t⌋ is the integer part of t, which is also the time when we last got an update from the RTC (a timer capture event)
* t′ is the time from the local clock (the Arduino timers)
* x = t′ − t is the local clock offset, measured by the ISR above at integer values of t; the physical time is given by t = t′ − x
* y = dx/dt is the local clock drift rate; it's a dimensionless quantity and typically less than 10−3 (i.e. less than 1 ms/s)
* xe(t) is the estimate, made by the software, of the offset x(t)
* ye(t) = dxe/dt is the estimate of the drift rate y(t)
* te = t′ − xe(te) is our software clock: a self-consistent estimate of t

The simplest solution, which is equivalent to the one you have in your question, is to assume x stays constant until it is updated. Thus

xe(t) = x(n)
te = t′ − x(n)

In other words, we are just correcting for the last known offset. The problem is, as stated before, that this gives a discontinuous time scale.

A better solution is to try to *predict* x(n+1), and linearly interpolate between our previous and our current prediction, thus building a continuous piecewise linear estimate of x:

xe(t) = xe(n) + (t−n)ye(n+½), where ye(n+½) = xe(n+1) − xe(n)

From this, the estimated time can be solved for as:

te = n + (t′−xe(n)−n)/(1+ye(n+½)) ≈ n + (t′−xe(n)−n)⋅(1−ye(n+½))

The factor 1/(1+ye(n+½)) ≈ (1−ye(n+½)) accounts for the fact that the clock has drifted since the last update at t = n.

Now we are left with the problem of predicting x(n+1). There are many possible approaches, and I will try to describe only a few.

## Simple PLL

One simple approach is to simulate an analog PLL with a first order low-pass filter. Here is the first illustration of the Wikipedia article on phase-locked loop:

Some translation is needed between this analog picture and the digital domain: The phase comparator takes the difference between the measured offset x(n) and our previous prediction xe(n). The low pass filter is implemented as an exponentially weighted moving average. The output of the filter is our estimate of the drift rate: ye. The VCO is the formula for estimating te, which has the built-in drift rate −ye. This could be translated to C++ roughly along these lines:

```
struct {
    uint32_t n;  // time of last update
    float xe;    // estimate of offset at time n
    float ye;    // estimate of drift rate for t in [n ,n+1]
} clock;

const float tau = 60;  // low-pass filter time constant, in seconds
const float K = 1;     // DC gain of the filter
const float alpha = 1/(1+tau);

// Called by the ISR.
// y is (x[now] - x[1 second ago]) in units of 4 us.
void tune_clock(int16_t y)
{
    static float x;   // last known offset
    x += y * 4e-6;    // update known offset
    float xe = clock.xe + clock.ye;  // estimate of current offset

    // Update time.
    clock.n++;

    // Update our estimate of the drift rate.
    clock.ye += alpha*(K*(x-xe) - clock.ye);

    // Update or estimate of the offset.
    clock.xe = xe;
}

// Estimate the current time.
float time()
{
    float t_local = micros() * 1e-6;
    return clock.n + (t_local - clock.xe - clock.n) * (1 - clock.ye);
}

```

Note that the code above is only meant as a guide. A good implementation should use fixed-point instead of floats and should also be rollover-safe.

The time constant of the filter should be chosen large enough to smooth out the jitter caused by the 4 µs resolution, yet short enough to closely track the frequency variations of the local clock. Ideally, it should be close to the Allan intercept of the x(n) time series.

This kind of PLL normally does a good job at tracking the reference clock, but it has one drawback: it tends to carry a systematic offset. Let's assume, for simplicity, that the drift rate is constant. Then it can be easily seen that the steady state of the PLL carries an offset error:

te − t = x − xe = y/K

where K is the DC gain of the filter. A large gain minimizes this error, but it does so at the expense of stability. Too large a DC gain and the PLL will spontaneously go into large oscillations.

I assume it should be possible to get rid of this systematic bias by using more sophisticated filters, maybe something like a PID, but I do not want to dive into the complexities of such filters.

## Simple linear extrapolation

Another way of estimating x(n+1), which does not suffer from systematic bias, is to linearly extrapolate from the two last known values:

xe(n+1) = 2 x(n) − x(n−1)

This means we assume that the drift rate is constant on this short time scale. The problem with this method is that it tends to amplify the fluctuations due to the jitter. Assuming for example an (overoptimistic) drift rate of 2 ppm, the measured offset will alternate between having zero and 4 µs increments. The extrapolation will predict every zero increment to be followed by another zero increment, and every 4 µs increment to be followed by another 4 µs increment, and thus it will always be wrong. The time evolution would look as follows:

```
t[s]    0   1   2   3   4   5   6   7   8   9  10
x[µs]   0   0   4   4   8   8  12  12  16  16  20
xₑ[µs]  0   0   0   8   4  12   8  16  12  20  16

```

## Brown's linear exponential smoothing

Brown's method is one of many linear extrapolation methods meant to smooth-out noise in the data. It is based on running *twice* the same low-pass filter on the input data:

```
s1 = low_pass(x)   // first smoothing
s2 = low_pass(s1)  // second smoothing

```

If τ is the time constant of the filter, then s1 is an average of data which has, *on average* the age τ, whereas s2 has the age 2τ. When can then, at time t, do a linear extrapolation by running a straight line through the points (t−τ, s1) and (t−2τ, s2). This gives the following algorithm for updating the estimates of the offset and the drift rate:

```
static float s1, s2;      // x smoothed once and twice
s1 += alpha * (x - s1);   // update s1
s2 += alpha * (s1 - s2);  // update s2

// Update or estimate of the offset.
clock.xe = xe;

// Extrapolate to estimate next offset.
xe = s1 + (s1-s2)*(tau+1)/tau;

// Update our estimate of the drift rate.
clock.ye = xe - clock.xe;

```

Here again, the optimal time constant should be of the order of the Allan intercept. Note that the limit τ → 0 gives the simple extrapolation of the previous section.

The figure below shows the performance of this algorithm on simulated data. The simulated clock has a drift rate oscillating between 1.7 and 2.3 ppm, and its measured offset is rounded to the closest multiple of 4 µs. The line labeled “predicted (τ = 0)” is the simple extrapolation of the previous section:

Here, the large jitter of the simple extrapolation method is quite obvious. On this simulated data, Brown's method works well with a time constant on the order of 5 s. The frequency of a real clock would change much more slowly, and a longer time constant would work better.

Now, all this is probably too general for your particular use case. I didn't know when I started this edit it would lead me so far... If you can tolerate more than, say, 10 µs of jitter, then the simple extrapolation should be good enough. And if you only need the time at t′-periodic intervals, this may enable some optimizations.
> 2 votes

# Answer
If you are using a RTC a far better solution to use alarms.

I use `TimeAlarms` for this purpose

```
#include <Time.h>        //http://www.arduino.cc/playground/Code/Time
#include <Timezone.h>    //https://github.com/JChristensen/Timezone
#include <TimeAlarms.h> //  Time alarms for use with Time library
#include <DS1307RTC.h>   //http://www.arduino.cc/playground/Code/Time returns time as a time_t

```

then include code to do something. The following waits for the Minutes to rollover, then calls function `Repeats` every 30 seconds etc

```
const int SampleRate = 30;  // seconds >1

  Alarm.waitMinuteRollover();
  Alarm.timerRepeat(SampleRate, Repeats);           // timer for every SampleRate seconds
  Alarm.alarmRepeat(alarmTime, rolloverLogFile);    // alarm to rollover LogFile (daily)

```
> 1 votes

---
Tags: timers, time, rtc
---


title: Where is Arduino on Fedora?

text:
# Question
Title: Where is Arduino on Fedora?
I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

# Answer
> 1 votes
It depends how you installed it.

If you downloaded the tarball and extracted it then it's wherever you extracted it.

If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.

If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in `~/.arduino15`

# Answer
> 0 votes
Assuming you have installed the tool from the Fedora repositories (that is, using yum/dnf or from the Software tool), the command to run the IDE will be installed at `/usr/bin/arduino` and you can run it from the command line just by typing `arduino` — or do the same in the search box in GNOME Shell.

Most of the package itself, including examples and libraries, will be installed under `/usr/share/arduino`.

And, once you run that program, it will create a new "sketchbook location" at `~/Arduino` — that is, a folder named "Arduino" in your home directory. If you've run the IDE already, that folder will already exist.

---
Tags: arduino-ide, teensy, linux, fedora
---


title: "No Socket available" for WiFiClient

text:
# Question
Title: "No Socket available" for WiFiClient
I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out `No Socket available`.

Any help will be appreciated; code below.

```
#include <SPI.h>
#include <WiFi.h>

int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;

char server[] = "www.example.com";
int value;

void setup() {
  Serial.begin(9600);
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  connectWifi();
  printWifiStatus();
  // postData();
}

void loop() {
  value = analogRead(LDR);
  postData();

  delay(10000);
}

void connectWifi() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
    delay(500);
  }
}

void printWifiStatus() {
  // Print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // Print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void postData() {
  WiFiClient client;
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    if (value > 350) {
      Serial.println("0");
      digitalWrite(LED, LOW);
      String data = "value=0";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    } else {
      Serial.println("1");
      digitalWrite(LED, HIGH);
      String data = "value=1";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    }
  } else {
    Serial.println("Connection failed");
    client.stop();
  }

}

```

Output:

```
Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available

```

Actual web address omitted.

# Answer
> 2 votes
I guess you have commented the command: //client.stop();

If you allow it, I guess you will have your code running

---
Tags: arduino-uno, wifi
---


# Question
Title: Should I use motor driver or Motor driver shield?
I want to run 4 microgear motor for an RC car with Arduino. Should I use L293d motor driver/L298n motor driver/L293d motor driver shield?? I am using N20 microgear motor with following rating: 6 V, 200 RPM and 120 mA with no load, 40 oz-in (2.9 kg-cm) and 1.6 A at stall.

# Answer
> 4 votes
The right driver module or shield depends on the motor. Do you know the voltage and the stall current of the motors ?

The L293D uses bipolar transistors for the output stage inside the chip and can only drive 600mA. It has a large voltage drop: the motor gets less voltage than the power voltage applied to the driver. Therefor it can be used with small 12V motors, but it does not work very well with 6V. The L298N also uses bipolar transistors and also has a large voltage drop. A mosfet driver like the DRV8833 works better with 6V, because it has a low voltage drop.

In small RC toys with four AA batteries, sometimes a H-bridge is made is transistors instead of using a special driver chip.

The very cheap motor shield with two L293D chips (originally designed by Adafruit) can drive four motors, but it uses many pins.

Bottom line: Everything depends on your motors. I suggest to use a mosfet driver.

# Answer
> 3 votes
The key differences between the L293D and the L298 are these:

* the L298 supports higher currents (up to 4 A with proper heat sink), the L293D is limited to 600 mA
* the L298 has a higher operating voltage (up to 46 V), the L293D is limited to 36 V
* the L298 is a dual full bridge driver whereas the L293D is a quadruple half bridge driver

Ok, what's the difference of two full bridges vs. four half bridges - it somehow sounds to be equal? In fact, when driving a DC motor that requires to reverse the polarity to reverse rotation a full bridge is required. This full bridge could now be provided by either of the L293D (two half bridges) or the L298 (one full bridge). If you on the other hand want to drive a four winding stepper motor (two phase bipolar) the L293D would be more helpful as it could drive two such steppers (using two separate half bridges) whereas the L298 would need to use both its full bridges and could therefore only operate one such stepper.

But since steppers are not part of this question this difference does not really matter and you could pick either chip with respect to the required current rating. A stall current of 1.6 A would be a serious problem for the L293D:

> Peak output current, I\_O (nonrepetitive, t ≤ 100 μs): 1.2 A

Whether to use the chip or a driver board or a shield, to be honest, is mainly personal preference. Shields and driver boards come ready-to-use on a pretty printed circuit board which is probably their main benefit.

---
Tags: motor
---


# Question
Title: How to arrange my code block to make it work smooth and correct
I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

* SOIL MOISTURE 2 PCS.
* WATER FLOW SENSOR 2 PCS.
* SOLENOID VALVE 2PS
* WATER LEVEL SENSOR 1 PCS.
* HUMIDITY SENSOR 1 PCS.
* REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..

Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..

```
#include <DS3231.h>

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14
#define WATERFLOW1 A13
#define WATERFLOW2 A12
#define HUMIDITY A11
#define RELAY1 9
#define RELAY2 8
#define ALARM 2

DS3231  rtc(SDA, SCL);
int DELAYNI = 1000;
void setup() {
  // put your setup code here, to run once:
pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(HUMIDITY, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

rtc.begin();

Serial.begin(9600);
}

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

  //Some Code here to get the data send by java app and then assign it to each variable

  readMoistureStatus();
  readWaterLevel();
}
void readWaterLevel(){
  ///Some code here
}

void readMoistureStatus(){

 int  moistureOneSensorValue = analogRead(MOISTURE1);
 int  moistureTwoSensorValue = analogRead(MOISTURE2);

   // checking the moisture range for the first soil moisture
  if(moistureOneSensorValue >= 700){
    // in case of dry soil:
    RelayOne();

     delay(DELAYNI);
  }
  if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureOneSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }
   //
   //
   // Checking the moisture range for the second soil moisture

  if(moistureTwoSensorValue >= 700){
    // in case of dry soil:
    RelayTwo();

     delay(DELAYNI);
  }
  if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureTwoSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }

}

void RelayOne(){
  //Close or Open the Solenoid

  //Read the water flow if the set point is reach it will close the solenoid using the relay
}

void RelayTwo(){
  //Close or Open the Solenoid

 //Read the water flow if the set point is reach it will close the solenoid using the relay
}

```

# Answer
I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec). Although there's nothing wrong in placing the

```
if(moistureOneSensorValue >= ...)
...
...

```

codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the `void loop()` itself and then place a `switch` case in the `doSomething()` function.

You can also use the data from the RTC to check moisture and do something:

```
void setup(){
...
time = DS3231.time(); //Time at the beginning
}

void loop(){

timeElapsed = now() - DS3231.time();//seconds elapsed

if (timeElapsed >= DELAYNI){
    moisture1 = analogRead(MOISTURE1); // Read ADC value
    moisture2 = analogRead(MOISTURE2); // Read ADC value
    updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
    switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
time = DS3231.time(); // Update the time

    }

}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: incompatible types in assignment of 'int*' to 'int [0]'
I was coding a class for "a kind of gun". I have this code for the classes:
*Gun.h:*

```
#ifndef Gun_h
#define Gun_h

#include "Arduino.h"

class Gun
{
  public:
    Gun(String identifier, String name, int teamIRCodes[]);
    String getIdentifier();
    String getName();
    int getIRCode();
  private:
    String _identifier;
    String _name;
    int _teamIRCodes[];
};

#endif

```

*Gun.cpp:*

```
#include "Arduino.h"
#include "Gun.h"

Gun::Gun(String identifier, String name, int teamIRCodes[])
{
  _identifier = identifier;
  _name = name;
  _teamIRCodes = teamIRCodes;
}

String Gun::getIdentifier(){
  return _identifier;
}
String Gun::getName(){
  return _name;
}
int Gun::getIRCode(){
  return _teamIRCodes[1];
}

```

It returns me this error while compiling:

```
sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

   _teamIRCodes = teamIRCodes;

                ^

exit status 1
incompatible types in assignment of 'int*' to 'int [0]'

```

# Answer
> 1 votes
The issue is with flexible array `int _teamIRCodes[];` This is an old technique which I don't recommend. But if you want to use it, you need you use `malloc` to create a class object, adding on enough space for the array:

```
// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

```

However, this does not call the ctor, and you still have to manually copy the data:

```
for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

```

I think it's much simpler to use a pointer:

```
int* _teamIRCodes;

```

Then you can make your ctor:

```
Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

```

And don' forget to add a dtor:

```
~Gun() {
    delete [] _teamIRCodes;
}

```

Or, if `teamIRCodes` is persistent throughout the lifetime of the object, you can just use a pointer to it:

```
 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

```

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).

# Answer
> 0 votes
Ok, using this worked:
Replace

```
_teamIRCodes = teamIRCodes;

```

For

```
for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
    _teamIRCodes[i] = teamIRCodes[i];

```

Needed to iterate through array, cannot copy full array.

---
Tags: library, class
---