# Question
Title: Want to display an image from SD card to ILI9486 LCD display
I am completely new to Arduino. I have been given a side project to display a image from SD card to display. LCD used is ILI9486 which has a SD card slot at the back of the display module. I have inserted an 1 GB micro SD card. I am using below example code to try to open the SD card and display the image on display module. I am getting error on serial monitor "Initializing sd card - failed". Can anyone let me know how to display image from SD card to screen.

```
#include <SD.h>
#include <SPI.h>
#include <TFT.h>  // Arduino LCD library

// pin definition for the Uno
#define sd_cs  4
#define lcd_cs 10
#define dc     9
#define rst    8

TFT TFTscreen = TFT(lcd_cs, dc, rst);

// this variable represents the image to be drawn on screen
PImage logo;

void setup() {
    // initialize the GLCD and show a message
    // asking the user to open the serial line
    TFTscreen.begin();
    TFTscreen.background(255, 255, 255);

    TFTscreen.stroke(0, 0, 255);
    TFTscreen.println();
    TFTscreen.println(F("Arduino TFT Bitmap Example"));
    TFTscreen.stroke(0, 0, 0);
    TFTscreen.println(F("Open serial monitor"));
    TFTscreen.println(F("to run the sketch"));

    // initialize the serial port: it will be used to
    // print some diagnostic info
    Serial.begin(9600);

    while (!Serial) {
        // wait for serial port to connect. Needed for native USB port only
    }

    // clear the GLCD screen before starting
    TFTscreen.background(255, 255, 255);

    // try to access the SD card. If that fails (e.g.
    // no card present), the setup process will stop.
    Serial.print(F("Initializing SD card..."));
    if (!SD.begin(sd_cs)) {
        Serial.println(F("failed!"));
        return;
    }
    Serial.println(F("OK!"));

    // initialize and clear the GLCD screen
    TFTscreen.begin();
    TFTscreen.background(255, 255, 255);

    // now that the SD card can be access, try to load the
    // image file.
    logo = TFTscreen.loadImage("arduino.bmp");
    if (!logo.isValid()) {
        Serial.println(F("error while loading arduino.bmp"));
    }
}

void loop() {
    // don't do anything if the image wasn't loaded correctly.
    if (logo.isValid() == false) {
        return;
    }

    Serial.println(F("drawing image"));

    // get a random location where to draw the image.
    // To avoid the image to be draw outside the screen,
    // take into account the image size.
    int x = random(TFTscreen.width() - logo.width());
    int y = random(TFTscreen.height() - logo.height());

    // draw the image to the screen
    TFTscreen.image(logo, x, y);

    // wait a little bit before drawing again
    delay(1500);
}

```

# Answer
Make sure your SD card is Fat16 format. At least that was a requirement of the test code I had on the same sort of display.
> 1 votes

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


# Question
Title: avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47
So I'm following a beginners arduino book and I made a blinking program and now I've coded another program but when I try to upload it, avrdude(whatever that is) gives me the errors in the title and repeats them 10 times. I have tried this so far:

* Restarting my windows 8
* Pressing the reset button on my arduino uno R3

My guess is that since it worked the first time, my blinking program must be clogging up the space in my arduino.How can I fix this problem. Or if my guess is right, how can I get the blinking program out of arduino and go home to my bots folder?

My IDE is arduino 1.6.7 and my port is CPU1. and lots of people mention tools\>serial port but there isn't a "serial port" button on my IDE.

# Answer
I had the same exact problem and fixed it, just by molding the two reset pins on the arduino together. Just check if they are properly connected as the error probably is caused by that.

If that doesn't work, check the LEDs on the board. When you are uploading a sketch both RX and TX should be lightning up.
> 2 votes

# Answer
Just search a little bit around Google.

A simple solution is pressing the restart button after the program is compiled, then, upload it.

Or restart the Arduino while the Arduino is uploading the program.

If the problem remains, try to **burn again the bootloader of your arduino.**
> 0 votes

# Answer
You're probably trying to connect through the wrong port.

I had this problem due to the mac suddenly making the /dev/cu.USB port option unavailable for selection through the arduino software interface under tools/port, and then not knowing what I was doing I just tried to connect through the wrong port and got this error.

After rebooted the mac, voila the /dev/cu.USB port option was suddenly available again under tools/port, we selected it and were able to successfully upload again.

I don't know why the mac or arduino software does this, my sense is that something must get confused during upload sometimes, especially if you disconnect and reconnect the usb for some reasons, or turn on the 9v power on the arduino board while uploading.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino IDE / Specified folder/zip file does not contain a valid library
I trying to add library here but it doesn't seem to work https://github.com/esp8266/Arduino

This happens "Specified folder/zip file does not contain a valid library"

This problem make me no longer upload any library. any solution about this?? Manual installation does not either.

# Answer
> 1 votes
You don't install that repository as a Arduino library.

**Read the README file in that repo**. It explains how to install it using the Arduino IDE Board manager. That's the correct way to install it.

---
Tags: esp8266
---


title: About Wemos D1 WiFi

text:
# Question
Title: About Wemos D1 WiFi
I bought the Wemos D1 WiFi and I am wondering how to operate this. So, inside the Arduino IDE, I downloaded ESP8266 boards, I see WeMos D1 mini, WeMos D1 R1, and WeMos mini Pro/Lite.

Why in the world don't I see Wemos D1?

How can I operate this board without the D1 board to select in the Arduino IDE?

Is there a way to add, or anyways to operate it?

I don't mind using other software besides the Arduino IDE if it's the only way to work with D1.

Board:

I get this Error when trying to upload D1 R1:

```
C:\...\ArduinoData\packages\esp8266\tools\esptool\2.5.0-3-20ed2b9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM6 -ca 0x00000 -cf
C:\...\Temp\arduino_build_179604/sketch_jan15a.ino.bin
esptool v0.4.13-1-gf80ae31 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
setting board to nodemcu
setting baudrate from 115200 to 115200
setting port from COM1 to COM6
setting address from 0x00000000 to 0x00000000
espcomm_upload_file
espcomm_upload_mem
setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
flush start
An error occurred while uploading the sketch
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
read 0, requested 1
trying to connect
flush start
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
espcomm_send_command: receiving 2 bytes of data
Uploading 287488 bytes from
C:\...\arduino_build_179604/sketch_jan15a.ino.bin to flash at 0x00000000
erasing flash
size: 046300 address: 000000
first_sector_index: 0
total_sector_count: 71
head_sector_count: 16
adjusted_sector_count: 55
erase_size: 037000
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
setting serial port timeouts to 15000 ms
read 0, requested 1
setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
flush start
setting serial port timeouts to 1 ms
setting serial port timeouts to 1000 ms
flush complete
error: espcomm_upload_mem failed

```

# Answer
> 2 votes
Your board is a WeMos D1 R1. You need to select **Tools \> Board \> WeMos D1 R1** in the Arduino IDE.

Here's a good comparison of the difference between the WeMos D1 R1 and the WeMos D1 R2: https://github.com/arendst/Sonoff-Tasmota/wiki/Wemos-D1-R1-&-R2

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


# Question
Title: Adding a custom board to the Arduino IDE
I would like to know what is the procedure for adding a custom board to the Arduino IDE?

My custom board is similar to the Arduino Zero. Instead of using the ATSAMD21G18, my board is based around the ATSAMC21G18. I also have the Atmel/Microchip SAMC21 Xplained development board.

I have found some open source code where the author has adapted/forked the Arduino SAMD21 code and made it work for the SAMC21 Xplained board (here). The author has stuck to the Arduino hardware folder structure and has added the SAMC21 Xplained to the `board.txt` file.

As a test, when I install the Arduino SAMD21 from the Arduino Board Manager, I noticed that it installed the hardware files in the following directory:

```
 %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\1.6.19\

```

I have read that to add hardware files to the board manager I need to create a `.json` file with the appropriate details. More information here. However, as far as I can tell, this requires me to zip the SAMC21 hardware files into a tarball and provide a URL to that tarball. I also need to generate and insert a SHA in the `.json` file.

Am I on the right path with the `.json` file?

Or should I just download the SAMC21 hardware files and place them in the `%LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\` folder next to the `1.6.19` folder?

My last resort would be to just copy the files into the existing SAMD21 hardware folder?

---

I have looked into the following Arduino SE questions but they do not answer the question satisfactorily.

# Answer
The simplest clean way to add your board using an existing core is to add the variant to your sketches folder's hardware subfolder. Only boards.txt and files for the board variant are added.

In your sketches folder create a 'hardware' folder. In this folder create a folder with the name of your boards package and a subfolder with the architecture name and a subfolder for variant and a name of the variant. for example `hardware/my_boards/samd/variants/samc21x`

In your variant folder (`variants/samc21x`) put the files for your variant based on variant files of the closet variant in the referenced hardware package. In your case perhaps a mkrzero would be a good example.

In your package's root (`hardware/my_boards/samd/`) add boards.txt file with entries for your board.

For boards.txt take the options for a similar board in referenced package. Change the names and settings and prefix `build.core` value with the name of the vendor of the referenced package. For arduino/samd it would be `arduino:`. For example `samc21x.build.core=arduino:arduino`

My custom and customized boards definitions https://github.com/jandrassy/my\_boards
> 10 votes

---
Tags: arduino-ide, samd21g, custom
---


title: Arduino hangs after some time

text:
# Question
Title: Arduino hangs after some time
I am using Atmega328p with 5V power supply, My Arduino getting hangs \[or auto restarts\] after some times.

I am using libraries:

* Wire.h
* CRC32.h
* EEPROM.h
* Arduino.h
* TimerOne.h
* RtcDS3231.h
* SoftwareSerial.h
* Adafruit\_NeoPixel.h
* avr/wdt.h

I have tried to search, some people are deny to use software serial library.

# Answer
> 3 votes
Not sure if this will fix your problem, but this is a major error:

```
  char buf1[8], buf2[6];
  sprintf(buf1, "%08lu", myvote.mydate);
  sprintf(buf2, "%06lu", myvote.mytime);

```

Take a look at sprintf function reference

> A terminating null character is automatically appended after the content.

So, the text buffers are too small. It should be at least:

```
char buf1[9], buf2[7];

```

---
Tags: arduino-mega, atmega328
---


# Question
Title: Need help with the syntax for a function that takes a closure
My C++ is very out-of-date. (20+ years, before C++ *had* closures).

I'm a senior SW engineer, and I spent several hours yesterday trying to figure this out, but I could not work it out.

**The background:**

I'm trying to create a class, `ClosureButton`, that is a subclass of another class, `ArduinoObject`. (An `ArduinoObject` has `setup()`, `start()`, `stop()`, and `loop()` methods so that the main program can invoke it.)

(C++ uses the terms closure and lambda to mean different things. In other languages the terms are interchangeable. Forgive me if I'm not using the correct term.)

A ClosureButton's constructor would take a pin number, and a closure with a bool parameter (`pressed`). I would save that closure to a member variable. When the button's state changed, it would invoke the closure and pass the new button state to the closure.

**The question:**

I need help with the syntax for the constructor, as well as how to declare the instance variable that would hold the closure.

The constructor would look something like this:

```
ClosureButton::ClosureButton(uint8_t pin, _unkonwn_syntax_ closure);

```

(Where I need help with the `_unkonwn_syntax_` bit.)

Then I need to declare a member variable on my ClosureButton to hold the closure:

```
class ClosureButton: ArduinoObject {
  //other stuff
  _other_unkonwn_syntax_ closure;
}

```

Again, I need help with the syntax to declare a member variable `closure` of type "closure that takes a bool parameter". (The `_other_unkonwn_syntax_` bit.) At this point I don't think my closure will capture variables from its enclosing scope, but at some future date I might need to do that, so help with that would be appreciated as well.)

# Answer
> 2 votes
There is no difference using a function pointer or a simple (non-capturing) lambda (C++ calls them lambdas). The only difference is that you provide a lambda instead of a function pointer.

For example:

```
void (*func)(bool b);

void setup() {
    func = [](bool b) {
        Serial.println(b);
    };

    Serial.begin(115200);
}

void loop() {
    func(digitalRead(0));
}

```

It's just a normal function pointer, but instead of assigning a function pointer to it you assign a lambda to it - which is just an anonymous function pointer.

To make life easier you can make a typedef for your function pointer variable type:

```
typedef void (*buttonCallback)(bool);

```

Then your functions would look like:

```
ClosureButton::ClosureButton(uint8_t pin, buttonCallback closure);

```

and:

```
class ClosureButton: ArduinoObject {
  //other stuff
  buttonCallback closure;
}

```

The basic syntax of a lambda is quite straight forward:

```
[](bool foo, int bar) { ... }
^  ^                    ^
|  |                    +- Function body
|  +- Normal parameter list
+- Empty capture list

```

If you want to return a value and you don't want to rely on the function being an "auto" return type you can specify the return type after the parameter list:

```
[](bool foo, int bar)->int { ... }
^  ^                   ^     ^
|  |                   |     +- Function body
|  |                   +- Return type
|  +- Normal parameter list
+- Empty capture list

```

If you don't specify the return type it is inferred from the type of variable/value that is used with `return` (as if the function were `auto`).

---

Here's a full example passing the lambda to a class which stores the pointer to it in a variable to call later:

```
typedef int (*callback)(bool b);

class MyClass {
    private:
        callback func;
        int pin;

    public:
        MyClass(int pinno, callback myfunc) {
            func = myfunc;
            pin = pinno;
        }

        void doit() {
            Serial.println(func(digitalRead(pin)));
        }
};

MyClass foo(3, [](bool b)->int {
        Serial.println(b);
        return rand();
});

void setup() {
    pinMode(3, INPUT_PULLUP);
    Serial.begin(115200);
}

void loop() {
    foo.doit();
    delay(100);
}

```

---

If you want to do capturing with your lambdas then I'm afraid you're out of luck.

The data type for that kind has to be `std::function<void>` but unfortunately the cut-down C library AVR-LIBC doesn't support that. The STL is generally not included for small microcontrollers since it uses far too many resources to be practical.

# Answer
> 1 votes
I suggested in a comment that a functor may be a viable alternative to a capturing lambda. This answer is mostly meant to answer the OP's request to elaborate on that suggestion.

Let's define a `ButtonCallback` as an object that can be called like a function taking a single boolean parameter:

```
class ButtonCallback {
public:
    virtual void operator()(bool) = 0;
};

```

To break down the syntax:

* `void operator()(bool)` declares a method that allows the object to be called as if it were a function taking a `bool` argument and returning nothing. In other words, if you issue a call such as `my_object(true)`, that method will be called.
* `virtual _method_declaration_ = 0;` says that the method is not going to be defined for this class (it's a “pure virtual method”), but it can be defined by derived classes. A class with such a method is called an “abstract class”: it defines an interface, it cannot be instantiated, and it's meant to be used as a parent for classes that do implement the missing methods.

Now the `Button` class can be defined like this:

```
class Button {
public:
    Button(uint8_t pin, ButtonCallback &callback)
    : pin(pin), callback(callback) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true);
        Serial.print("release: "); callback(false);
    }
private:
    uint8_t pin;
    ButtonCallback &callback;
};

```

Notice that the callback is stored as a *reference* to a `ButtonCallback` object. The object itself cannot be stored because it has an abstract type. Alternatively, a pointer could be used, which would practically be equivalent.

For using this class, you first have to create the callback as a concrete class that inherits from from `ButtonCallback`. Any data you wish to capture should be stored as class data:

```
class CapturingLambda : public ButtonCallback {
public:
    CapturingLambda(int data) : some_data(data) {}
    virtual void operator()(bool pressed) {
        if (pressed)
            Serial.println(some_data);
        else
            Serial.println(0);
    }
private:
    int some_data;
};

```

With all this in place, the following test:

```
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    CapturingLambda callback(data_to_capture);
    Button the_button(2, callback);
    the_button.push();
}

void loop(){}

```

outputs:

```
press: 42
release: 0

```

Did you said you “find the syntax of C++ pretty obtuse”? I can only concur with you!

---

**Addendum**: Another alternative is to define the callback using the good old C idiom: a “lambda” is the combination of a function pointer and a generic data pointer. The function pointer looks like this:

```
typedef void (*ButtonCallback)(bool, void *);

```

The second argument is used to provide the callback whatever data it is supposed to have “captured”. It is a generic pointer (a `void *`) because the library does not know what kind of data its client may need. Now the `Button` class has to store *both* the function pointer and the data pointer, and always provide the data pointer to the callback:

```
class Button {
public:
    Button(uint8_t pin, ButtonCallback callback, void *callback_data)
    : pin(pin), callback(callback), callback_data(callback_data) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true, callback_data);
        Serial.print("release: "); callback(false, callback_data);
    }
private:
    uint8_t pin;
    ButtonCallback callback;
    void *callback_data;
};

```

The user would have to decide what kind of data it needs, and do explicit pointer casts to/from the proper pointer type and `void *`. For example, assuming we need an `int`, the callback may be:

```
void callback(bool pressed, void *data) {
    int *actual_data = (int *) data;
    if (pressed)
        Serial.println(*actual_data);
    else
        Serial.println(0);
}

```

Here is the test, with the exact same output as before:

```
void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    Button the_button(2, callback, (void *) &data_to_capture);
    the_button.push();
}

void loop(){}

```

Notice that, syntactic differences apart, this solution does essentially the same as the previous one. The main difference is that the data is given to the callback as an explicit pointer instead of the implicit `this` pointer. If you have to choose between these two solutions, I would suggest going for whichever syntax *you* find easier to work with.

Beware also that in both cases it is the programmer's responsibility to manage the storage of the callback data and make sure the corresponding reference (or pointer) remains valid throughout the lifetime of the `Button` object.

---
Tags: programming, c++
---


title: Need some help on a very small project

text:
# Question
Title: Need some help on a very small project
Apologies for the simple question, I really couldn’t find any help online with this as when I kept searching, the results had lights that had way too much voltage compared to what I need.

So I have a simple light decoration that requires around 3v and comes with a battery pack to power it (2AA batteries) and I took it apart and was able to connect them via a breadboard to test if is all working.

How do incorporate the Arduino into it so that I can switch the lights on through the Arduino? A lot of the small voltage videos I saw were just simple connecting 1 LED through a digital pin but that’s not enough current for the lights I have and I’m not experienced enough to find myself a solution so help would be greatly appreciated.

For little more info, the 3.3v and 5v pins my Arduino (uno) are already taken up.

Also, I’ll be turning the lights on and off with an IR Remote which I’ve already programmed to a servo that’s powered through the USB supply (5v) and the IR Sensor is connected to the 3.3V.

Sorry if the question was badly worded.

# Answer
I think I managed to make a little circuit that should prevent you from burning up your Arduino.

From what I read you shouldn't connect MOSFET directly to Arduino. Imagine that MOSFET has a little capacitor inside it, and in the beginning that capacitor can take such high current that actually can burn the Arduino pin. Instead you use a simple NPN transistor (with 100kohm resistor) as a "switch". The NPN can survive much higher current, and it will not strain the Arduino pin.

When I simulated this setup using the default "blink" sketch the light bulb was lit when PIN13 was HIGH. Just note that there always is a small voltage drop (think of it as a resistor inside the MOSFET) and it can make the MOSFET get a little warm. In your setup it should not be a problem, but in some cases it's nice to screw a radiator on the MOSFET.
> 0 votes

---
Tags: arduino-uno, hardware
---


# Question
Title: Power a Raspberry Pi 3 from an Arduino Uno
I would like to power my Raspberry Pi 3B using an Arduino Uno.

I have been able to do this by connecting the 5v on the Arduino to the 5 V on the Pi and connecting the GND to GND, and the Pi turns on. But I get a constant under voltage sign.

How can I get the Arduino to output the right amount of power (5 V and 2.5 A)?

# Answer
> 3 votes
You can't.

The on-board regulator of the Uno, the NCP1117, is only able to supply up to 1A before starting to dropout voltage (hence your undervoltage warning).

Even worse, because the NCP1117 lacks a proper heatsink, it will probably start dropping out voltage before reaching 1A, due to its internal thermal shutdown protection.

# Answer
> 1 votes
If you are using PC USB, your total current cap is \<500mA. Arduino + Pi + accesories is exceed this cap.

Use an adapter for Arduino. Ardiuno will suck up some current and rest can flow to Pi or whatever else is there.

Arduino has a linear voltage regulator. Try not to use \>5v adapters. Voltage regulator will generate more heat as more current pass.

# Answer
> 1 votes
If you reverse which board gets the power adapter you should be able successfully power them both from a single 5V 2.5A power supply.

Connect the power adapter to the Raspberry Pi3 and power the Arduino from the Pi's 5V pin. The Uno should only draw about 200mA @ 5V from the Pi (depending on everything else you have connected).

---
Tags: arduino-uno, power, raspberrypi
---


# Question
Title: Serial not declared in this scope, newbie mistake most likely
Ok, newguy with a little VBA coding experience going to pull hair out soon. It is probably a simple thing I have missed but I would like someone to point out where I went wrong. I modified a sketch that used an lcd to use the serial monitor instead but I sometimes run into this "not declared in this scope" issue. Doing something wrong, please point me in the correct direction.

```
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;
DateTime now;
char daysOfTheWeek[7][12] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

void showDate(void);
void showTime(void);
void showDay(void);

void showDate()
{
  serial.print(now.day());
  serial.print('/');
  serial.print(now.month());
  serial.print('/');
  serial.print(now.year());
}

void showDay()
{
  serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
}

void showTime()
{
  serial.print("Time:");
  serial.print(now.hour());
  serial.print(':');
  serial.print(now.minute());
  serial.print(':');
  serial.print(now.second());
  serial.print("    ");
}

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

  serial.println("working....")
  //wire.begin();
  //delay(2000);
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC Module");
    while (1);
  }

  if (rtc.lostPower())
  {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop ()
{
  now = rtc.now();
  showDate();
  showDay();
  showTime();
}

```

# Answer
Case matters in C/C++. You should write `Serial` rather than `serial`.
> 3 votes

---
Tags: programming
---


# Question
Title: iBus transmission and read it in Arduino
I am using an Arduino Uno and I want to transmit data from FSi6 to FS-iA6B and read received data in an Arduino. After searching, I found the below link which is **iBUStelemetry**.

iBustelemetry

I am not able to make out how to get the data from this library and print it on the serial monitor.

I have hooked up receiver ground and power pins to ground and power pins of Arduino. Signal from the receiver is connected to D2.

The author has included an example, but I am not much clear how data is read and printed on the serial monitor.

Can someone please help by telling how do I read data from receiver using this library?

# Answer
If I understand correctly, the code should look like this.

```
#include <iBUStelemetry.h>
iBUStelemetry telemetry(4);
byte i;

void setup(){
 Serial.begin(115200);
 telemetry.begin(115200);
 telemetry.addSensor(2);
}

void loop(){
 telemetry.setSensorMeasurement(1, i++);
 delay(1000);
 Serial.println(telemetry);
 //or
 Serial.println(telemetry.setSensorMeasurement(1, i++));
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Failsafe Arduino

text:
# Question
Title: Failsafe Arduino
I want to read an RFID tag using an Arduino, which controls some relais. This is easy.

For me the more complex part is to build it fault-tolerant. So I thought I could use the watchdog. The tricky part is, my relais module should keep a certain state (change of state is rare), no matter what happens to the Arduino.

My first thought was to put some condensators to the relais. Calculate the RC component so it can last the watchdog timeout plus booting up.

Now there is the problem, that the relais module is keeping its state while booting. I guess I can't use a pull up/down resistor, since the state of the relais can be low or high at random.

My second thought was using a latch relay. But this has the disadvantage, that it probably can hide problems. For example if the arduino died, and the latch relay holds a certain state, it masks the problem. In that case it's not possible to notice a faulty Arduino.

1. Those are the reasons I tend to think condensators are better?
2. Are those ideas feasible? Are there easier ways to accomplish this?
3. Are there more problems to think about?

(I was already reading about millis at gammon's page. Apparently it's not a problem after all.)

# Answer
> 2 votes
Consider constraining your design with clear requirements. As it is highly unlikely any design can protect its self for all situations.

> my relais module should keep a certain state (change of state is rare), no matter what happens to the arduino

Consider latching relays where there is a set coil and a reset coil. Such as this one. Such a device does not need to be continuously powered. Only pulsed to set and a pulsed to reset.

> So I thought I could use the watchdog.

Watchdog timers are fine if your program can get stuck waiting for an event that may never happen. Like waiting to read the data from and RFID chip. If you think this might happen, then add the watchdog timer to your design.

> Now there is the problem, that the relais module is keeping its state while booting.

Most embedded processors with bi-directional GPIO pins force those pins to be inputs when booting up. This appears as high impedance to the outside world. Consider using pull ups or pull downs on these pins to prevent them from floating to a state which may change the relays during booting of the processor.

---
Tags: arduino-uno, relay
---


title: Simultaneous button reading?

text:
# Question
Title: Simultaneous button reading?
I'm currently working on a project that requires that I simultanously check the state of two buttons. Each button HIGH state is assigned to one if loop. Here's the basic concept:

```
void loop() {
  S1_State = digitalRead(S1_Pin);
  S2_State = digitalRead(S2_Pin);
  ButtonPRESSED = false;

  P1_Time = random(2000, 5000);
  delay(P1_Time);
  digitalWrite(P1_Pin, HIGH);

  while(ButtonPRESSED == false) {
    if (S1_State == HIGH) {
       Serial.print("Player 1 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
    if (S2_State == HIGH) {
       Serial.print("Player 2 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }

```

The problem is that checking for the button states this way requires that the S1\_State loop \_has to be read before the S2\_State loop\_, thus giving player 1 an advantage. Although I'm not sure how pronounced this issue is in practice, it certainly was noticable when I was first trying this project out through python code on a Pi through similar means.

Is it possible check the conditions to both if loops simultanously? If not, are there other ways to circumvent this problem?

# Answer
There is a very easy solution to your problem, and it's called "interrupts".

The processes inside `loop` method are executed synchronously, so always one read will be done before second one, and always one check will be done before a second one (even if they are inside one `if` statement)

Fortunately there is a way of simulating asynchronous behavior in ATmega. It's called "external interrupt". You can setup ATmega inside Arduino to stop processing `loop` method and instead immediately run a different method whenever a voltage on one of the pins change. You are "interrupting" execution of `loop` hence the name "interrupt". In Arduino Uno this can be done (only) on pins 2 and 3.

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I made a little model i Tinkercad

Whenever you push left button PIN2 of the Arduino gets shorted to ground. Whenever you push right button PIN3 of the Arduino gets shorted to ground.

And now my source code

```
void setup()
{
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  interrupts();
  attachInterrupt(digitalPinToInterrupt(2), Player1ButtonPress, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), Player2ButtonPress, FALLING);

  Serial.begin(9600);
}

void Player1ButtonPress() {
  Serial.println("Player 1 wins");
}

void Player2ButtonPress() {
  Serial.println("Player 2 wins");
}

void loop()
{
    //nothing here
}

```

And now some explanation. In `setup` we first setup PIN2 and PIN3 as "input with pullup resistor". In our design this means that when button is not pressed those pins will have 5V on them, but as soon as the buttons are pressed voltages go down to 0V. Then we make sure that `interrupts` are turned on (they are on by default, but I like to show everyone who is reading the code that I will be using them) and then we do some `attachInterrupt` magic. We make that a "falling edge" (change from 5V to 0V) on PIN2 and PIN3 will immediately run methods `Player1ButtonPress` and `Player2ButtonPress`.

When I was playing with buttons they worked perfectly.

And a word about possible cheating. Keeping the button pressed does not create a "falling edge" (voltage on a pin is constantly 0) so if you only add some global variables with info when game starts and who won. Then add some conditions in the two methods responsible for interrupts. You can then use the `loop` method to start the game, and show result.
> 11 votes

# Answer
Instead of using the high level digitalRead() function access the low level port registers. See this documentation.

A port register is one byte and each bit represents one of the digital inputs on the arduino.

Do something like this:

```
pin_status = PIND; //Input port D (pins 0-7)
button_1 = bitRead(pin_status, 2); // digital pin 2
button_2 = bitRead(pin_status, 3); // digital pin 3

```

The values are read simultaneously so it is possible to have a tie.
> 12 votes

# Answer
I think you want after a random time, a 'Start' LED to be lit, and whoever presses his/her button first wins.

There are some problems in your sketch:

* It seems even when a button is pressed to early, the button is still taken into account. You should check for this 'cheating'. So check directly after the 'start' LED is lit, that no buttons are pressed. If so, that player loses.
* Assuming the players are honest, you check for their buttons, which probably the first iteration it will not be pressed (that would be an immediate reaction speed). However, than you wait 5 seconds; probably both players pressed their buttons, and you check the button of the first player first. It will help, if you change the delay to 1 ms, or even remove it completely.

Untested proposal:

```
int playerXWon = 0; // No player won yet, 1 = player 1 wins, 2 = player 2 wins, 3 = draw

void loop()
{
   // Delay for a random time.
   P1_Time = random(2000, 5000);
   delay(P1_Time);

   CheatCheck();

   if (playerXWon == 0)
   {
      // Start
      digitalWrite(P1_Pin, HIGH);

      checkFirstPress();
   }
}

void CheatCheck()
{
   // Check if a player did not press its button too early.
   // (Btw, it does not matter if the player presses and release its button before the LED goes on.
   S1_State = digitalRead(S1_Pin);
   S2_State = digitalRead(S2_Pin);

   if (S1_State == HIGH)
   {
      else if (S2_State == HIGH)
      {
         PlayerWin(3);
      }
      else
      {
         PlayerWin(2);
      }
   }
   else
   {
      if (S2_State == HIGH)
      {
         PlayerWin(1);
      }
   }
}

void checkFirstPress()
{
   // Whoever presses first wins.
   while (playerXWon == 0)
   {
      S1_State = digitalRead(S1_Pin);
      S2_State = digitalRead(S2_Pin);

      if (S1_State == HIGH)
      {
         if (S2_State == HIGH)
         {
            PlayerWin(3);
         }
         else if (S1_State == HIGH)
         {
            PlayerWin(1);
         }
      }
      else if (S2_State == HIGH)
      {
         PlayerWin(2);
      }
   }
}

void playerWins(int player)
{
   switch (player)
   {
   case 1:
      Serial.print("Player 1 wins\n");
      break;

   case 2:
      Serial.print("Player 2 wins\n");
      break;

   case 3:
      Serial.print("Both players win\n");
      break;

    default:
       assert(NULL); // Programming error
       break;
   }

   playerXWon = player;

   digitalWrite(P1_Pin, LOW);
}

```
> 3 votes

# Answer
I was not sure about posting this as an answer, since it is basically some more considerations on the three existing answers (for reference, they are Michel Keijzers's one - using digitalRead -, Craig's one - read the PIND variable at once -, Filip Franik's one - use interrupts), but it became quite long and so a single comment could not fit all of this.

What you and the other answerers wrote is in theory correct. Checking the button of player 1 before player 2 gives an advantage to player one. What you lack is... How much advantage?

Mechanical actions (such as the pressing of a button) have a time duration that is around 50ms\*.

Since I assume your application is a reaction time tester, human reaction times are around 250ms.

Moreover mechanical buttons have "bounces". Typical debounce times are in the range 20-100ms. You can avoid this by just checking the first edge.

A player gets an advantage if he is awarded as winner even if the button was pressed at the same time.

---

\_* I tried to find a source for this, but I was not able to get some data. I tried with an online stopwatch and pressing the two spacebars (notebook and USB keyboard) roughly at the same time, obtaining results around 75ms. This is not a real value, so if someone has some measured values or estimations feel free to comment

---

Now, let's assume you properly coded your program so that you check for ties and avoid delays, since these will greatly affect the following measurements.

**In the `digitalRead` case** you are executing this series of actions:

1. Read status of pin 1 - 3.6us
2. Read status of pin 2 - 3.6us
3. Check the statuses and decide who won - some tens of instructions (about 1us)
4. Loop - a couple instructions (0.5us)

The 60 instructions comes from this thread (3.6us = 57.8 instructions @16MHz); as for the others it's a rough measurement. Let's assume that the function actually samples the pin at the very end of the function.

Now, since you are checking for ties, if both buttons get pressed during phases 3, 4 or 1 you will get a tie (since both buttons will be read as pressed). If both buttons get pressed during phase 2, button 2 will be marked as pressed and button 1 not, thus giving advantage to that player. The time when this happens is about 3.6us long. So you are giving a 3.6us advantage to button 2 player.

**In the PIND case** you are reading the buttons exactly at the same time. The advantage is thus 0.

**In the interrupt case** when both EXT0 and EXT1 interrupts are triggered at the same time EXT0 gets executed, since it is before in the ISR. Consequently the player pressing the button on EXT0 has one interrupt checking cycle of advantage. I admit I do not know how often the inputs are checked for the EXT interrupt, but I assume it performs a check every clock cycle (consequently the advantage is 62.5ns).

---

Now, let's sum up the advantage

* digitalRead: 3.6us
* PIND: 0
* interrupt: 62.5ns

The solution is pretty obvious to me, and it is... Don't care! Even in the worst case scenario you are four order of magnitude faster than your phenomenon. You are giving one player a 4us advantage in a 250ms game (0.0016% of advantage). I'm pretty sure that the mechanical differences between the two buttons (maybe one is a bit stiffer, or has a slightly higher size, or has a slightly lower contact) affect the reading much more than this.

In the end, with this kind of setup you will reasonably be able to have an accuracy that is at most some tens of milliseconds. With other measurement setups (maybe optically based) you can go as low as 1ms. Adding 4us of advantage to one player will not influence the result.

Try to focus on the rest of the program, and for this problem use whichever solution you find more understandable.

NOTE: This is based on the assumption that a proper program is developed, with tie checks and no delays and so on. The program as you wrote in the question is not ok from this point of view (as it is now it will stay in the loop forever; if you change `Sx_State` to `digitalRead` it will become roughly fair - something like 4us of advantage to player one and 3.8us of advantage to player two)
> 3 votes

# Answer
I have to concur with frarugi87 here. The few microseconds taken by `digitalRead()` are completely inconsequential for your application. But let me add that, even if your players were super-humans capable of sub-millisecond reaction times, you are not giving an advantage to any of them if you alternatively check button 1, then button 2, then button 1, and so on. The reason is that, in the small time window between reading button 1 and reading button 2, you give an advantage to player 2: he will win if both buttons are pressed simultaneously. In the following time window (between checking button 2 and button 1) the same advantage goes to player 1.

The net result is that the game has a tiny amount of randomness: if both buttons are pressed simultaneously, the result is seemingly random. But again, the chances of this happening are so tiny that it makes no sense to worry about it.

Here is how I would determine the winner. I think this code makes clear that we are alternatively checking button 1, then button 2, then button 1...

```
int find_winner()
{
    for (;;) {
        if (digitalRead(S1_Pin) == HIGH)
            return 1;
        if (digitalRead(S2_Pin) == HIGH)
            return 2;
    }
}

```
> 1 votes

---
Tags: loop
---


# Question
Title: Trying to power multiple servos at once using a Arduino Mega
Recently I have been trying to do a project for my end of year project, it involved making a humanoid arm.

I am still a newbie at these things, I usually have my friend do the wiring, but since he is away for the moment can anyone help me with it?

I am currently using 6X MG996R Servos for each finger and 1 for the wrist. I am also using a Arduino Mega with a Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface.

I have already searched through the web for the best way to power it but I only found people trying to power it with a 5v adaptor, my problem is I'm trying to make the hand mobile so I need to use a battery. I have tried 2x UltraFire 18650 3000mAh 3.7V rechargeable battery in series (still doesn't work only 1 servo moved), also using a 9v battery (Only moved 2 servos).

So i have been wondering if I could utilise the Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface..

# Answer
> 0 votes
Here is a spec-sheet for the MG996R servos. Notice at the top of the 2d page, they require a supply of 4.8 - 7.2 volts, and can draw .5 - .9 Amps running and 2.5 Amps when stalled.

You'll need a supply of 6 volts (+/-) that can handle that current, times however many servos you need to operate simultaneously. The 3.7 volt batteries don't even meet the minimum voltage for the servos (unless you have two of them in series, but then they're slightly over the maximum).

You need to figure out your power budget first, then how your are going to meet it. You might be able to use a lighter supply than the worst case (6 stalled motors) would require or even than 6 motors at full operating torque (0.9 Amp each), if you monitor the current on each motor and shut down the or sequence the one(s) with the highest draw. You might even try monitoring just the battery-pack voltage, which won't tell you which motor(s) are stressing, but will let you know that you're unable to supply the total requirement for that present move.

If it were me, I'd use battery voltage sensing first (easier, simpler) to see if I have a problem that I can't solve by sequencing the motors. I might find I don't need to measure each motor's current.

Update:

> So its either i use 3.7 bat or 9v. Or.can you suggest any other power source?

A single 3.7v battery won't work well) for a motor that needs 4.8v minimum. Two of them in series will be slightly over the max voltage spec (7.4v vs. 7.2v). Will that slight overage damage or overheat the motor? Will be OK for intermittent use? Maybe, if you're careful to shut down a stalled motor quickly. The alternative is to build a voltage regulator that will drop the 7.4 to around 6v, but the regulator must also be able to meet your power budget, too.

A 9v supply is definitely too high and will need to regulated to within the motors' spec. (I assume you're not considering the four or five cm high ones with snap-on connectors, usually used in smoke-detectors? They have very little capability to deliver current and will be totally unsuitable for your application.)

My first try would be to experiment with 1 motor at 7.4v with a typical (for your project) mechanical forces on it, and see if it overheats and how soon, with how much load. You'd be taking a bit of a risk with that motor but the potential advantage is you might save yourself having to build a high-current voltage regulator.

Update2:

> NiMH AA cells are 1.2V

Good call. Just know that Nickle-based batteries have the twin disadvantages of long charge cycles (or degradation of capacity with faster charging) and higher self-discharge rate of about 1%/day. Their advantage to you is that it's easier to make a battery pack whose voltage falls within the motor spec. If this is a one-time project, this may well be more important to you than their disadvantages.

---
Tags: servo, adafruit, battery, electronics, current
---


# Question
Title: Does Arduino C++ support dynamic arrays of objects
My C++ is seriously out-of-date, and I'm working on a project that will be juggling multiple timed actions at the same time, with a menu system to manage the interface and control those timed actions (A multi-channel power outlet controller.)

To do the control I'm planning to have an array of objects that get serviced every time through the event loop. I'm currently using a static C array of objects, but I'd like to use a dynamic C++ array where I can add and remove objects as needed.

I know that some features of the C++ standard library are not supported on Arduino. I think C++ calls smart arrays vectors, and believe vectors are part of the standard library, which isn't supported/fully supported on Arduino. Is there some sort of dynamic array class available?

# Answer
Even if it would be possible to use dynamic arrays, I would not recommend it, especially not on an Arduino Uno/Mega with only 2 or 8 KB memory.

Instead, create a static data element (e.g. array) that has a (reasonable) maximum number of created elements. This also has the benefit that the constructor will not be called after initialization, thus no variance in execution time (construction of objects can take time).

To manage multiple items within this data element, you can:

* Using a ring buffer, this is the normal way to store items on one side, and process them from the other (so-called FIFO, first in first out).
* Using a stack (for LIFO, last in last out).
* For arrays, keep one variable that holds the number of elements currently filled.
> 4 votes

---
Tags: programming, array, vector, object-oriented
---


# Question
Title: Display Wireless Temperature Sensor data to Web page by using Serial communication
I am reading from wireless temperature sensor with help of gateway receiver connected to Arduino UNO, using this code

I need to display the data of the wireless sensor on the webpage. Any suggestion on which help to start working using serial com or should I have to use Ethernet port for this?

# Answer
> -1 votes
So you want to read serial port data from a webpage, I am not a web developer, but I suggest you to read the following links.
You can use a local server to read the data (NodeJs, php) :

---
Tags: serial, web-server, wireless
---


# Question
Title: How do I use a 5v/120v relay that is not mounted on a board
I bought an arduino kit, and it came with, amongst other things, a 5v relay to control 120-220v.

The relay is only that, there is only the 5 pin relay, and it's not on a board on which one can screw in the leads

I was wondering how I can use it.. i.e. how do I mount it somehow (especially since the leads are metric and most perf board is standard (or vice-versa)).

I don't mind soldering the 5v control leads from the arduino, but I'm not so sure about soldering or connecting 110v straight on the relay. i'm worried about long term longevity.

I have soldered longer leads just to be able to fit it on a board for tests, but those are tiny, and aren't safe for higher voltage/current.

Any suggestions? Thanks, Seb.

# Answer
What I did with a similar looking 'module' (An AC/DC converter), was to use a protoboard/perfboard. Some holes fitted in the existing holes, others I drilled with a small drill.

On the back you can solder the wires you need, so for the 110V wires you might use thicker wires than for the controls.

Than if you want to make it fancy, you add some terminal blocks to connect the external wires too. Terminal blocks looks like this:
> 0 votes

---
Tags: relay
---


# Question
Title: Clear existing array when getting new serial command
I'm starting to build my first Arduino project but I'm running into some problems with serial communication.

I get serial data from the console and store it in a char array called "data".

Then, when I send a new console message to the Arduino, I want it to clear the existing "data" array and store only the new data in that array.

I don't understand exactly what's wrong with my code: I believe those nested Serial.available() statements don't work but I have no ideas on how to fix the code.

Data is correctly stored by the Arduino but it concatenates the newer string to the old one.

```
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {

  if (Serial.available() > 0){
    if (dataComplete == true){
    Serial.println("There is data already, clearing...");
    char data[30];
    dataComplete = false;
  }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

```

Thanks in advance!

# Answer
> 18 votes
To clear an array you would do:

```
for( int i = 0; i < sizeof(data);  ++i )
   data[i] = (char)0;

```

or

```
memset(data, 0, sizeof(data));

```

, which does the same thing using a library function.

However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:

```
data[0] = (char)0;

```

will do it.

# Answer
> 2 votes
First of all, this is an *excellent* example why whitespace matters. Your code is really hard to read as it is, as skimming over it, it seems as the second if statement is outside of the first one.

Fixed code:

```
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available() > 0){
    if (dataComplete == true){
      Serial.println("There is data already, clearing...");
      char data[30];
      dataComplete = false;
    }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

```

Also, it seems as it prints "Command received:" every iteration, regardless of if there's new data or not (although, this could be the intended feature).

Like mentioned, you don't *clear* the variable, you just create a new one. You'll need to clear *and* reset `count` to fix this issue. However, just resetting count won't work if the second command is shorter than the one before.

Also, why do you complicate the code with the `dataComplete` variable? I simplified the code below:

```
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available()){
    Serial.println("New command, collecting...");
    count = 0;
    data[] = "";
    while (Serial.available()){
      char character = Serial.read();
      data[count] = character;
      count++;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

```

# Answer
> 1 votes
This probably doesn't do what you intend it to do:

```
Serial.println("There is data already, clearing...");
char data[30];

```

Your output says you are clearing the `data` array, but you're doing no such thing. In fact, you are declaring a *new* local variable called `data`, which is independent of the global `data` you already have declared at the top of your program. Local variables only exist within the scope in which they are declared (inside their nearest enclosing `{ }`).

Instead, your `count` variable keeps track of how much data you have received. So perhaps do the following:

```
Serial.println("There is data already, clearing...");
count = 0;

```

This is not the only thing that might cause your program to operate unexpectedly, but it should at least fix the problem stated in your question.

# Answer
> 0 votes
To speak to the point of the question, and what the author was attempting to accomplish.

None of this code actually works as a whole. The data would get over written and just keep looping continuously... anyway here is a working example of the original code.

This method I prefer to clear an array:

```
    for( int i = 0; i < sizeof(data);  ++i )
    data[i] = (char)0;

```

Here is working example. ( Make sure to select Carriage Return on the serial monitor )

```
    char message[32];
    uint8_t incomingByte = 0;
    uint8_t BufferPos = 0;
    int clearbyte = 0;

    void setup() {
    Serial.begin(9600);
    Serial.println("\n String conversion testing");

    }

    void loop() {

       if (BufferPos >= 32) {
              Serial.print("Buffer Full\n");
              BufferPos = 00;
              incomingByte = 0;

       }

      if (Serial.available()) {
             incomingByte = Serial.read();
             message[BufferPos++]= incomingByte;

         switch(incomingByte)
      {
           case '\n':
           case ' ':
             break;
           case '\r':
              Serial.println(message);

          for( int i = 0; i < sizeof(message);  ++i )
         message[i] = (char)0;
              BufferPos= 0;
              incomingByte= 0;

      }
      }
    }

```

# Answer
> 0 votes
I was read all comments on this question, but all codes was share so verbosing. After that, i create a code with simple functions and less of line. in this case, i think this code will working fine

if you set baudrate under 115200, must be add delay() for saving message to char array

```
void loop() {
    char data[255];
    uint8_t k = 0;
    while (Serial.available()) {
        data[k] = Serial.read();
         k++;
    }
    for (int i = 0; i < k; i++) {
        Serial.print(data[i]);
        data [i] = '\0';
    }
    //delay(50);
}

```

---
Tags: serial
---


# Question
Title: Motor controller for 24v motor, Arduino Uno
I need a motor controller for a 24v motor and I want to control it using än Arduino Uno. Suggestions?

The motor needs to run both directions and is going to draw about 5A

# Answer
> 2 votes
try this Arduino Compatible Mega Motor Shield. Specs:

1. Low-cost robust H-bridge ''shield'' for Arduino
2. Provides the ability to control up to 30A of current at up to 28V
3. Supply voltage: 5V to 28V (24V max battery rating)
4. Continuous output current: 13A Have, a look:

# Answer
> 0 votes
I'm doing my own driver dude using Tip122 but you can use TIP120 too TIPand other components

# Answer
> 0 votes
better invest few dollars and use a motor controller that will keep you from shooting threw the MOSFET transistors, enable soft start of motor and let you select between fast decay and slow decay when PWM is in OFF state. ( see details for DRV8814 by TI)

---
Tags: arduino-uno, arduino-motor-shield
---


# Question
Title: Dynamically modifying the call stack using pointers
In a C++ Arduino library, can we modify the call stack from inside a function by intentionally decrementing a pointer to a stack variable so that it's out of range? Like this:

```
void FooBar()
{
  char a;
  char *ptr = &a;
  ptr -= 4;
  // Can we edit the call stack with ptr now?
}

```

Can we use this to, for example, change what function is "calling" `FooBar()` by replacing the function pointer of the calling function on the call stack to another function? Or can we change the values of function variables in the calling function in mischievous fashion?

# Answer
> 1 votes
I am answering in the context of the AVR calling conventions, as they are the only ones I know well enough to be able to answer here.

> Can we use this to, for example, change what function is "calling" `FooBar()` by replacing the function pointer of the calling function on the call stack to another function?

That will probably be impossible in C++. Let's say you have the following call chain: `main()``f()``FooBar()`. In the body of `FooBar()`, the stack will look like this (oldest stuff at top):

```
return address from f() to main()
registers saved by the f() prologue
return address from FooBar() to f()
registers saved by the FooBar() prologue

```

Getting the stack pointer is easy. No need to declare a dummy variable, just:

```
char *stack_pointer = (char *) SP;

```

Now, to change the required return address, you need to skip over the registers saved by the `FooBar()` prologue. And this is the big problem: you do not know how many registers were saved there. Function prologues are written by the compiler, and whatever they save depends on how many registers are needed within the function, which in turn depends on the complexity of that function. Even minor changes to the function can modify the number of registers its prologue saves.

The only solution to this problem I can imagine is to forego the compiler-generated prologue and write `FooBar()` in assembly. If you wish to do it within a C++ file, you can attach the "naked" attribute to the function and write its body using inline assembly.

> Or can we change the values of function variables in the calling function in mischievous fashion?

No need to tamper with the stack for this. The compiler strives to store as many local variable as possible in CPU registers rather than the stack. The caller's local variables are most likely still in those registers and you can modify them at will (in assembly). That's why you have this register-saving prologue and register-restoring epilogue in the first place. Indeed, if you make the function "naked" and don't do the saving/restoring yourself, you will very likely end up corrupting the caller's locals.

---
Tags: c++, memory, pointer
---


# Question
Title: How to combine strings and text together?
I'm trying to combine two strings (strings/int) together with text in below code:

```
int foo = String((char*)payload).indexOf(' ');
int message1;
int message2;

message1 = String((char*)payload).substring(0, foo).toInt();
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

client.publish(msg, String(message1 + " " + message2).c_str(), true);
// published value: 1 0

```

Instead of publishing "1 0" its publishing some weird values, what am i missing?

# Answer
I wouldn't use the String class, but instead use the C functions to concatenate strings (like strcat, strncat).

You can use the itoa function to convert an integer to a string, see:

> https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c

Or use the sprintf function.

These are all standard C functions which gives you complete control of the buffer sizes to use. Handy because the Arduino Uno has just 2 KB.
> 2 votes

---
Tags: arduino-uno, programming, string
---


# Question
Title: How to find the MAC address using NodeMCU when connecting to WiFi?
I am new to using NodeMCU and IOT. I am testing the NodeMCU (ESP8266) so that I can connect with pubnub server. Have taken code from github but there is error saying

```
'mac was not declared in this scope'

```

and some other error too.

Can anyone tell whats the problem?

This code is from pubnub github page - https://github.com/pubnub/arduino

Code:-

```
#include <Ethernet.h>

#include <PubNub.h>

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* If you use some other HW, you need to do some other
       initialization of it here... */
    Ethernet.begin();

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(publisher key, subscriber key);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */
    Ethernet.maintain();

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

error :-
  sketch_jan17a:28:47: error: 'pubchannel' was not declared in this scope

     PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");

                                               ^

sketch_jan17a:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

Multiple libraries were found for "Ethernet.h"
 Used: C:\Users\sultan\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta2\libraries\Ethernet
 Not used: C:\Program Files (x86)\Arduino\libraries\Ethernet
exit status 1
'mac' was not declared in this scope

```

# Answer
> 2 votes
I don't believe you have an Wiznet Ethernet module connected to your NodeMcu. Ethernet library is for the Wiznet chips for wired LAN. You want to use the WiFi of the NodeMcu. For that the esp8266 core has the ESP8266WiFi library. It has the same API as other WiFi libraries based on Arduino WiFi library. So you can modify the WiFi examples of the Arduino pubnub library. Only change `#include <WiFi101.h>` to `#include <ESP8266WiFi.h>`. (And remove `#include <SPI.h>`.)

---
Tags: esp8266, wifi, nodemcu
---


# Question
Title: ArduinoISP external programmer produces verification error?
I am using an ArduinoISP external programmer to upload a sketch to an Arduino MEGA.

I set the processor type to MEGA 2560, and use Ctrl-Shft-U to upload using a programmer. My programmer is set to ArduinoISP under tools\>Programmer.

So far, I haven't been able to get the sketch to upload without a verification error. Worse, the programmer made it far enough in the upload process to overwrite the bootloader. Trying to re-upload the boot loader ("Burn Bootloader") also fails. The verbose error output is below with the exact error at the bottom.

A previous post suggested that code with a lot of `0xFF` statements in it would fail. I have none.

Following a suggestion in the comments, I unsoldered the power over ISP programmer jumper (SJVCC) on my ArduinoISP. I powered the Arduino using the power jack; however, I got the same verification error.

I have also tried updating the software the the latest version (1.6.12), but that also does not seem to work. I may try to downgrade the software, but this all seems a little futile. Other forums don't seem to have a good answer for similar verification problems.

Is this a known problem? What can I do to fix it? What is particularly frustrating is that the problem occurs intermittently, ocassional after a computer reboot, it will upload successfully one time.

```
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : arduinoisp
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : USBtiny
     Description     :
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be     performed
     To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file     "C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex"
avrdude: writing flash (9334 bytes):

Writing | ################################################## | 100% 10.71s

avrdude: 9334 bytes of flash written
avrdude: verifying flash memory against     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Te    nsion_wo_Averaging.ino.hex:
avrdude: load data flash data from input file     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex:
avrdude: input file                     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex contains 9334 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 7.34s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0600
         0xdd != 0x4a
avrdude: verification error; content mismatch

avrdude done.  Thank you.

```

# Answer
Sounds like you have a bad Arduino ISP board.

I've had limited success restoring bootloaders on some Arduinos with my bad USBtinyISP programmer by connecting a 9V power supply to the Arduino in addition to the 5V that the ICSP cable provides. Worth a try.

Note that back when my USBtinyISP was working properly I didn't need to attach 9V, the 5V from the ICSP cable was all the power needed.
> 1 votes

---
Tags: arduino-mega, uploading, isp, programmer, arduinoisp
---


# Question
Title: Issue with analog readings on Arduino atMega with YL-69 moisture sensors
I've connected four YL-69 sensors to my arduino at-mega2560 on analogs pins 0-3. This is combined with four DHT11 sensors that are in digital pins.

The DHT work fine, and I can work one YL-69 moisture sensor that gives correct readings. But when I connected the others, the readings are just 100% for all. I'm sure I must have made a mistake in my code somewhere, just can't spot it.

I've posted the sketch I use below, and the results from serial monitor. (BTW i added a short delay of 10ms between each reading thinking that may be the issue, but it had no effect).

**Serial Monitor:**

**Sketch:**

```
#include "DHT.h"
#include <SPI.h>        // Include SPI library (needed for the SD card)
#include <SD.h>         // Include SD library

File dataFile;

#define DHTPIN0 10     // what pin we're connected to
#define DHTPIN1 11     // what pin we're connected to
#define DHTPIN2 12     // what pin we're connected to
#define DHTPIN3 13     // what pin we're connected to

// Uncomment whatever type you're using!

#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// How to connect sensors
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht0(DHTPIN0, DHTTYPE);
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
DHT dht3(DHTPIN3, DHTTYPE);

int output_value ;
int output_value1 ;
int output_value2 ;
int output_value3 ;
int output_value4 ;

unsigned long time;

void setup() {
 Serial.begin(9600);
 while (!Serial)
    ; // wait for serial port to connect. Needed for native USB port only
  Serial.print("Initializing SD card...");
  if (!SD.begin()) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");
 Serial.println("DHTxx test!");
 dht0.begin();
 dht1.begin();
 dht2.begin();
 dht3.begin();
 delay(2000);
}

uint16_t line = 1;

void loop() {
 // Reading temperature or humidity takes about 250 milliseconds!
 // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
 float h0 = dht0.readHumidity();
 float h1 = dht1.readHumidity();
 float h2 = dht2.readHumidity();
 float h3 = dht3.readHumidity();
 float t0 = dht0.readTemperature();
 float t1 = dht1.readTemperature();
 float t2 = dht2.readTemperature();
 float t3 = dht3.readTemperature();

 dataFile = SD.open("DHT11Log.csv", FILE_WRITE);
 //  if any result below is NaN (not a number) then something went wrong!
 if (dataFile) {
   output_value= analogRead(A0);
   delay(10);
   output_value1= analogRead(A1);
   delay(10);
   output_value2= analogRead(A2);
   delay(10);
   output_value3= analogRead(A3);
   delay(10);
   output_value4= analogRead(A4);
   output_value = map(output_value,1024,0,0,100);
   output_value1 = map(output_value,1024,0,0,100);
   output_value2 = map(output_value,1024,0,0,100);
   output_value3 = map(output_value,1024,0,0,100);
   output_value4 = map(output_value,1024,0,0,100);
   Serial.print("Moisture : ");
   Serial.print(output_value);
   Serial.println("%");
   Serial.print(output_value1);
   Serial.println("%");
   Serial.print(output_value2);
   Serial.println("%");
   Serial.print(output_value3);
   Serial.println("%");
   Serial.print(output_value4);
   Serial.println("%");
   Serial.print("Humidity  : sensor 0, ");
   Serial.println(h0);
   Serial.print("  sensor 1, ");
   Serial.println(h1);
   Serial.print("  sensor 2, ");
   Serial.println(h2);
   Serial.print("  sensor 3, ");
   Serial.println(h3);
   Serial.println(" %\t");
   Serial.print("temperature  : sensor 0, ");
   Serial.println(t0);
   Serial.print("  sensor 1, ");
   Serial.println(t1);
   Serial.print("  sensor 2, ");
   Serial.println(t2);
   Serial.print("  sensor 3, ");
   Serial.println(t3);
   Serial.println(" %\t");
   dataFile.print(line++);
   dataFile.print(":    Temperature = ");
   dataFile.print(",");
   dataFile.print(t0);
   dataFile.print(",");
   dataFile.print(t1);
   dataFile.print(",");
   dataFile.print(t2);
   dataFile.print(",");
   dataFile.print(t3);
   dataFile.print(",");
   dataFile.print("°C,    Humidity = ");
   dataFile.print(",");
   dataFile.print(h0);
   dataFile.print(",");
   dataFile.print(h1);
   dataFile.print(",");
   dataFile.print(h2);
   dataFile.print(",");
   dataFile.print(h3);
   dataFile.print(",");
   dataFile.println("%");
   dataFile.print(",");
   dataFile.print("Moisture : ");
   dataFile.print(",");
   dataFile.print(output_value);
   dataFile.print(",");
   dataFile.print(output_value1);
   dataFile.print(",");
   dataFile.print(output_value2);
   dataFile.print(",");
   dataFile.print(output_value3);
   dataFile.print(",");
   dataFile.print(output_value4);
   dataFile.close();

  }
  // if the file didn't open, print an error:
  else
    Serial.println("error opening DHT11Log.txt");
    delay(10000);
}

```

# Answer
I think that the problem is here:

```
output_value = map(output_value,1024,0,0,100);
output_value1 = map(output_value,1024,0,0,100);
output_value2 = map(output_value,1024,0,0,100);
output_value3 = map(output_value,1024,0,0,100);
output_value4 = map(output_value,1024,0,0,100);

```

replace them with:

```
output_value = map(output_value,1024,0,0,100);
output_value1 = map(output_value1,1024,0,0,100);
output_value2 = map(output_value2,1024,0,0,100);
output_value3 = map(output_value3,1024,0,0,100);
output_value4 = map(output_value4,1024,0,0,100);

```
> 2 votes

---
Tags: arduino-mega, sensors, c++
---


# Question
Title: 'inet_addr_to_ipaddr' was not declared in this scope
I am using ESP32 Ping from this page: https://github.com/pbecchi/ESP32\_ping

It works fine on ESP32, no compiler error.

Because something wrong on my PC, I did fresh install Windows 10 and Arduino IDE 1.8.8.

After fresh install, ESP32 Ping doesn't work anymore.

Arduino IDE Compiler error in Ping.cpp:

```
//Ping.cpp

#include <Arduino.h>

#include <math.h>
#include <float.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>

#include "ping.h"

#include "lwip/inet_chksum.h"
#include "lwip/ip.h"
#include "lwip/ip4.h"
#include "lwip/err.h"
#include "lwip/icmp.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"

static uint16_t ping_seq_num;
static uint8_t stopped = 0;

/*
* Statistics
*/
static uint32_t transmitted = 0;
static uint32_t received = 0;
static float min_time = 0;
static float max_time = 0;
static float mean_time = 0;
static float last_mean_time = 0;
static float var_time = 0;

#define PING_ID 0xAFAF

#define PING_DEFAULT_COUNT    10
#define PING_DEFAULT_INTERVAL  1
#define PING_DEFAULT_SIZE     32
#define PING_DEFAULT_TIMEOUT   1

/*
* Helper functions
*
*/
static void ping_prepare_echo(struct icmp_echo_hdr *iecho, uint16_t len) {
    size_t i;
    size_t data_len = len - sizeof(struct icmp_echo_hdr);

    ICMPH_TYPE_SET(iecho, ICMP_ECHO);
    ICMPH_CODE_SET(iecho, 0);
    iecho->chksum = 0;
    iecho->id = PING_ID;
    iecho->seqno = htons(++ping_seq_num);

    /* fill the additional data buffer with some data */
    for (i = 0; i < data_len; i++) {
        ((char*)iecho)[sizeof(struct icmp_echo_hdr) + i] = (char)i;
    }

    iecho->chksum = inet_chksum(iecho, len);
}

static err_t ping_send(int s, ip4_addr_t *addr, int size) {
    struct icmp_echo_hdr *iecho;
    struct sockaddr_in to;
    size_t ping_size = sizeof(struct icmp_echo_hdr) + size;
    int err;

    iecho = (struct icmp_echo_hdr *)mem_malloc((mem_size_t)ping_size);
    if (!iecho) {
        return ERR_MEM;
    }

    ping_prepare_echo(iecho, (uint16_t)ping_size);

    to.sin_len = sizeof(to);
    to.sin_family = AF_INET;
    inet_addr_from_ipaddr(&to.sin_addr, addr);

    if ((err = sendto(s, iecho, ping_size, 0, (struct sockaddr*)&to, sizeof(to)))) {
        transmitted++;
    }
    free(iecho)
    return (err ? ERR_OK : ERR_VAL);
}

static void ping_recv(int s) {
    char buf[64];
    int fromlen, len;
    struct sockaddr_in from;
    struct ip_hdr *iphdr;
    struct icmp_echo_hdr *iecho = NULL;
    char ipa[16];
    struct timeval begin;
    struct timeval end;
    uint64_t micros_begin;
    uint64_t micros_end;
    float elapsed;

    // Register begin time
    gettimeofday(&begin, NULL);

    // Send
    while ((len = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&from, (socklen_t*)&fromlen)) > 0) {
        if (len >= (int)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr))) {
            // Register end time
            gettimeofday(&end, NULL);

            /// Get from IP address
            ip4_addr_t fromaddr;
            inet_addr_to_ipaddr(&fromaddr, &from.sin_addr);

            strcpy(ipa, inet_ntoa(fromaddr));

            // Get echo
            iphdr = (struct ip_hdr *)buf;
            iecho = (struct icmp_echo_hdr *)(buf + (IPH_HL(iphdr) * 4));

            // Print ....
            if ((iecho->id == PING_ID) && (iecho->seqno == htons(ping_seq_num))) {
                received++;

                // Get elapsed time in milliseconds
                micros_begin = begin.tv_sec * 1000000;
                micros_begin += begin.tv_usec;

                micros_end = end.tv_sec * 1000000;
                micros_end += end.tv_usec;

                elapsed = (float)(micros_end - micros_begin) / (float)1000.0;

                // Update statistics
                // Mean and variance are computed in an incremental way
                if (elapsed < min_time) {
                    min_time = elapsed;
                }

                if (elapsed > max_time) {
                    max_time = elapsed;
                }

                last_mean_time = mean_time;
                mean_time = (((received - 1) * mean_time) + elapsed) / received;

                if (received > 1) {
                    var_time = var_time + ((elapsed - last_mean_time) * (elapsed - mean_time));
                }

                // Print ...
                log_d("%d bytes from %s: icmp_seq=%d time=%.3f ms\r\n", len, ipa,
                    ntohs(iecho->seqno), elapsed
                );

                return;
            }
            else {
                // TODO
            }
        }
    }

    if (len < 0) {
        log_d("Request timeout for icmp_seq %d\r\n", ping_seq_num);
    }
}
/*
static void stop_action(int i) {
    signal(i, SIG_DFL);
    stopped = 1;
}
+/
/*
* Operation functions
*
*/
void ping(const char *name, int count, int interval, int size, int timeout) {
    // Resolve name
    hostent * target = gethostbyname(name);
    IPAddress adr = *target->h_addr_list[0];
    if (target->h_length == 0) {
        // TODO: error not found target?????
        return;
    }
    ping_start(adr, count, interval, size, timeout);
}
bool ping_start(struct ping_option *ping_o) {

    return ping_start(ping_o->ip,ping_o->count,0,0,0);

}
bool ping_start(IPAddress adr, int count=0, int interval=0, int size=0, int timeout=0) {
//  driver_error_t *error;
    struct sockaddr_in address;
    ip4_addr_t ping_target;
    int s;
    // Get default values if argument are not provided
    if (count == 0) {
        count = PING_DEFAULT_COUNT;
    }

    if (interval == 0) {
        interval = PING_DEFAULT_INTERVAL;
    }

    if (size == 0) {
        size = PING_DEFAULT_SIZE;
    }

    if (timeout == 0) {
        timeout = PING_DEFAULT_TIMEOUT;
    }

    // Create socket
    if ((s = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP)) < 0) {
        // TODO: error
        return false;
    }

    address.sin_addr.s_addr = adr;
    ping_target.addr = address.sin_addr.s_addr;

    // Setup socket
    struct timeval tout;

    // Timeout
    tout.tv_sec = timeout;
    tout.tv_usec = 0;

    if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(tout)) < 0) {
        closesocket(s);
        // TODO: error
        return false;
    }

    stopped = 0;
    transmitted = 0;
    received = 0;
    min_time = 1.E+9;// FLT_MAX;
    max_time = 0.0;
    mean_time = 0.0;
    var_time = 0.0;

    // Register signal for stop ping
    //signal(SIGINT, stop_action);

    // Begin ping ...
    char ipa[16];

    strcpy(ipa, inet_ntoa(ping_target));
    log_i("PING %s: %d data bytes\r\n",  ipa, size);

    ping_seq_num = 0;

    while ((ping_seq_num < count) && (!stopped)) {
        if (ping_send(s, &ping_target, size) == ERR_OK) {
            ping_recv(s);
        }
        delay( interval*1000L);
    }

    closesocket(s);

    log_i("%d packets transmitted, %d packets received, %.1f%% packet loss\r\n",
        transmitted,
        received,
        ((((float)transmitted - (float)received) / (float)transmitted) * 100.0)
    );

    if (received) {
        ping_resp pingresp;
        log_i("round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\r\n", min_time, mean_time, max_time, sqrt(var_time / received));
        pingresp.total_count = 10;
        pingresp.timeout_count = 10;
        pingresp.total_bytes = 1;
        pingresp.total_time = mean_time;
        pingresp.ping_err = 0;
        return true;
    //  ping_o->sent_function(ping_o, (uint8*)&pingresp);
    }
    return false;
}

bool ping_regist_recv(struct ping_option *ping_opt, ping_recv_function ping_recv)
{
    if (ping_opt == NULL)
        return false;

    ping_opt->recv_function = ping_recv;
    return true;
}

bool ping_regist_sent(struct ping_option *ping_opt, ping_sent_function ping_sent)
{
    if (ping_opt == NULL)
        return false;

    ping_opt->sent_function = ping_sent;
    return true;
}

```

Arduino IDE 1.8.8. compiler stop in this line:

```
inet_addr_from_ipaddr(&to.sin_addr, addr);

```

The error message: **'inet\_addr\_to\_ipaddr' was not declared in this scope**

According to this post, `inet_addr` need `lwip` library.

So... the conclusion: cause of this issue is broken `lwip` library.

But when ESP32 Ping working fine previously, I didn't install any separate `lwip` library. Maybe ESP32 Ping use `lwip` library from Arduino library - `#include <Arduino.h>`

But why after fresh install, ESP32 Ping doesn't work anymore?

Arduino IDE installation automatically included Arduino library. Also, I didn't change anything on Arduino Sketch & Library folder - `C:\Users\Documents\Arduino`. The folder content as the same as before fresh install.

How to fix this?

Please help...

# Answer
Done this steps:

```
1. Uninstall Arduino IDE 1.8.8
2. Delete C:\Users\AppData\Local\
3. Rename C:\Users\Documents\Arduino into C:\Users\Documents\Arduino_OLD
4. Restart the PC
5. Install Arduino IDE 1.8.8
6. Install ESP32 Core version 1.0.0 using Boards Manager

```

Then.... compile my sketch.

And now.... **it WORKS**.... :) :) :)

My previous mistake is not installing ESP32 Core version 1.0.0.

I did it by installing version 1.0.1 - the Boards Manager default version - which didn't work.

It seems some change in ESP32 Core version 1.0.1 broke ESP32 Ping library connection.
> 0 votes

---
Tags: arduino-ide, library
---


# Question
Title: How do I turn on/off led with the same IR button?
I'm trying to make the led switch on/off by the same case(): code. But its not working could anyone help me?

# Answer
> 0 votes
It would be good if you add your sketch if you have one.

In principle, you have to create a boolean variable which keeps the current state of the LED. When you get an IR command, inside the IR button handler invert the state of the boolean. Than change the LED accordingly.

Something like:

Const/Global variable:

```
#define LED_PIN 8

int ledState;

```

In setup:

```
 ledState = FALSE;
 digitalWrite(LED_PIN, ledState);

```

In side loop:

```
case IR_BUTTON_CHANGE_LED:
   ledState = ledState == LOW ? HIGH : LOW; // Invert state
   digitalWrite(LED_PIN, ledState); // Set LED according to state
   break;

```

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


# Question
Title: Error compiling a sketch to class/library conversion
I'm trying to take a sketch and turn it into a class for a library I'm making, but I'm getting compile issues.

This is not a duplicate as suggested. as i explain in the comment and my answer. Thank you all for your help - as I am new to creating libraries - figured I would attempt something correctly for a change :)

Here is the original sketch: Gotten here

```
#include <ros.h>
#include <sensor_msgs/BatteryState.h>

#define K           0.00472199
#define CELLS       6
#define MAX_CELLS   12

double cell_const[MAX_CELLS] =
{
  1.0000,
  2.1915,
  2.6970,
  4.1111,
  4.7333,
  6.6000,
  6.6000,
  7.8293,
  8.4667,
  9.2353,
  11.0000,
  11.0000
};

ros::NodeHandle nh;
sensor_msgs::BatteryState batt_state;
ros::Publisher batteryState("battery_state", &batt_state);

void setup()
{
  // Initialize the ROS node.
  nh.initNode();
  nh.advertise(batteryState);

  // Populate battery parameters.
  batt_state.design_capacity = 2200;      // mAh
  batt_state.power_supply_status = 2;     // discharging
  batt_state.power_supply_health = 0;     // unknown
  batt_state.power_supply_technology = 3; // LiPo
  batt_state.present = 1;                 // battery present

  batt_state.location = "Crawler";        // unit location
  batt_state.serial_number = "ABC_0001";  // unit serial number
  batt_state.cell_voltage = new float[CELLS];

}

void loop()
{
  // Battery status.
  double battVoltage = 0.0;
  double prevVoltage = 0.0;

  // Populate battery state message.
  for (int i = 0; i < CELLS; i++)
  {
     // Read raw voltage from analog pin.
    double cellVoltage = analogRead(i) * K;

    // Scale reading to full voltage.
    cellVoltage *= cell_const[i];
    double tmp = cellVoltage;

    // Isolate current cell voltage.
    cellVoltage -= prevVoltage;
    battVoltage += cellVoltage;
    prevVoltage = tmp;

    // Set current cell voltage to message.
    batt_state.cell_voltage[i] = (float)cellVoltage;

    // Check if battery is attached.
    if (batt_state.cell_voltage[i] >= 2.0)
      batt_state.present = 1;
    else
      batt_state.present = 0;
  }

  // Update battery health.
  batt_state.voltage = (float)battVoltage;

  if (batt_state.voltage > CELLS * 4.2)
    batt_state.power_supply_health = 4; // overvoltage
  else if (batt_state.voltage < CELLS * 3.0)
    batt_state.power_supply_health = 3; // dead
  else
    batt_state.power_supply_health = 1; // good

  // Publish data to ROSSERIAL.
  batteryState.publish( &batt_state );
  nh.spinOnce();
  delay(1000);

}

```

Here is my header file:

```
#ifndef battery_h
#define battery_h

#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#include <ros.h>
#include <sensor_msgs/BatteryState.h>

#define K           0.00472199
#define CELLS       6
#define MAX_CELLS   12
#define CRITICAL    0.30

double cell_const[MAX_CELLS] =
{
  1.0000, 2.1915, 2.6970, 4.1111,
  4.7333, 6.6000, 6.6000, 7.8293,
  8.4667, 9.2353, 11.0000, 11.0000
};

ros::NodeHandle nh;
sensor_msgs::BatteryState batt_state;

ros::Publisher batteryState("/battery/info", &batt_state);

class Battery
{
  private:
   void updateBatteryHealth();
   double battVoltage;
   double prevVoltage;
  public:
    void begin();
    void updateBatteryState();
};

#endif

```

This is my cpp file:

```
#include "battery.h"

void Battery::begin(){

  // Launch ROS node and set parameters.
  nh.initNode();

  // Setup publishers/subscribers.
  nh.advertise(batteryState);

  // Populate battery parameters.
  batt_state.design_capacity          = 2200;  // mAh
  batt_state.power_supply_status      = 2;     // discharging
  batt_state.power_supply_health      = 0;     // unknown
  batt_state.power_supply_technology  = 3;     // LiPo
  batt_state.present                  = 1;     // battery present

  batt_state.location      = "Crawler";        // unit location
  batt_state.serial_number = "ABC_0001";       // unit serial number

  batt_state.cell_voltage = new float[CELLS];  // individual cell health

}

void Battery::updateBatteryState() {
  battVoltage = 0.0;
  prevVoltage = 0.0;
  // Reset Power Supply Health.
  batt_state.power_supply_health = 0;
    // Populate battery state message.
  for (int i = 0; i < CELLS; i++)
  {
    // Read raw voltage from analog pin.
    double cellVoltage = analogRead(i) * K;

    // Scale reading to full voltage.
    cellVoltage *= cell_const[i];
    double tmp = cellVoltage;

    // Isolate current cell voltage.
    cellVoltage -= prevVoltage;
    battVoltage += cellVoltage;
    prevVoltage = tmp;

    // Set current cell voltage to message.
    batt_state.cell_voltage[i] = (float)cellVoltage;

    // Check if battery is attached.
    if (batt_state.cell_voltage[i] >= 2.0)
    {
      if (batt_state.cell_voltage[i] <= 3.2)
        batt_state.power_supply_health = 5; // Unspecified failure.
      batt_state.present = 1;
    }
    else{
      batt_state.present = 0;
    }
  }
};

void Battery::updateBatteryHealth() {
    // Update battery health.
  if (batt_state.present)
  {
    batt_state.voltage = (float)battVoltage;
    float volt = batt_state.voltage;
    float low  = 3.0 * CELLS;
    float high = 4.2 * CELLS;
    batt_state.percentage = constrain((volt - low) / (high - low), 0.0, 1.0);
  }
  else
  {
    batt_state.voltage = 0.0;
    batt_state.percentage = 0.0;
  }

  // Update power supply health if not failed.
  if (batt_state.power_supply_health == 0 && batt_state.present)
  {
    if (batt_state.voltage > CELLS * 4.2)
      batt_state.power_supply_health = 4; // overvoltage
    else if (batt_state.voltage < CELLS * 3.0)
      batt_state.power_supply_health = 3; // dead
    else
      batt_state.power_supply_health = 1; // good
  }
   // Publish data to ROSSERIAL.
  batteryState.publish( &batt_state );
  nh.spinOnce();
};

```

this is the error im getting simply by calling the Battery::begin function in my main class:

```
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `nh'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `batt_state'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `batteryState'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/KBROSRobot/KBROSRobot.cpp.o (symbol from plugin): In function `KBROSRobot::KBROSRobot()':
(.text+0x0): multiple definition of `cell_const'
sketch/rob_test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
/var/folders/m4/lq13_j5j23qc0l2wp8dqmt4h0000gp/T//cczNyzqC.ltrans1.ltrans.o: In function `begin':
/Users/keith.brown/Documents/Arduino/libraries/KBROSRobot/KBROSRobot.cpp:9: undefined reference to `Battery::begin()'
collect2: error: ld returned 1 exit status
exit status 1

```

# Answer
> 1 votes
Don't define your global variables in the header file. Only declare them, using external linkage. Then define them in the implementation file

Header (.h):

```
extern ros::NodeHandle nh;

```

Implementation (.cpp):

```
ros::NodeHandle nh;

```

Try to keep usage of global variables to a minimum. If you don't need them outside of the library, declare them in the implementation file and mark them static.
Or even better: encapsulate them inside of the class.

---

The reason that you are getting these errors is because each implementation file is compiled separately. You have two implementation files that include your header file, so the header file is compiled twice. This results in two global variables with the name `nh`. During the linking stage, the linker tries to combine the compiled version of both `KBROSRobot.cpp` and `rob_test.ino.cpp` (these are called object files, `.o`). The linker has no way of knowing which variable is which, because they are both defined twice, so it throws an error.

Multiple *declarations* are fine, because it just tells the compiler "there is a definition somewhere", and the linker will find that definition eventually. That's why the declaration with external linkage solves your problem.
Multiple *definitions* are not allowed (in most cases).

# Answer
> 0 votes
I also found that all other classes in the library have to be in the `utility` folder or the wont compile. Answering my comment above. Thank you @tttapa for your help.

Now I just have to intelligently program the robot, which is unfortunately subjective... ;)

---
Tags: arduino-mega, library, battery, robotics, error
---


# Question
Title: RFID RC522 reads the previous tag serial with different tag
I hope someone can help me.

I'm using a Mega with RC522, and this happens:

I use a tag, it reads the right serial (e.g. AA:BB:CC:DD). Then I use a second tag and sometimes it gives me the correct value (e.g. 00:11:22:33), but often it gives me the previous tag serial (AA:BB:CC:DD). After a few attempts, it finally gives me the right one (00:11:22:33).

I really can't find what's wrong and i'd be grateful if someone could shed some light.

Here's the code:

```
if (RC522.PICC_IsNewCardPresent())  {
           RC522.PICC_ReadCardSerial();
          String strID = "";
        for (byte i = 0; i < 4; i++) {
          strID +=
            (RC522.uid.uidByte[i] < 0x10 ? "0" : "") +
            String(RC522.uid.uidByte[i], HEX) +
            (i != 3 ? ":" : "");
        }
        String seriale = strID;

        if (seriale != "0"){

          for(h=0; h<=numerogiocatori -1;h++){

            if (seriale == seriali[h]) {
              lcd.clear();
              lcd.print("Saldo Gioc. ") ;
              lcd.print(h + 1) ;
              Serial.print("tag ID: ");
              Serial.print(seriale);
              Serial.print(" .    ");
              lcd.setCursor(0, 1);
              lcd.print(totaledenaro[h]) ;
              delay(1500);
              lcd.clear();
              lcd.print("Importo");
              lcd.setCursor(0, 1);
            }
          }
        }}}

```

Thanks to anyone willing to help!

# Answer
One rule for writing safety code is :

*The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked inside each function.*

You forgot to check if the tag has been readed i.e the return value of PICC\_ReadCardSerial. If it fails the value is not updated, that is the reason why the value is still the old one.

Using the following code (from the ReadNUID example of the MFRC522 library https://github.com/miguelbalboa/rfid/blob/master/examples/ReadNUID/ReadNUID.ino)

```
// Init array that will store new NUID
byte nuidPICC[4];

void loop() {

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    Serial.println(F("NUID has NOT been readed."));

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
  }
}

```

the result is

> A new card has been detected.
> The NUID tag is:
> 97 C6 6E 09
> **NUID has NOT been readed.
Card read previously.**
> A new card has been detected.
> The NUID tag is:
> CC 16 5D 83
> A new card has been detected.
> The NUID tag is:
> 97 C6 6E 09
> **NUID has NOT been readed.
Card read previously.**
> A new card has been detected.
> The NUID tag is:
> CC 16 5D 83

Sometimes when the second tag is used the tag is not read and the uid remains the same.
> 2 votes

---
Tags: arduino-mega, arduino-ide, rfid
---