# Question
Title: Writing analog voltages on analog pins of Arduino
Can we write a analog voltage to analog pins `A0`-`A7` of the Arduino Nano (for example)?

As in:

```
pinMode(A3, OUTPUT);
analogWrite(A3, 200);

```

# Answer
> 6 votes
No. The `analogWrite(pin, val)` function is reserved to PWM pins (`D3`, `D5`, `D6`, `D9`, `D10`, and `D11` in Arduino Nano). Pins marked as "ANALOG IN" on the board can work either as analog input (to the **A**nalog to **D**igital **C**onverter), digital input, or digital output.

It is worth to note that the Arduino Nano (and any other Arduino board I'm aware of) actually doesn't have any 'true' analog output port. When you use `analogWrite(pin, val)` you are actually telling the Arduino to output a PWM signal with the duty cicle specified by `val` (100% for `val = 255` and 0% for `val = 0`). If you actually do need a true analog output, you should consider using any form of analog lowpass filter at the specified PWM output port. Depending on how *clean* you want your signal to be, you could use a single capacitor or any other (a little more complex) filter.

If you don't know anything about filters, this could be a good starting point: ElectronicsTutorials - Passive Low Pass Filter

More insight about PWM in Arduino, here: EAS 199 - Basic Pulse Width Modulation

# Answer
> 1 votes
analogWrite are PWM digital pins. Analog pins on Nano are ADC read/input only (or digital I/O except A6 and A7).

# Answer
> 1 votes
All microcontrollers including Arduino are digital, and rely on specific circuit hardware in order to interface with the analog world. Two of these relate to your question:

* Analog-to-digital converters (ADCs) sample an analog voltage and output a number representing the voltage relative to the measurement range - such as 0 to 1023 on a 10-bit ADC.
* Digital-to-analog converters (DACs) do the reverse, where a digital number from the microcontroller is used to output an analog voltage, e.g. between ground and the supply voltage.

While ADCs and DACs convert analog-to-digital and vice versa, they need different circuits. In the case of Arduino boards and other microcontrollers, analog input (read) and output (write) must use different pins. Analog input pins cannot be used as outputs, and vice-versa.

The exception is where you want to produce an analog output via PWM (and a smoothing capacitor). In that case the answer is yes, you can use pins A0-A7. However, you will need to bit-bang and won't be able to use the timer hardware. It's much easier to use the pins dedicated to DAC or `analogwrite` if that's an option for you.

# Answer
> 0 votes
You can create your own PWM on non-PWM pins using Blink Without Delay techniques. Use the micros() timer and check it every pass thru loop() to if it is time to change the state of the output.

This will create 50% duty cycle, with frequency = 1/(2 x halfPeriod)

```
void loop(){
  currentMicros = micros(); // capture the current 'time'
  elapsedMicros = currentMicros - previousMicros;
  if (elapsedMicros >= halfPeriod){
    previousMicros = previousMicros + halfPeriod; // set the 'time' of the next transition
  }
}

```

all time related elements are of type unsigned long

Then filter with a RC Lowpass filter (Resistor and a capacitor) to smooth it out so it's more like an analog level.

---
Tags: arduino-nano, analogwrite
---


# Question
Title: How do i send ads1115 data over spi to master arduino
I am trying to send ADS 1115 data which is connected with Arduino mega\_1 over I2C and arduino Mega\_1 is connected with arduino Mega\_0 over SPI. Arduino Mega\_1 is act as a slave and send ADS 1115 data to master device.. I think my whole setup is working but i want to received actual data of ADS 1115 on master Arduino Here is screenshots of results of my code

**master**

```
#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{
byte a;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
a=transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("results:");
  Serial.println (a);

  delay (1000);  // 1 second delay
}  // end of loop

```

**slave**

```
#include <Wire.h>
#include <Adafruit_ADS1015.h>
int out_buf;
int adc0;

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;
// what to do with incoming data
volatile byte command = 0;
void ss_falling ()
{
  command = 0;
}
void setup (void)
{
 ads.begin();
 Serial.begin(9600);
 //ads.startComparator_SingleEnded(0, 1000);
// have to send on master in, *slave out*
 pinMode(MISO, OUTPUT);

// turn on SPI in slave mode
 SPCR |= _BV(SPE);

 // turn on interrupts
 SPCR |= _BV(SPIE);
 attachInterrupt (0, ss_falling, FALLING);

}

// SPI interrupt routine
ISR (SPI_STC_vect)
{
 byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = out_buf; // add 15
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
adc0 = ads.readADC_SingleEnded(0);
Serial.print("AIN0: "); Serial.println(adc0);

out_buf=adc0;
//int buff = atoi(out_buf);
Serial.print("AIN1: "); Serial.println(out_buf);
delay(1000);
 }

```

i am sending 1570 but on Master side i received 35 i think ADS data is of 16 bits i.e 2 bytes and SPI received only 1 byte at a time i am stuck here please help me. Thank you in Advance

example

# Answer
> 0 votes
My Problem is solved now, thanks to the almighty. I did few changed in code as: 1. Converted the received int type data from ADS to Char. 2. Stored it in an Array, to form a string.

Here is my Modified Slave Code:

```
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1015 ads;
void setup (void)
{
ads.begin();
 Serial.begin(9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

char buf[20];
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
int adc0=0;
adc0 = ads.readADC_SingleEnded(0);
itoa(adc0,buf,10);
Serial.print("AIN1: "); Serial.println(buf);
delay(500);
}  // end of loop

```

**On Master side**

We are receiving string by sending one dummy value at a time. Here is modified master code:

```
#include <SPI.h>

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (500);
}  // end of loop

```

# Answer
> 0 votes
Implementing SPI slave mode is a little more tricky than you may think. The most important thing to remember is that it's not a "Give me X" -\> "Ok, here is X" kind of protocol. It's actually a "Here's X" \<=\> "Here's Y" protocol.

That is, at the same time that the master sends X to the slave, the slave sends "Y" to the master.

The way you have it is that the master sends "a" as a command and discards what it receives. The slave remembers that "a" as the "command". Then the master sends 0, and remembers what it receives. The slave receives that 0 and thinks "Ah, I got the command last time, so it must want the value" and queues up the value to be sent the next time a transaction occurs. That then gets thrown away, since that occurs when the next "command" is sent.

You need to be a little more cunning, and implement a finite state machine to work out where in the stream you are.

* When SS falls set a "byte counter" to 0.
* When a byte is received examine the "byte counter":
    + Byte 0: If it's an "a" then place the first byte of the value in SPDR.
    + Byte 1: Place the second byte of the value in SPDR
    + Byte 3: Do nothing (or place 0 in SPDR)
* Increment the byte counter

So the transaction goes something like this (1570 is 0x622 in hex, and I choose "little endian" since the AVR is naturally little endian):

```
Master Sends        Slave Queues          Master Receives
'a'                 0x22                  Rubbish
0                   0x06                  0x22
0                   0x00                  0x06

'a'                 0x22                  0x00
0                   0x06                  0x22
0                   0x00                  0x06

```

The important thing to remember is that the master receives what the slave queued *on the next transfer*.

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


# Question
Title: Arduino and Pyton Serial Communication, Pyton get stuck and keeps sending
I have recebntly started a project where I need to connect an arduino and another device through serial. And I have setup a simple serial connection betwee python and arduino. I can setup the connection through the python terminal and it works just fine. When I type : `arduino.write("1")`, It receives the data only once. However, When I run this code:

```
import serial

arduino = serial.Serial('/dev/ttyACM0', 115200, timeout=.1)

while True:
    arduino.write("1")

```

it writes properly, howver when I stop it using Ctrl-C, it doesn't stop sending and keeps sending to the arduino. Stops sending when I open a serial. connection using the python terminal again.

I have no idea what is causing this or how I can fiz it. Would reallly appreciate some help. Thanks in advance:

# Answer
> -1 votes
Your python code is sending "1"'s to the serial port at a blinding speed. Way faster than they can go out over the serial line. So when you stop your python code the serial port is still sending trying to get all the "1"'s out of its buffer. When you open the connection again you clear that buffer and it stops sending.

---
Tags: arduino-uno, serial, python
---


# Question
Title: ESP8266 Programming using ESP-01 to USB converter
I am new to ESP8266. To ease out the task of programming esp8266, I bought this: ESP-01 ESP8266 Programmer CH340G Chip USB WiFi Wireless UART GPIO0 Adapter.

Configured Arduino Interface to run **AT** commands in the serial monitor. I flashed ESP8266 with the basic **blink LED** example. It worked fine for some time and later on gave this error.

```
warning: espcomm_sync failed

```

When i tried to flash another program on to ESP8266, I am getting the following error.

```
Sketch uses 221,995 bytes (51%) of program storage space. Maximum is 434,160 bytes.
Global variables use 31,568 bytes (38%) of dynamic memory, leaving 50,352 bytes for local variables. Maximum is 81,920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

I could only find one article regarding this adapter. There he made a custom bridge soldering GPIO 0 to GND for ESP8266 Flashing.

So should i make a removable bridge for the same, to upload a new program. Is there any other way to simplify this task?

# Answer
> 3 votes
Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip

For more info

Additional Reference: Programming ESP8266

# Answer
> 0 votes
Just solder a jumper to the adapter according to this image (bottom side):

If you want to use programming mode, just switch to connect GND and GPIO0. Switch back to use GPIO0 as IO pin (you may attach your F-F Dupont cable to the floating pin).

---
Tags: esp8266, uart, programmer, ch340
---


title: Serial data showing incorrect values

text:
# Question
Title: Serial data showing incorrect values
I am sending data over USB Serial to my `Uno` in a specified format and printing the values after they are read

```
void loop() {
    if(Serial.available()){
        while(Serial.available()){
            int pos = Serial.readStringUntil(':').toInt();
            Serial.println(pos);
            int r = Serial.readStringUntil(',').toInt();
            Serial.println(r);
            int g = Serial.readStringUntil(',').toInt();
            Serial.println(g);
            int b = Serial.readStringUntil(';').toInt();
            Serial.println(b);
        }
    }
}

```

This is how the data is being sent

```
0:255,255,255;1:255,255,255;2:255,255,255;3:255,255,255;4:255,255,255;5:255,255,255;6:255,255,255;7:255,255,255;8:255,255,255;9:255,255,255;10:255,255,255;

```

format is `{position}:{Red value},{Green value},{Blue value};`

When I send this string to the device through the serial monitor it prints wrong values

```
0
255
255
255
1
55 //should be 255
255
255
2
55 //should be 255
255
255
3
55 //should be 255
255
255
4
55 //should be 255
255
255
5
255
255
255
6
255
255
255
7
255
255
255
8
255
255
255
9
255
255
255
10
255
255
255

```

Why is the data wrong?

Is it just the serial monitor that isnt showing it right but the values are actually right?

# Answer
> 0 votes
It looks like you are parsing the incoming data for a string of 4 numbers, pos+r+g+b. To avoid data loss as well as improve speed (if you need it), it may be better to send the data as bytes:

```
: 0x01 0xFF 0xFF 0xFF : 0x02 0xFF 0xFF 0xFF : 0x03 0xFF 0xFF 0xFF ... etc

```

This can be done with Arduino serial monitor via a hex to ASCII converter. For example https://www.branah.com/ascii-converter

Type in hex (missing 0x, where `0x3a=':'`): `3a01FFFFFF3a02FFFFFF3a03FFFFFF3a04FFFFFFFF`

Get ASCII: `:ÿÿÿ:ÿÿÿ:ÿÿÿ:ÿÿÿ`

Copy this into the Arduino serial monitor

Also, try to do all of the serial prints in one go, don't interleave reading and writing unless you absolutely have to. Sometimes bytes get dropped that way, too.

```
byte pos, r, g, b;

void setup(){
// serial begin
}

void loop() {
    if(Serial.available()){
        while(Serial.available()){
            Serial.readStringUntil(':');
            pos = Serial.read();
            r   = Serial.read();
            g   = Serial.read();
            b   = Serial.read();
            Serial.write(pos);
            Serial.write(r);
            Serial.write(g);
            Serial.write(b);
         }
    }
}

```

If you need a more elegant way to do the serial write, you will find plenty of answers already on stack exchange (too many to suggest only one).

---
Tags: arduino-uno, serial
---


# Question
Title: exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'
The code below

```
// include the library code:
#include "LiquidCrystal.h"
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(2,4,5,6,7);

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");
}
void loop()
{
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

```

Gives me the following error:

```
exit status 1 no matching function for call to 'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

```

# Answer
> 2 votes
It seems as if you are missing a parameter in the `lcd()` call. It seem to take six arguments, not five.

From the `Blink` example in the `LiquidCrystal` library:

```
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

```

Also, looking at the library definition, from `LiquidCrystal.cpp`:

```
class LiquidCrystal : public Print {
public:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
...
}

```

The number of arguments accepted by the various overloaded constructors are (respectively):

* 10
* 11
* 7
* 6

So, your statement:

```
LiquidCrystal lcd(2,4,5,6,7);

```

is missing a parameter (or more) as it only has five.

This explains why the error that you are seeing has five `int`s listed in the parameter list:

```
'LiquidCrystal::LiquidCrystal(int, int, int, int, int)'

```

---
Tags: arduino-mega
---


# Question
Title: How to work with non-traditional UART baud rates
I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.

The Arduino code look like this:

```
void setup() {
  // Put your setup code here, to run once:
  Serial.begin(800000);
}

void loop() {
  // Put your main code here, to run repeatedly:
  delay(5000);
  Serial.println(0x2be1);
}

```

When I am trying to debug it with PuTTY the result is:

And when I change the baud rate to 400 kbit/s the result is (as it should be):

Any idea?

# Answer
The Arduino Nano cannot do 800 kb/s. As you can see in the source code, the bit duration is rounded to the nearest multiple of 8 CPU cycles. In your case, it is rounded to 3 × 8 CPU cycles, which yields a baud rate of 666.666 kb/s. That is 16% too slow, an error too large for any communication to be possible.

At 400 kb/s there is no rounding error, so everything works fine.

**Edit**: Note that if you build your own barebones Arduino, then either a 12.8 MHz or a 19.2 MHz crystal should allow you to get that exact baud rate. But then `millis()`, `delay()` and co. would all be off.
> 13 votes

---
Tags: serial, arduino-nano, uart, baud-rate
---


# Question
Title: Too few arguments for multiple if statement conditions
I am using the Arduino Uno. I am attempting to only light a red LED when both a blue LED is on and the push button is pressed. However, I keep receiving an error message stating too few arguments in my if statement. I don't know whether I am simply overlooking something in my code.

The code is as follows:

```
int redLEDPin=7;
int blueLEDPin=3;
int redLEDOn=2000;
int redLEDOff=1000;
int blueLEDOn=2000;
int blueLEDOff=1000;
int leverR=2;

void setup() {
    pinMode(redLEDPin, OUTPUT);
    pinMode(blueLEDPin, OUTPUT);
    pinMode(leverR, INPUT);
    }

void loop() {
    digitalWrite(blueLEDPin, HIGH);
    delay(blueLEDOn);
    digitalWrite(blueLEDPin, LOW);
    delay(blueLEDOff);
    }

  if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {
    digitalWrite(redLEDPin, HIGH);
    delay(redLEDOn);
    digitalWrite(redLEDPin, LOW);
    delay(redLEDOff);
    }
  else
  {
    digitalWrite(redLEDPin, LOW);
  }
}

```

# Answer
> 5 votes
The digitalWrite statement in the if statement needs a value to write. It looks like you meant digitalRead, since you're comparing the result to something and the other condition is a digitalRead.

```
 if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {

```

vs

```
 if ((digitalRead(blueLEDPin) == HIGH)  && (digitalRead(leverR) == HIGH)) {

```

# Answer
> 3 votes
This is your `loop()` function:

```
void loop() {
    digitalWrite(blueLEDPin, HIGH);
    delay(blueLEDOn);
    digitalWrite(blueLEDPin, LOW);
    delay(blueLEDOff);
    }

```

Your `if()` statement is outside of your loop. Check your brackets. In the Arduino IDE, if you put your cursor to the right of a bracket, it will highlight which bracket corresponds to that one.

*Large Edit:*

To blink two LEDs concurrently, you need to get rid of the delays. Please read about using the millis() function: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

I don't know how to explain this succinctly, so I am providing the code (note that the on and off times for the LEDs are equal -- if you want them on longer than they are off, you can work on that part of it):

```
int redLEDPin=7;
int blueLEDPin=3;
int redLEDOn=2000;  //not used
int redLEDOff=250;
int blueLEDOn=2000;
int blueLEDOff=1000;  //not used
int leverR=2;

// the following variables are needed for timing and tracking LED state:
long previousMillisBlue = 0;
long previousMillisRed = 0;
bool ledStateBlue = LOW;
bool ledStateRed = LOW;

void setup() {
    pinMode(redLEDPin, OUTPUT);
    pinMode(blueLEDPin, OUTPUT);
    pinMode(leverR, INPUT_PULLUP); //I am using internal pullup resistor
}

void loop() {
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillisBlue > blueLEDOn)
    {
      previousMillisBlue = currentMillis;

      if (ledStateBlue == LOW)
        {ledStateBlue = HIGH;}
      else
        {ledStateBlue = LOW;}

      digitalWrite(blueLEDPin, ledStateBlue);
    }

    //since we are tracking ledStateBlue above, we can reference it here
    if(digitalRead(leverR) == HIGH && ledStateBlue)
    {
      if(currentMillis - previousMillisRed > redLEDOff)
      {
        previousMillisRed = currentMillis;

        if (ledStateRed == LOW)
          {ledStateRed = HIGH;}
        else
          {ledStateRed = LOW;}

        digitalWrite(redLEDPin, ledStateRed);
      }
    }
    else
    {digitalWrite(redLEDPin, LOW);}

}

```

# Answer
> 1 votes
Your if statement is outside of the loop() function.

Remove the `}` after `delay(blueLEDOff);`

---
Tags: arduino-uno
---


title: ESP8266: Is it safe to use pin 0?

text:
# Question
Title: ESP8266: Is it safe to use pin 0?
This (maybe stupid) question is bothering me for a long time...

If the pin 0 has to be connected to the ground for uploading a sketch into ESP8266, and after the uploading the chip automatically starts the uploaded sketch (without waiting for reboot with pin 0 to be disconnected), then won't it destroy the chip if I do digitalWrite(0, HIGH) in my sketch? Correct me if I'm wrong, but it should short 3.3V directly to the ground through this pin... Is this problem secured somehow? Or maybe this pin can be safely used for reading only?

Edit:

I have seen it connected to ground directly on every schematic about ESP8266, but maybe I should just use a pull-down resistor? Or maybe the chip already has a resistor before this pin to solve this problem?

# Answer
> 6 votes
You can absolutely use GPIO0 as an output. The ESP will read the state of GPIO0 once at boot (And never again thereafter) to determine what boot mode to enter. During this time it is an input, so, whatever you hook GPIO0 up to must not hold this pin low (Unless you want to enter bootloader mode, of course), at least until the chip boots. As long as you satisfy this condition, you can use the pin for anything else. On my board for example, I use it to drive a simple status LED, and have never seen any issue from it.

# Answer
> 2 votes
What do you consider pin 0? As I look at the schematics it could either be GND, VCC, RX or TX pin. Or do you mean GPIO0?

GPIO0 when connected to GND and in combination with RST to GND will put ESP into programing mode. Good practice is to have separate programing board, something like This here. Go down to "Writing a program to the ESP8266" section and check out the schematic. Voltage regulator can be omitted if you are already powering it with 3.3v.

# Answer
> 0 votes
It may be stated that GPIO0 is safe to use as an output, but I challenge anyone to show he has actually done it. When configuring GPIO0 as an output I get only oscillations (about 70kHz), loaded or open, when driving this pin LOW. Even GPIO15 works without issues when used as an output. Several new ESP8266-12F modules were tested.

---
Tags: pins, esp8266, safety
---


# Question
Title: Interrupts: use of the "volatile" keyword with a structure pointer for button debounce
I've written a small sketch targeted at the Arduino Uno (ATmega328P) to debounce a mechanical pushbutton using the summing/integration technique:

```
#include <IntegratingDebounce.h>
#define PIN_BTN 4

IntegratingDebounce *btn;

ISR (TIMER2_OVF_vect) {
  ideb_poll(btn);
} // end timer2 overflow ISR

void set_debounce_timer() {
  TCNT2 = 0;                                  // Clear timer
  TCCR2A &= ~( bit( WGM21 ) | bit( WGM20 ) ); // Set waveform generation mode to normal
  TCCR2B &= ~bit( WGM22 );
  TIMSK2 |= bit( TOIE2 );                     // Enable interrupt on overflow
  TCCR2B |= 7;                                // Start clocking the timer
} // set_debounce_timer()

void setup() {
  Serial.begin(9600);
  pinMode(PIN_BTN, INPUT_PULLUP);

  ideb_init(&btn, PIN_BTN, 4);
  set_debounce_timer();
} // setup()

void loop() {
  while (ideb_read(btn) == HIGH);  // wait until the button pin goes low
  Serial.println("Pressed!");
  delay(100);
} // loop()

```

An `IntegratingDebounce` structure stores the data needed to perform the debounce. I keep a pointer to the structure, `btn`, in the global memory space.

The timer2 overflow ISR periodically polls the state of the button pin, updates the internal integrator, and sets the (also internal) debounced output accordingly. The `ideb_read()` function reads the debounced output out of the structure.

I'm having trouble determining where the `volatile` keyword should be placed in the declaration for the `btn` structure pointer. First I declared it as:

`volatile IntegratingDebounce *btn;`

I thought this would make all of the fields in the structure pointed to by `btn` volatile, but button presses are not detected in loop(). Declaring `btn` as a volatile pointer rather than a pointer to a volatile structure generates the expected output:

`IntegratingDebounce *volatile btn;`

This seems backwards. Why does this work?

**IntegratingDebounce.h**

```
#ifndef __INTEGRATING_DEBOUNCE_H__
#define __INTEGRATING_DEBOUNCE_H__

#include <Arduino.h>
#include <stdint.h>

extern "C" {

typedef struct IntegratingDebounce_S IntegratingDebounce;
typedef uint8_t ideb_size_t;

// Create a debounce structure and initialize.
void ideb_init(
  IntegratingDebounce **ideb,
  uint8_t pin,                  // I/O pin to debounce
  ideb_size_t clamp             // debounce clamp; the maximum value the
                                //   internal sum is able to take on
);

// Poll the state of the pin, integrate, and update the debounced output.
void ideb_poll(IntegratingDebounce *ideb);

// Read the debounced state of the pin.
uint8_t ideb_read(IntegratingDebounce *ideb);

// Reset the internal integrator to either the LOW or HIGH state.
void ideb_reset(IntegratingDebounce *ideb, uint8_t state);

} // extern C

#endif

```

**IntegratingDebounce.c**

```
#include "IntegratingDebounce.h"

struct IntegratingDebounce_S {
  uint8_t pin;              // pin to debounce
  uint8_t output;           // debounced output
  ideb_size_t clamp;        // debounce clamp
  ideb_size_t integrator;   // clamped running sum
};

void ideb_init(IntegratingDebounce **ideb, uint8_t pin, uint8_t clamp) {
  *ideb = (IntegratingDebounce *)malloc(sizeof(IntegratingDebounce));
  (*ideb)->pin = pin;
  (*ideb)->clamp = clamp;
  (*ideb)->output = 0;
  (*ideb)->integrator = 0;
} // ideb_init()

void ideb_poll(IntegratingDebounce *ideb) {
  // update the integrator based on the present state of the pin:
  // - if LOW, decrement the integerator; if HIGH, increment the integrator
  // - constrain the integrator to values between 0 and 'clamp'
  if (digitalRead(ideb->pin) == LOW) {
    if (ideb->integrator > 0) ideb->integrator--;
  } // if
  else {
    if (ideb->integrator < ideb->clamp) ideb->integrator++;
  } // else

  // update the output based on the value of the integrator; the output
  // will not change until the integrator reaches a limiting value
  if (ideb->integrator == 0 && ideb->output == HIGH) {
    ideb->output = LOW;
  } // if
  else if (ideb->integrator == ideb->clamp && ideb->output == LOW) {
    ideb->output = HIGH;
  } // else if
} // ideb_poll()

uint8_t ideb_read(IntegratingDebounce *ideb) {
  return ideb->output;
} // ideb_read()

void ideb_reset(IntegratingDebounce *ideb, uint8_t state) {
  if (state == LOW) {
    ideb->integrator = 0;
    ideb->output = LOW;
  } // if
  else {
    ideb->integrator = ideb->clamp;
    ideb->output = HIGH;
  } // else
} // ideb_reset()

```

# Answer
> 4 votes
I think, that the problem is in `ideb_read`, which expects "a pointer to (non-volatile) structure" and so it does not care about re-reading `ideb->output` if it can it optimize out somehow (say putting it in free register).

IMHO the `ideb_read` should have parameter declared as `(volatile IntegratingDebounce *ideb)` (to know, that structure pointed by `ideb` is volatile) or use global variable `btn` (which is pointer to volatile structure) instead of pointer parametr to non-volatitle structure.

---

And why the second works would be because it forces re-read the parameter of `ideb_read` and so it cannot be saved out somewhere and the function is indirectly forced to expect changed pointer, so it have to use its 'new value' and read the structure (as it is simpler, than ensure, that the `ideb` have the same value as it had last call and so the whole structure there (which is declared as non-volatile in header of `ideb_read`) could be cached)

---

Another wording of the above:

Declaring `volatile IntegratingDebounce *btn;` the main program in `loop` simply takes the value of `btn` (which is non-volatile pointer to volatile structure) and copy that (non-volatile) value to `ideb` parametr od `ideb_read`, which is non-volatile pointer to non-volatile structure. `ideb_read` use it that way and compiler somehow was able to cache all of that and so not read `ideb->output` again, as it knows, that it is part of non-volatile struct. (So it does not work)

Declaring `IntegratingDebounce *volatile btn;` you made the `btn` volatile, so it gets read each time `ideb_read` is called and the 'new actual value' is passed to (non-volatile) `ideb` parametr (which is this way given 'new value' and so cannot be cached between calls) and it results to reading (non-volatile) date from "new" place pointed by `ideb`. So it works (by mistake).

Right solution would be declare correctly `volatile IntegratingDebounce *btn;` in main program AND declare correctly `uint8_t ideb_read(volatile IntegratingDebounce *ideb)` so the `ideb_read` function is forced read value pointed by `ideb` every time again (which is the right thing to do)

And it should be used for all other `ideb_**` functions too.

And I think, that it would be simpler to declare some typedef for this volatile structure (something like `typedef struct { ... } volatile ideb_t;` ) and use the new type everywhere.

# Answer
> 4 votes
Getting pointer declarations right can be anything but obvious, especially where `const` and `volatile` are concerned (which are syntactically equivalent). Your problem stemmed from the confusion between "volatile pointer to struct" and "pointer to volatile struct". See the difference? In words it's fairly clear. In C, it has you - and me - running to your C manual's Table of Precedence.

I keep a copy of Dan Saks' article, "Const T vs. T Const" on hand for just exactly this case - it seems I always need to look it up.

And while you're there, check out some of his other articles as well. I learn something every time I read one.

---
Tags: interrupt, button, isr, debounce
---


# Question
Title: a code problem for arduino GSM 1400 to send a SMS when tilt movment is detected using accelerometer
## There is a mistake in the design implementation of the code probably in if statment - when using the serial monitor it repeatedly shows printf() statements from the code instead of "Sending SMS message".

```
 // Include the GSM library
#include <MKRGSM.h>
#include<math.h>
#include<stdio.h>
int xp = A5;
int yp = A4;
int x,y;
#include "arduino_secrets.h"
// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[] = SECRET_PINNUMBER;

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

void setup() {
    x=analogRead(xp);delay(2);
    y=analogRead(yp);delay(2);

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

  Serial.println("SMS Messages Sender");
  pinMode(xp,INPUT);
  pinMode(yp,INPUT);

  // connection state
  boolean connected = false;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (!connected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

void loop() {
    if ((x>=0.60) & (y>=40))

 Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+491781234567\"\r");
    char remoteNum[20];

  // sms text
  Serial.print("your bike is in danger!");
  char txtMsg[200];

  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNum);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
   delay(5000);
   if ((x<=0.30) & (y<=25))

 Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+491781234567\"\r");

  // sms text
  Serial.print("your bike is in danger");
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNum);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
   delay(5000);
}

```

# Answer
# Your if statement is broken!

```
if(cond)
   statement; // this is conditional
statment2; // this will always be executed!

```

You need to use a code block:

```
if(cond)
{
    statement; // both statments are now
    statement2; // conditional!
}

```
> -1 votes

---
Tags: programming, sensors, gsm
---


# Question
Title: GPS: Not receiving any valid output from ATGM336H
I have an Arduino Pro Mini along with a GPS Unit - ATGM336H. Below is the sketch I'm currently using:

```
#include <SoftwareSerial.h>
#include "Ublox.h"
SoftwareSerial GPS(4,5);
Ublox serial_gps;

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

void loop(){
  while(GPS.available()){
  char c = GPS.read();
  if(serial_gps.encode(c)){
  Serial.println(serial_gps.longitude);
    }
  }
}

```

I'm able to receive NMEA stream from the GPS Unit and parse (tried TinyGPS++, TinyGPS and Ublox) the stream but the data is not valid nor does it ever change. I've read that this GPS unit can take up to 32 seconds to get a fixed position and deliver valid co-ords but I cannot receive any.

Is there anything obviously wrong with my sketch or hardware setup?

Any and all help would be greatly appreciated!

# Answer
while(GPS.available() \> 0) {....

Also is the GPS unit outside?
> -1 votes

---
Tags: arduino-pro-mini, gps
---


title: Load Cell and HX711 only outputting 0's

text:
# Question
Title: Load Cell and HX711 only outputting 0's
I am using an Arduino Uno and HX711 amplifier to collect data from a load cell. I previously had the load cell calibrated and functioning, but now the load cell will not read any values; only 0's are outputted, even when I apply a small load to the sensor. I have re-soldered and replaced the connecting wires. Are there any suggesting for getting a readout from my sensor?

I have been testing with 2 different load cells: Sparkfun's TAL220 Straight Bar 10kg load cell and an LFS 210-300 from Cooper Instruments (the latter is the one I want to use long term). My load cell is connected like the HX711 Breakout Guide (with an Arduino Uno instead of a RedBoard and a USB connection):

I have been using the HX711 Breakout Guide Calibration sketch to test my load cell:

```
#include <HX711.h>

#define DOUT 3
#define CLK 2

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

```

I am still new to Arduino and data acquisition in general, so any suggestions would be appreciated!

# Answer
> 3 votes
This line is where you are reading the data and printing it:

```
Serial.print(scale.get_units(), 1);

```

The 1 on the end of the line defines how many digits you are displaying from your reading. I have a similar setup to yours and I have it set to 5 which shows up to +/-0.00001kg. (Obviously, the accuracy will be different depending on which load cell you have)

---
Tags: arduino-uno, serial, sensors
---


title: ESP8266-01 WifiScan not working

text:
# Question
Title: ESP8266-01 WifiScan not working
I have a ESP8266-01 and am trying to get it to work. I am using the example WiFiScan code shown below.

```
#include "ESP8266WiFi.h"

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

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

```

I have a voltage regulator producing 3.3 V connected to `CH_PD` and the Arduino powers the ESP's VCC via the 3.3 V pin. `TX` is connected to `TX` and `RX` is connected to `RX`. `GPIO0` is connected to ground. I can upload, but it cannot find any networks. It always states no networks found. Now I'm not even sure how to proceed... Any help would be appreciated.

# Answer
> 1 votes
You should provide a good power source for the VCC. One that can supply 170 mA for WiFi operations of esp8266. You should use the power regulator to supply 3.3 V to VCC and there is no reason to use other power source for the CH\_PD pin. CH\_PD pin is "enable" pin, it doesn't need a strong power supply.

IO 0 should be connected to ground only for upload, not for normal operation.

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


# Question
Title: What is the difference between Serial.write and Serial.print? And when are they used?
What is the difference between Serial.write and Serial.print? And when are they used?
Both have been used to print on serial monitor, what are their actual differences?

# Answer
Serial.write is more down to earth , it is simple and fast, it is made to talk binary, one byte at a time. example:

```
Serial.write(0x45);   // will write 0100 0101 to the cable

```

Serial.print in the other hand is more versatile , it will do the conversion for you from ASCII to binary it also can convert to BIN/ HEX/OCT/DEC but you need to specify a second argument like so

```
Serial.print(76, BIN) gives "0100 1100"
Serial.print(76, OCT) gives "114"
Serial.print("L", DEC) gives "76"
Serial.print(76, HEX) gives "4C"

```

more examples with visual serial output :

**Code:**

```
  Serial.write(0x48);   // H
  Serial.write(0x45);   // E
  Serial.write(0x4C);   // L
  Serial.write(0x4C);   // L
  Serial.write(0x4F);   // O

```

**SERIAL OUTPUT :**

**Code:**

```
  Serial.print("HELLO");

```

**SERIAL OUTPUT :**

Serial.println() in the other hand will add end of line 2 bytes 0x0D and 0x0A as you can see in the frame

**Code:**

```
  Serial.println("HELLO");

```

**SERIAL OUTPUT :**
> 36 votes

# Answer
From the Arduino site for Serial.write and Serial.print:

**Serial.write()**

> Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead.

**Serial.print()**

> Prints data to the serial port as human-readable ASCII text. This command can take many forms. Numbers are printed using an ASCII character for each digit. Floats are similarly printed as ASCII digits, defaulting to two decimal places. Bytes are sent as a single character. Characters and strings are sent as is
> 24 votes

# Answer
`Serial.write` sends bytes to the serial port while `Serial.print` sends ASCII characters so people can read easily.

Some devices work using bytes to set configurations, commonly use packets of data and you need to use write function to communicate with them. Eventually they will send bytes through serial interface and then you can interpret by going each byte.
> 7 votes

# Answer
All of the examples above are correct, but maybe more clearly.... All data sent through the serial port is sent as 1's and 0's. (obvious.... I hope)... The difference in the two commands is how whatever is being sent is actually translated/interpreted to/from these 1's and 0's. The clearest example involves transmitting numbers.

Let's say you need to send the number 217. The binary (1's and 0's) representation of this number is 11011001. Using the command `Serial.write(217)` will literally just send 11011001 across the line. The Hex representation of the same number is 0xD9, and the command `Serial.write(0xD9)` will send the same thing ... 11011001.

Here is where it gets interesting... If you were to use the command `Serial.write("217")` you would instead get this: 00110010 00110001 00110111... WHAT?!?!?
When a string is passed as the argument it is broken down into individual characters, converted to ASCII, and then sent as a byte for each character. You would get the exact same output if you were to use the following:

```
Serial.write(50);
Serial.write(51);
Serial.write(55);

```

(00110010 00110001 00110111)

Now let's look at `Serial.print()`. The commands `Serial.print(217)` or `Serial.print("217")` will both print the same thing: 00110010 00110001 00110111. This is because the print command first converts any number to a string representation and then uses the command `Serial.write()` to send each character as individual ASCII bits.

Though this is not a COMPLETE description, I hope it helps to get you thinking in the right direction...
> 7 votes

# Answer
Yet another way to answer this is to state the Serial.write accepts single characters where Serial.print accepts strings. There may be some differences but this is the main one.
> 3 votes

---
Tags: serial
---


# Question
Title: ESP8266 Stops Working After A While (Unknown Problem)
have an esp8266.

i'm trying to create a DDNS updater.

it has to wait 5 min then do a GET request to a URL.

Here's my code:

```
/* Code For DNS Updater.*/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define LOOP_TIME 300000

const char* ssid = "SomeSSID";
const char* password = "SomePSWD";

const String address="http://dynamicdns.park-your-domain.com";
const String path="update";
const String pathHost="host";
const String pathPassword="password";
const String pathDomain="domain";

const String dnsName="my-example-host.com";
const String ddnsPassword="my-example-password";
const String updateHosts[]={
    "@",
    "subdomain1",
    "subdomain2",
  };

void setup() {
  Serial.begin(115200);
  connectWiFi();
}

long nextUpdate=0;

void loop() {
  if(nextUpdate<millis()){
    if (WiFi.status() == WL_CONNECTED) {
    updateDNS();
    }else{
      connectWiFi();
    }
    nextUpdate=millis()+LOOP_TIME;
  }
}

void updateDNS(){
  Serial.println("Updating Hosts:");
  for(int host=0;host<(sizeof(updateHosts)/sizeof(String));host++){
    Serial.print(updateHosts[host]+": ");
    String assembledURL=address+"/"+path+"?"+pathHost+"="+updateHosts[host]+"&"+pathDomain+"="+dnsName+"&"+pathPassword+"="+ddnsPassword;
//    Serial.println("Host: "+updateHosts[host]+" URL: "+assembledURL);
    HTTPClient http;
    http.begin(assembledURL);
    http.GET();
    http.end();
    Serial.println("Done");
  }
}

void connectWiFi(){
  WiFi.begin(ssid, password);

  Serial.print("Connecting To ");
  Serial.println(ssid);
  Serial.print("Password: ");
  Serial.println(password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {

    delay(500);
    Serial.print(".");

  }
  Serial.println();
  Serial.print("Connected To ");
  Serial.println(ssid);
}

```

and it stops after a couple of hours - which isnt good for a DDNS updater.

EDIT: maybe it has something to do with my timer. will try an unsigned long instead.

# Answer
I have had the "stops after a while" too and it turned out to be heap memory consumption and fragmentation that caused not having enough stack and heap space any more.

My solution: check the heap from time to time (in loop) and reboot the node when it comes down to a practical limit.

Alternate: avoid using the String type and other Heap usages.
> 1 votes

---
Tags: esp8266, loop
---


title: Adafruit Feather 32u4 FONA KEY Pin

text:
# Question
Title: Adafruit Feather 32u4 FONA KEY Pin
I received a Adafruit Feather 32u4 FONA as a gift and have read the great, comprehensive document Adafruit put have put together surrounding pinouts, examples etc for the board. I am having issue understanding the section on the KEY pin, I understand that it is used to put the cellular module to sleep, but in order to do this it is mentioned to “cut the trace and wire it to a micro controller pin”. Does this mean that in order to utilize the on/off functionality of the SIM module I have to slightly butcher my new shiny board instead of using the pin directly?

# Answer
Yes, you will need to physically cut the trace to use the on/off feature. This is common on development boards. It could be done with a jumper but that would add cost and/or require a larger board.

You will see on the back of the board there are 2 large pads connected by a thin trace. You can use an exacto knife to cut the trace. To repair the cut you use a blob of solder to bridge the gap between the pads.
> 2 votes

---
Tags: adafruit
---


title: Is my Arduino dead?

text:
# Question
Title: Is my Arduino dead?
I connected my Arduino Uno to an external power supply, but did not noticed the power supply was on 30 V, I saw the part in the picture smoking and immediately pulled the cable out of the Arduino. now, each time I connect it to some source of power his "ON and "L" light up ("TX" and "RX" are dark) and the ATmega heats up, and it can't receive sketches from my PC. It says just

> Problem uploading to board.

Is my board completely dead or I can somehow save it?

# Answer
> 1 votes
If the '328P gets hot, it is dead. But, it's replaceable, you can even buy one with a bootloader loaded in already.

The part you circles is a 100nF capacitor, a 10 cents part.

If the PC is not recognizing it when you plug in USB, then the Atmega16U2 that does the USB interfacing is dead. That one is a very small surface mount part that you cannot replace without a hot air rework station, and then you will need a Programmer to reload it with its USB interface program.

And if you killed the 2 regulators, those need replacing too.

Get another board, be more careful next time. I'd get a 7.5V or 9V wallwart for power. I think you can get the wallwart and a bootloaded '328P from www.dipmicro.com, www.sparkfruit.com, www.adafruit.com, etc.

# Answer
> 2 votes
You could try to replace the SMD part, probably a capacitor (I may be wrong), if you can identify which part it is from the schematic (or any marking on the board). However, you may have damaged something else as well. You will only know if and once you have replaced the smoking part.

You may be lucky and only that part has been damaged.

The ATmega appears to be socketed so you *could* try removing it and putting it in another undamaged board to see if it works still.

It looks like the smoking part is next to a regulator, `IC2` (I am not 100% sure about that), but that would make sense, seeing as it was a power supply issue that caused the smoking in the first place. Maybe just the power supply part of the board is damaged (`D1`, `PC1`, `PC2`, `C2`, `IC1` or `IC2` \- the two big black and white capacitors, with `47 25V` written on them in your photo are `PC1` and `PC2`), and you could slowly work your way through it, checking and replacing the sequential parts (again with the use of the schematic).

I wouldn't throw the board away, I have some partially damaged boards that only half function, but the part that still functions will probably suitable for some project or other in the future... or maybe not, depending on the damage.

It is hard to tell from just a photo which being able to check the parts using a multimeter.

Given that the power LED and `L` LED still work, there is some hope. Try using the USB input for power and see if that helps as the circuit is different from that of the power jack (no regulator). See `VIN` AND `PWRIN` versus `USBVCC`, on the schematic.

Here is the power jack circuit:

Here is the USB input:

However, if, as you say, the PC can not see the Arduino to communicate with it, it will make programming it difficult.

If you *do* have another UNO board, with a removable ATmega IC, program `Blink.ino` on to the ATmega and place it in the damaged board to see if the `L` LED blinks. If it does then at least some of the board still works.

However, to sum up, your Arduino is probably not going to be as useful as it was prior to the over voltage having been applied - unless you are both lucky and replace a few SMD parts.

On the positive side, look at it as a learning experience on how to track down and repair faults on a PCB - a very useful skill to have.

---
Tags: arduino-uno, heat
---


# Question
Title: Arduino UART (TX/RX) multidrop 1 master 50 slaves
I'm thinking to connect about 50 slave Arduinos on 1 master using TX/RX. I'm following recommendation of these links:

using the cathode of diode connected to slaves TX pins and pulling up this line, like this image:

In Arduino - Digital Pins, when pin is set to input (high impedance), it is "equivalent to a series resistor of 100 MΩ in front of the pin". Slave RX line has input (RX pin) in parallel, then, if this 'equivalent resistor' is true, we have a low resistance (duo parallel configuration) that burn the master TX. Is it make sense?

I have not found either in the Arduino or the ATmega documentation, if TX port have the internal pullup on. In ATmega documentation, TX pin is set as output and RX pin as input. The TTL logic is high on idle, then 5 V must be sourced from somewhere, correct?

# Answer
> 0 votes
An input pin draws 1uA or less input current, so more like 1 Megohm resistor, not 100 Megohm.

In an Uno, the USB interface chip typically is what is pulling the Tx and Rx lines high with 5mA drive (high output thru a 1K resistor to D0 or D1).

What you have drawn should work. The pullup resistor will ensure the Rx into the 1st Arduino sees a nice crisp high when the other two stop pulling the line low as they send a message out, and the diodes will prevent the one driving the line high while the other pulls it low.

---
Tags: serial, uart, pull-up
---


# Question
Title: How will I solve my problem : expected primary-expression before '>' token
```
// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
// defines variables
long duration;
int distance;

#include <moving.h>
#include <Servo.h>

Servo servo;

moving car(6, 2, 3, 5, 4, 7, 11, 8, 9, 10, 12, 13); // setting up a new RC car with pins EN1, IN1, IN2, EN2, IN3, IN4, EN3, IN5, IN6, EN4, IN7, IN8

void setup() {
{
  for (int i=2; i<14; i++)
  {
    pinMode(i, OUTPUT);
  }
  servo.attach(10);
  servo.write(90);
}
{
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
}

void loop() {
  if (distance) > 10; // this is the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
  if (distance) < 10; // and this
  car.set_speed(0);
  car.forward();
  delay(600);
  car.set_speed(127);
  car.right();
  delay(700);
  car.set_speed(127);
  car.forward();
  delay(700);
}

```

# Answer
You need curly brackets around your if block.

```
if (distance > 10) { // this solves the problem
  car.set_speed(127);
  car.forward();
  delay(3000);
}

```

etc Edit: Thanks to the commenter.
> 2 votes

---
Tags: programming
---


# Question
Title: Why does reading an analog pin give a different results when interfacing with Processing?
I am interested in measuring the voltage over an analog pin (`A6`). When I use the Arduino IDE to print the results through the serial I get values around `300`.

Here's the code

```
void setup(){
   Serial.begin(57600);
}

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}

```

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around `900`.

Here's the Processing code:

```
import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}

```

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?

The pin is connected to a circuit with supply voltage. I also tried reading the values directly using `Serial` in Processing (so without using the `cc.arduino.*` \- library) and that showed me the values around `300`. So I guess the difference is caused by the `arduino.analogRead()` method. I am puzzled as to whether that's a bug in the library or something else.

The problem seems to be me not properly initialising the pins. But calling

```
arduino.pinMode(6,Arduino.ANALOG);

```

in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.

# Answer
You have not provided a schematic of how the Arduino is wired up.

However, if *nothing* is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then `analogRead()` will produce a different value than when your hand in not near it.

I would hazard a guess that if you ran *both* sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.

Try that first, and then tie the input to either `HIGH` or `LOW` and then repeat the previous experiment.

In the second case the results should be consistent, and equal in the Arduino and Processing alike.

---

However, according to your comment, that is **not** your issue, as your inputs are not floating.

I think that issue is actually this:

> Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.

Source: Re: Firmata problem with analogRead in Processing Library

Looking at your Processing code the pins are **not** defined. You need to do so.

With the Arduino code, there is no need to define the analogue pins.
> 1 votes

---
Tags: analogread, processing-lang, voltage
---


title: Arduino - Button to start / stop loop

text:
# Question
Title: Arduino - Button to start / stop loop
So basically I'm trying to create a device where when I push a button it starts a loop. When I push this button again, it stops the loop. Right now I have it logged to serial. It starts up correctly with no output. When I press the button the loop begins and it spits out "toggled on" continuously. When I press the button again... nothing happens. What should happen ideally is that it should stop spitting out "toggled on" and just go back to doing nothing.

```
#include <Bounce2.h>

Bounce bouncer = Bounce();
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
  bouncer.attach(W);
  bouncer.interval(5);
}

void loop() {
  bouncer.update();
  if (bouncer.read() == LOW) {
    wOn = !wOn;
  }

  if (wOn > 0) {
    Serial.println("toggled on");
  }
}

```

# Answer
> 1 votes
If you change your sketch to this one, you'll see the issue:

```
const int W = 10;
bool wOn = false;

void setup() {
  Serial.begin(9600);
  pinMode(W, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(W) == LOW) {
    wOn = !wOn;
  }

  if (wOn) {
    //Serial.println("toggled on");
  }
  Serial.println(wOn);
}

```

The button's contacts "bounce" (Google "contact bounce"), sending multiple low to high signals. There are several software solutions that will eliminate this issue. Have a look at: arduino.cc/en/Tutorial/Debounce. There are a couple of libraries that simplify de-bouncing buttons: playground.arduino.cc/Code/Debounce and playground.arduino.cc/Code/Bounce

# Answer
> -1 votes
Fixed. The solution I used was to add state change checking using `.fell()` which you'll see reflected below. I added state change verification using `Bounce2.fell()`, like so:

```
  if (bouncer.read() == LOW && bouncer.fell()) {

```

---
Tags: button, loop
---


# Question
Title: How do I (easily) power a 5 V 3-pin fan?
I have a 5 V 3-pin fan. I want to be able to:

1. power it from an Arduino Uno or a Seeeduino Lotus board, and, ideally;
2. be able to change its speed.

Most resources I can find on the web explain how to connect a standard 12 V fan and moreover complicate the thing by explaining how to get the speed of a fan or to control multiple fans. This is way too complex for me.

If my understanding is correct, I can't just connect a fan to analog output pins, because the absolute max power per pin is 40 mA (recommended: 20 mA), while the fan uses 100 mA.

Instead, I have to somehow connect two of the three pins of the fan to an external power, and use the third pin to control the speed. Am I supposed to use the ground and 5 V pins situated on the left side of the board above ANALOG IN?

If not, what are my other options? The board is powered by an USB cable, and I see no way to split the power at this level between the board and another device without running a risk of damaging the board.

# Answer
> 9 votes
You are correct in your assumption that you can not power a fan from an Arduino directly.

Use a transistor, for example 2N2222 or BC548, which is switched by the Arduino, using a *single* pin, in order to provide sufficient current to the fan.

Such as this simple circuit (note that the 12V supply would be 5V in your case):

>

Source: Driving a PC fan - transistor with or without an optocoupler?1

*However, as chrisl has pointed out, you fan has three pins and not two. The above circuit will only work for a two pin fan. In your case, for the reasons stated in Chrisl's answer, one pin goes to 5 V supply, one to `GND` and then third goes directly to the Arduino - let's say pin 3. Then you can use the code below.*

Assuming that the fan is connected to pin 3, then the code will look like this:

```
const int fan = 3;

void setup() {
  pinMode(fan, OUTPUT);
}

void loop() {
  int fanSpeed = 255;
  analogWrite(fan, fanSpeed);
}

```

This will run the fan at full blast. However, you can thereafter modify your code to vary the value of `fanSpeed`.

Furthermore, by reading an analog input pin (let's assume that you have a potentiometer hanging off `A0`), using `analogRead()`, you can use the read value to modify the value of `fanSpeed` directly (by dividing the value returned from `analogRead()` by four2 and then sending to `analogWrite()`, like so:

```
  int potPin = A0;
  fanSpeed = analogRead(potPin)/4;
  analogWrite(fan, fanSpeed);

```

or even more succinctly, do away with `fanSpeed` completely and use:

```
  int potPin = A0;
  analogWrite(fan,analogRead(potPin)/4);

```

---

1 Note that the code in the link in incorrect as it attempts to write values greater than 255 using `analogWrite()`. As stated here, Arduino reference - analogWrite(), `analogWrite()` takes values of `0-255`, whereas `analogRead()` returns values of `0-1023`

2 See the `loop()` function in Arduino reference - analogWrite() for another example.

# Answer
> 1 votes
EDIT:

As VE7JRO pointed out the fan you are using does not have a native PWM pin. The third pin is actually reporting back the RPMs of the fan. So you need to follow Greenonline's answer by using a MOSFET. For now I will leave my answer here for reference. If wanted I will delete it later.

---

A 3-pin fan is controlled like a servo. The current for actually driving the motor flows through the power pins (5V and Ground). The third pin takes a PWM (pulse width modulation) signal to determine the wanted fan speed. This is just a signal line, there is only very little current flow, so that the Arduinos pin will not be damaged. So the motor driver is already included.

From the programming side you can use `analogWrite()`, which outputs a PWM signal at one of the PWM-capable pins. The speed of the fan is controlled via the duty cycle of the signal. 100% (value of 255 for UNO) means full speed, 0% (value of 0) stops the motor.

About the power supply: Since your fan uses 100mA at full speed (I assume), it is still possible to power it over the 5V pin of the Arduino. You can source about 500mA over it (including the current for the Arduino itself). When sourcing higher currents over the USB plug, the polyfuse will be fried. This is the value for the UNO r3. A Nano can source only 200mA, because the diode will be fried.

So be carefull how much current you draw from the 5V pin of the Arduino. Or, if you have greater current requirements you have to supply an extra voltage to drive the fan.

---
Tags: motor
---


# Question
Title: Arduino connected keypad printing wrong numbers
Going crazy here trying to connect a keypad to my Arduino. I followed this article KeypadTutorial, but my guess is something is wrong/different because my keypad only has 9 pins and the far left (pin 1) and far right (pin 9) pins have no traces back to the keypad. I bought it years ago and just got around to finding a use for it. It looks just like this one Arduino Keypad but different with white keys with black font.

The issue is the wrong key shows up (i.e. press 0 and get 9). I used a multi-meter to test for continuity between pins when pressing each key and got results that are kind of stumping me. I would think there would be some kind of pattern (like the first pin would always be a 1, 2, or a 3), but obviously not (or I just have a bad keypad).

```
KEY(pin1, pin2)
1(2,3)
2(1,2)
3(2,5)
4(3,7)
5(1,7)
6(5,7)
8(1,6)
9(5,6)
0(1,4)
#(4,5)
*(3,4)

```

# Answer
> 0 votes
Transpose the pins for some of the keys and a pattern will emerge.

```
KEY(pin1, pin2)      transposed pins
1(2,3)        x        1(3,2)
2(1,2)                 2(1,2)
3(2,5)        x        3(5,2)
4(3,7)                 4(3,7)
5(1,7)                 5(1,7)
6(5,7)                 6(5,7)
8(1,6)                 8(1,6)
9(5,6)                 9(5,6)
0(1,4)                 0(1,4)
#(4,5)        x        #(5,4)
*(3,4)                 *(3,4)

```

---
Tags: arduino-uno
---


title: Query related to Serial communication

text:
# Question
Title: Query related to Serial communication
I have a Raspberry Pi and an Arduino. On my Arduino I wrote a program, if you see the last two functions i.e. `getMove()` and `SendMove()` you will see that I am sending a move serially and the RPi will read the string only after it reads start. It is sending it to the RPi through serial communication using a USB (Note: As you can see the Arduino will send the string only one time and not again and again since once it sends the string the control will go into `getMove()` which waits for "Rstart").

Once I uploaded the code in the Arduino, I opened the serial monitor to check the output that I should be expecting in my RPi. Then I removed the USB from my laptop and connected the Arduino to the RPi and ran the Python code to read the string sent from the Arduino serially and got the string sent. I ran the code again on the RPi and got the string sent.

Now my question is, the first time when I opened the serial monitor on the laptop there was serial communication between the Arduino and my laptop, so I expected the string I sent to have gone to the laptop. So, when I connected the Arduino to the RPi, I didn't expect a string to be received on the RPi since the string was already sent to the laptop. Then again I ran the code on the RPi but still got the string sent.

Can someone explain how Serial communication works? Once I send something from the Arduino serially, will it always be in the serial buffer?

**EDIT**:
I have understood that unless the DTR pin of the serial connector is disabled the Arduino will keep resetting itself when connected to something new.

Now my question is, why does Arduino reset itself when I run the Python code (to read the serial buffer) again and again?

**ARDUINO CODE**

```
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // 4 bit mode
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0} };

int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                {0,0,0,0,0,0,0,0}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,0,1,1,1,1,1}, \
                                {0,0,0,0,0,0,0,0}, \
                                {0,1,0,0,0,0,0,0} };
//int SensorValStore_Curr[8][8];
int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
String file,moveSan,Temp,bestMove;
char Buffer[20];
void doAction();
void ReadSensor();
void Difference();
void binToIntCalc();
void check();
void getMovePlayed();
void SendMove();
void getmove();

void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

void loop()
{
  //if( digitalRead(10) == 0 )
  //{
  Serial.print("--------------------Initial Matrix-----------------------------\n");
  Print(SensorValStore_Prev);
  // doAction();
  delay(40);
  Serial.print("--------------------Final Matrix------------------------------\n");
  Print(SensorValStore_Curr);
  delay(40);
  Difference();
  delay(40);
  binToIntCalc();
  delay(40);
  check();
  delay(40);
  getMovePlayed();
  delay(40);
  getMove();
  delay(40);
  //}
}

void Print(int matrix[8][8])
{
  for(i=0;i<8;i++)
  {
    for(j=0;j<8;j++)
    {
      Serial.print(matrix[i][j]);
      Serial.print(" ");
    }
    Serial.println();
  }
}

void doAction()
{
  nextRow = 0;
  for(i=0;i<8;i++)
  {
    digitalWrite(38 + nextRow,LOW);
    delay(40);
    ReadSensor(i);
    digitalWrite(38 + nextRow,HIGH);
    delay(40);
    nextRow +=2;
  }
}

void ReadSensor(int iter)
{
  delay(10);
  for(j=0;j<8;j++)
    SensorValStore_Curr[iter][j] = digitalRead(j+2);
  Serial.print("----------------------------------------------");
  Serial.println("Value of sensory board after move is played");
}

void Difference()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
      temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);
  Serial.print("-----------------------Difference---------------------------\n");
  Print(temp);
}

void binToIntCalc()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
    {
      sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
      sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
    }
  Serial.print("---------------------sum1 and sum --------------------------\n");
  for(i=0;i<8;i++)
  {
    Serial.print(sum1[i]);
    Serial.print(" ");
  }
  Serial.println();

  for(i=0;i<8;i++)
  {
    Serial.print(sum2[i]);
    Serial.print(" ");
  }
  Serial.println();
}

void check()
{
  k=0;
  l=0;
  for(i=0;i<8;i++)
  {
    if(sum2[i]>sum1[i])
      k = i;
    if(sum2[i]<sum1[i])
      l = i;
    delay(40);
  }
}

void getMovePlayed()
{
  for(j=0;j<8;j++)
  {
    if(temp[k][j] == 1)
    {
      rank =k+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp = moveSan;
    }
  }
  for(j=0;j<8;j++)
  {
    if( temp[l][j] == 1)
    {
      rank =l+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp.concat(moveSan);
    }
  }
}

void SendMove(String movePlayed)
{
  Serial.println("start");
  Serial.print(movePlayed);
  Serial.println();
}

void getMove()
{
  while(1)
  {
    if(Serial.available()>0)
    {
      if(Serial.readString() == "Rstart")
      {
        bestMove = Serial.readString();
        lcd.setCursor(0,0);
        lcd.print(bestMove);
        delay(5000);
        lcd.clear();
        Serial.println(bestMove);
        exit(0);
      }
    }
  }
}

```

**PYTHON CODE**

```
import serial
from stockfish import Stockfish
s1 = serial.Serial('/dev/ttyACM0', 9600)
stockfish = Stockfish('/usr/games/stockfish')
while 1 :
    if str(s1.readline(),'UTF-8').strip('\n\r') == 'start' :
                move_played = str(s1.readline(),'UTF-8').strip('\n\r')
                print(move_played)
                // stockfish.set_position(move_played)
                // print("Rstart")
                // print(stockfish.get_best_move().encoded())
                break

```

# Answer
> -1 votes
It would help to see your code but bear in mind when you connect the serial monitor to your arduino it resets so any code will re-run

---
Tags: serial
---


# Question
Title: Arduino MEGA2560 wake up using DS3231 RTC
I am trying to set the Arduino MEGA 2560 R3 into sleep mode and wake it up with an RTC DS3231 via interrupt. I was following this tutorial: Tutorial

One of the libraries included is the "LowPower" library, you can find it here on GitHub. It produces the following error while compiling:

```
C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp: In member function 'void LowPowerClass::idle(period_t, adc_t, timer5_t, timer4_t, timer3_t, timer2_t, timer1_t, timer0_t, spi_t, usart3_t, usart2_t, usart1_t, usart0_t, twi_t)':

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:562:49: error: 'power_usart3_disable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_disable();

                                                 ^

C:\XX\Arduino\libraries\Low-Power-master\LowPower.cpp:597:48: error: 'power_usart3_enable' was not declared in this scope

  if (usart3 == USART3_OFF) power_usart3_enable();

                                                ^

exit status 1
Error while compiling for Arduino/Genuino Mega or Mega 2560.

```

I dont understand why there should be any functions in the library, which are not declared...This would mean noone could use it?! I am not an expert in C++ so maybe one of you could tell me what the issue could be. I am glad for any help.

# Answer
> 1 votes
after further web research, it looks like this is a bug which hasnt been fixed yet. it was discussed previously here and here.

My solution was to go into the "LowPower.cpp" scroll down to the lines, where the functions are not declared and I just out-commented them. Compiling works now.

---
Tags: arduino-mega
---


# Question
Title: To send data perpetually from multiple clients to a server using NodeMCU?
I am working on sending data from multiple clients to a server, all of which are NodeMCUs. I have been able to send data for a single iteration. Trouble arises when I want it to send data repeatedly so that if I update my client data, this new data should be reflected at the server as well.

Since I am using multiple clients, I have employed MAC addresses as the means of identifying the clients. This way, the signals received from a particular client are given as output to a particular pin.

To send data perpetually, I tried to use an infinite loop: `while(true)`, but it reads the first connected client even on recognizing the second client.

Here's my server code:

```
#include <ESP8266WiFi.h>
#define Max_Clients 5

extern "C" {
  #include <user_interface.h>
}

WiFiServer server(80); //Initialize the server on Port 80
WiFiClient *clients[Max_Clients] = {NULL}; //Initializing client(s)
String inputs [Max_Clients] ={""}; //Initializing to store the string received from clients

int32_t freq = 10000;

IPAddress remoteIP();

void setup() {
  pinMode(D1,OUTPUT); //Intializing pins for showing output and input
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(A0,INPUT);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window
  analogWriteFreq(freq);
  WiFi.mode(WIFI_AP); //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678"); //Provide the (SSID, password)
  IPAddress myIP = WiFi.softAPIP(); //Obtain the IP of the Server
  Serial.println("Server IP is: "); //Print the IP to the monitor window
  Serial.println(myIP);
  server.begin(); //Start the HTTP Server
}

void loop() {
  WiFiClient client = server.available(); //Check if a new Client has connected to the server
  unsigned char number_client;
  struct station_info *stat_info;
  struct ip_addr *IPaddress;
  IPAddress address;
  int k=0;
  if (client) {
    Serial.println("A new Client has connected :)");
   for (int i=0 ; i<Max_Clients ; ++i){ //Acknowledges and sets up new clients
    if (NULL == clients[i]){
      Serial.println(i);
      clients[i] = new WiFiClient(client); //nothing in clients[i] means it is a new client
      break;
    }
   }

   while (true){
    delay(3000);
    number_client = wifi_softap_get_station_num();
    stat_info = wifi_softap_get_station_info();
    Serial.println();
    Serial.print("Total connected clients are = ");
    Serial.print(number_client);
    Serial.println();
    while (stat_info != NULL){
      for(int i=0 ; i<number_client ; ++i)  { //For available clients
        if (NULL != clients[i]) {
          IPaddress = &stat_info->ip;
          address = IPaddress->addr;
          Serial.println();
          Serial.print("Client = ");
          Serial.print(i+1);
          Serial.println();
          Serial.print("Client IP Address = ");
          Serial.print(address);
          Serial.println();
          Serial.print("Client MAC Address = ");
          Serial.print(stat_info->bssid[0],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[1],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[2],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[3],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[4],HEX);
          Serial.print(":");
          Serial.print(stat_info->bssid[5],HEX);
          Serial.println();

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95) {
            Serial.println("Compared MAC address successfully - 1 :)");
            String request1 = clients[i]->readStringUntil('\r');
            Serial.print("Client 1 asks: ");
            Serial.print(request1);
            inputs[i] = request1;
            int duty1 = request1.toInt();
            analogWrite(D1,duty1);
            clients[i]->flush();
            k++;
            clients[i]->print("From Central Server to Client 1 - 150\r");
          }

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0x1F && stat_info->bssid[5] == 0x9D) {
            Serial.println("Compared MAC address successfully - 2 :)");
            String request2 = clients[i]->readStringUntil('\r');
            Serial.print("Client 2 asks: ");
            Serial.print(request2);
            inputs[i] = request2;
            int duty2 = request2.toInt();
            analogWrite(D2,duty2);
            clients[i]->flush();
            clients[i]->print("From Central Server to Client 2 - 200\r");
            k++;
            }

          if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x18 && stat_info->bssid[4] == 0xB && stat_info->bssid[5] == 0x71) {
            Serial.println("Compared MAC address successfully - 3 :)");
            String request3 = clients[i]->readStringUntil('\r');
            Serial.print("Client 3 asks: ");
            Serial.print(request3);
            inputs[i] = request3;
            int duty3 = request3.toInt();
            analogWrite(D3,duty3);
            clients[i]->flush();
            k++;
            clients[i]->print("From Central Server to Client 3 - 250\r");
          }

        if (k == 0){
            Serial.println();
            Serial.println("Client not recognised.");
          }

          stat_info = STAILQ_NEXT(stat_info, next);
          Serial.println();
        }
       }
      }
     }
    }
   } //void loop closure

```

Here's my client code:

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

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

WiFiClient client; // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()
IPAddress server(192,168,4,1);

void setup() {
  pinMode(A0,INPUT);
  pinMode(D6,OUTPUT);
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  Serial.begin(9600); //Serial connection
  WiFi.begin(ssid,password); //WiFi connection
  while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server, 80);   // Connection to the server
}

void loop() {
  if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
    while(true){
      int duty = analogRead(A0);
      client.print(String(duty)+"\r"); //Client's message to the server
      String answer = client.readStringUntil('\r'); //Reading response from the server
      Serial.print("Central Server: 200"); //Printing the response
      Serial.print(answer);
     }
   } else {
     Serial.println("Error in WiFi connection");
   }
}

```

Kindly suggest a solution. Thanks in advance.

# Answer
I found the error. The `if(client)` is to be closed before the `while(stat_info)` otherwise the loop will run only if it finds a new client. It is running fine now. Thank you everyone for the suggestions. :)
> 1 votes

# Answer
It's vital that either `loop()` return or that you call `yield()` or `delay()` in your `loop()` handler.

Your client code as it's written doesn't do that.

You don't need the `while(true)` at all. Take it out and leave the body of it in the `if` statement. `loop()` will be continuously re-entered and your code will keep running. `loop()` is already an infinite loop.

Leaving `while(true)` inside `loop()` means that `loop()` never returns. When it doesn't return, the SDK doesn't get to perform certain housekeeping functions that are necessary for its proper operation. In particular, networking functions may stop working correctly, so your call to `client.readStringUntil()` may not work correctly.
> 0 votes

---
Tags: esp8266, arduino-ide, nodemcu, wireless
---


# Question
Title: A minor confusion in digitalWrite command
Will the Arduino IDE interpret digitalWrite(13,x), where x\>0, as digitalWrite(13,HIGH)? And will it interpret digitalWrite(13,x), where x\<=0, as digitalWrite(13,LOW)?

# Answer
> 1 votes
Every other value than `0` or `LOW` will result in setting the pin to `HIGH`. In the following I explain why:

The function `digitalWrite()` can be seen in the file `hardware/arduino/avr/cores/arduino/wiring_digital.c`. The important lines here are:

```
if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

```

As you can see, it checks, if the given value (from the parameter) is equal to `LOW` and if so will set the corresponding pin to `0`. In every other case it will set the pin to `1`. The definition of `LOW` can be found in `arduino/hardware/arduino/avr/cores/arduino/Arduino.h`:

```
#define HIGH 0x1
#define LOW  0x0

```

So the code checks, if the value is equal to `0` and sets the pin also to `0`. Every other value will result in a `1` (meaning `HIGH`). Also have a look at the definition of `digitalWrite()`:

```
void digitalWrite(uint8_t pin, uint8_t val)

```

The value is an unsigned type, so every signed type will be casted to an unsigned type. A negative number would result in a positive number inside the function.

---
Tags: digitalwrite
---


title: ESP8266 light sleep - can't wake up

text:
# Question
Title: ESP8266 light sleep - can't wake up
I am attempting to implement a light sleep mode on an esp8266 (feather huzzah) which, when a button is pressed, wakes the system up so that it can continue its normal task.

I cobbled together some code from this post, which I've slightly modified:

```
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WAKE_PIN 5

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

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

    pinMode(WAKE_PIN, INPUT_PULLUP);
    gpio_init(); // Init GPIO pins
}

void loop(){
    Serial.println("Do something...");
    Serial.println(digitalRead(WAKE_PIN));
    delay(500); //random delay for that stuff to be done

    if(!digitalRead(WAKE_PIN)){ //if we don't detect pin, sleep
        sleep();
    }
    delay(1000);

}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_LOLEVEL);  //LO OR HI?
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(5000); //Sleep for short time
    delay(100);
    Serial.println("Woke up!");
}

```

Here is how I have things wired:

So the setup function works as expected, as well as "do something". The button reads high (1) when it is unpressed, and when I push it, it reads low (0) - which sends the ESP to sleep. In the serial monitor, I see:

```
Going to sleep...
Soft WDT reset

ctx: cont
sp: 3ffef7a0 end: 3ffef9a0 offset: 01b0

>>>stack>>>
3ffef950:  0001260d 00000600 3ffee970 4021fc84
3ffef960:  00001388 402020ba 402020b1 402020a1
3ffef970:  00000000 00000000 3ffee944 40202115
3ffef980:  3fffdad0 00000000 3ffee968 402027d4
3ffef990:  feefeffe feefeffe 3ffee980 40100710
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)

 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

```

I'm not very experienced with Arduino or Electric Engineering, so I'm not exactly sure what is happening vs. what should happen, but this is my interpretation:

I read somewhere that reset causes are as follows:

```
reset causes:
    0:
    1: normal boot
    2: reset pin
    3: software reset
    4: watchdog reset

boot device:
    0:
    1: ram
    3: flash

```

In which case, if `soft reset` is considered light sleep for the esp, then the `rst cause:2` is expected behavior, as it means it was triggered by pin 5. The `rst cause: 4` i'm not sure about though - watchdog reset. Seems to be a protective mechanism for the device, in which case maybe the reset of this must coincide with the reset triggered by sleep mode and is normal? Or does it indicate a crash? In any case, I have no idea what all the `stack` stuff is, but the system does not restart - I cannot get any further readings from the serial monitor after this.

I'm not sure whether `GPIO_PIN_INTR_LOLEVEL` should be high or low - I couldn't find documentation on this (though I did see it in the \[GPIO header source file\] on git.

I read something where someone else had a similar problem and someone made a reference to adding resistors and making sure GPIO 0 should be high, and 15 should be low. The link they posted was dead, but it made me think of something I read about deep sleep, in which you have to wire RST to 0. I actually tried running a wire between RST and holding to the `#0` pad that's right by the USB port on the feather huzzah, and after that, the code would actually go to sleep, then wake itself up automatically and resume the normal loop function - but what I want is for only the button to wake up the ESP.

I'm stuck from here. Anyone have any ideas of what might be happening and how to fix it?

# Answer
> 1 votes
You can make the ESP8266 wake from deep sleep by just pulsing RST low briefly. Crudely you can just use your switch to connect it to GND perhaps with a pullup resistor to +v. If you want to be a bit more elegant you could use a small capacitor to smooth out the switch bounce so your code only restarts once. I use this on an ESP8266 that is solar-powered. Most of the time it is in deep-sleep. It wakes up, connects to MQTT and deep sleeps again only when the sensor it is monitoring changes state.

---
Tags: esp8266, power, adafruit, sleep, pull-up
---


# Question
Title: How can I read servo motor readings via serial communication?
I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.

This is the Arduino code that I found on Google and edited it for my servo motor problem:

```
#include <Servo.h>
const int servoPin = 3;
int recValue; // received value from MATLAB
Servo Servo1;

void setup()
{
  Serial.begin(9600);
  Servo1.attach(servoPin);
}

void loop()
{
  if (Serial.available() > 0)
  {
    recValue = Serial.read();
    if  (recValue == 100)
    {
      Servo1.write(0);
      delay(1000);
    }
    if (recValue == 101)
    {
      Servo1.write(90);
      delay(1000);
    }
  }
}

```

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.

# Answer
> 1 votes
chrisl is quite right. You need to understand how MATLAB is talking to your Arduino. I suspect it is sending a sequence of characters for each servo angle instead of a single character. In your code you are waiting for 100 and 101, which are the ASCII 'd' and 'e' characters, and then acting immediately you have read one character. See if the servo will turn if you send 'd' or 'e'. If that works then what you need to do is read a whole line of ASCII characters e.g. '9' (which is 57) and '0' (which is 48) followed by a delimiter e.g. newline (13) At the beginning of line you can set int angle = 0 and each time you read a character multiply your angle by 10 and add in the new value by subtracting 48 from it. When you reach the delimiter you can then send the angle to the servo. Oh - and make sure MATLAB is talking at the right baud rate.

# Answer
> 0 votes
I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.

You don't have to convert anything here. The `Serial.read()` function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:

```
Servo1.write(recValue);

```

EDIT:

You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:

The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content `00100000` has a numerical value of `32`. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of `32`, you could mean the actual numerical value `32`, or you could mean the ASCII equivalent to `32`, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.

So you have to investigate, in which kind you are encoding the angle value. If you use `fwrite()` in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use `fprintf()`, you are sending the angle value as an ASCII encoded string. The value `32` from above would then occupy 2 bytes with the characters `3` and `2`, which correspond to the byte values of `51` and `50`. In this case you should add a delimiter character at the end in `fprintf()` (for example the newline character "\n") and use `Serial.parseInt()` to get the angle value from the string.

You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.

---
Tags: arduino-uno, serial
---


title: Using a DFRobot Voltage Divider

text:
# Question
Title: Using a DFRobot Voltage Divider
I'm reading on the DFRobot website to implement this Voltage divider: Analog Voltage Divider SKU: DFR0051

```
void setup()
{
  Serial.begin(9600);
}
void loop()
{
      float val;
      float temp;
      val=analogRead(2);//This divider module will divide the measured voltage by 5, the maximum voltage it can measure is 25V.
      temp= val/40.92;
      val=(float)temp;
      Serial.println(val);
      delay(1000);
}

```

Where does `40.92` come from? And even when printing only `VAL` it's something like `210` and I'm not sure what this is supposed to be. I don't get how to get the *actual* voltage of the battery etc. being measured? If it's divided by 5, why do you not multiply by 5 anywhere?

# Answer
> 1 votes
The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino. That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.

---
Tags: arduino-uno, sensors, voltage
---


title: Coding multiple servos in Arduino

text:
# Question
Title: Coding multiple servos in Arduino
I'm a first year persuing Mechatronic engineering, and I'm having trouble with this code that I am using to control a biped robot for my project.

```
#include <servo.h>
Servo myservoa;
           myservob;
           myservoc;
           myservod;
int     myservoa=10;
          myservob=55;
          myservoc=25;
          myservod=125;

void setup() {
    myservoa.attach(2)
    myservob.attach(3)
    myservoc.attach(4)
    myservod.attach(5)
}

void loop() {
    for pos=10;pos<=75;pos+=1;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1;
    {
        myservob.write(pos)
        delay (1800)
    }
    for pos=25;pos<=165;pos+=1;
    {
        myservoc.write(pos)
        delay (1000)
    }
    for pos=125;pos<=170;pos+=1;
    {
        myservod.write(pos)
        delay (1800)
    }
}

```

Could there be an error in the code?

# Answer
> Could there be an error in the code?

You could say that, yes. Let's list all the syntax errors to start with:

```
#include <servo.h>
Servo myservoa;
           myservob; // This has no type. It's just a word by itself.
           myservoc; // This has no type. It's just a word by itself.
           myservod; // This has no type. It's just a word by itself.

int     myservoa=10; // You already defined myservoa as a Servo type.
          myservob=55; // This has no type. It's just a word by itself.
          myservoc=25; // This has no type. It's just a word by itself.
          myservod=125; // This has no type. It's just a word by itself.

void setup()
{
    myservoa.attach(2) // Semicolons must terminate all statements.
    myservob.attach(3) // Semicolons must terminate all statements.
    myservoc.attach(4) // Semicolons must terminate all statements.
    myservod.attach(5) // Semicolons must terminate all statements.
}

void loop()
{
    for pos=10;pos<=75;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservob.write(pos)  // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
    for pos=25;pos<=165;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoc.write(pos) // Semicolons must terminate all statements.
        delay (1000) // Semicolons must terminate all statements.
    }
    for pos=125;pos<=170;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservod.write(pos) // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
}

```

You really need to get to grips with the syntax of a language before you start programming in that language. I count just 6 lines (not including { and }) of valid C code there, and two of them are handed to you by the IDE.
> 3 votes

---
Tags: programming
---


# Question
Title: Why is my esp8266 still visible under "available connections" when connecting to WiFi?
I wrote a "Hello world" type of sketch using the Arduino IDE and uploaded it to an esp8266. I used no libraries, or any kind of WiFi commands. However, when I powered up the esp8266, it was visible under "available connections" when I connected to WiFi using a Windows laptop. I was told that the firmware on an esp8266 (which has the AT commands) is being flashed when the Arduino IDE uploads a sketch. Why do I still see the esp8266 when my laptop connects to WiFi?

# Answer
> 2 votes
It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch. The WiFi code is always included and always running regardless of what you include or don't include in your sketch.

Uploading a sketch doesn't replace those settings, and so they remain.

To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.

If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools menu in the IDE to Erase Flash.

---
Tags: esp8266, wifi, firmware
---