# Question
Title: Second item in array not gets assigned from struct object, ArduinoJson
I got the below code generated this amazing tool.

```
const size_t capacity = JSON_ARRAY_SIZE(2) + JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(4) + 2*JSON_OBJECT_SIZE(7);
DynamicJsonDocument doc(capacity);

JsonObject config = doc.createNestedObject("config");
config["type"] = "power_plug";
config["chip_id"] = "12345";
config["mac_address"] = "abc";

JsonArray config_attachments = config.createNestedArray("attachments");

JsonObject config_attachments_0 = config_attachments.createNestedObject();
config_attachments_0["name"] = "socket";
config_attachments_0["input_type"] = "toggle_switch";
config_attachments_0["on_state"] = "on";
config_attachments_0["off_state"] = "off";
config_attachments_0["pin_type"] = "output";
config_attachments_0["pin"] = 15;
config_attachments_0["current_state"] = "on";

JsonObject config_attachments_1 = config_attachments.createNestedObject();
config_attachments_1["name"] = "socket_1";
config_attachments_1["input_type"] = "toggle_switch";
config_attachments_1["on_state"] = "on";
config_attachments_1["off_state"] = "off";
config_attachments_1["pin_type"] = "output";
config_attachments_1["pin"] = 12;
config_attachments_1["current_state"] = "off";

serializeJson(doc, Serial);

```

This prints out the desired json properly. but when amend single line from the second array item, to take the `on_state` from my struct object `d_config`,

```
Serial.println(">>" + d_configs.peripherals[1].current_state);
Serial.println(">>" + d_configs.peripherals[1].on_state);
config_attachments_1["on_state"] = d_configs.peripherals[1].on_state;

```

the parsing gets quiet unexpected, and some of the keys from serialised string json gets missing. For above case, This gets printed in serial monitor;

```
>>off
>>on
{"config":{"type":"power_plug","chip_id":"12345","mac_address":"abc","attachments":[{"name":"socket","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":15,"current_state":"on"},{"name":"socket_1","input_type":"toggle_switch","on_state":"on","off_state":"off","pin_type":"output","pin":12}]}}

```

**NOTE** in the second item of `attachments`, the key `current_state` is entirely missing. When I assign all values from this struct object, the serialised json misses many more keys... and the behaviour is quite unexpected. here is how I have defined my structs;

```
typedef struct Peripheral{
    String name;
    String input_type;
    String on_state;
    String off_state;
    String pin_type;
    String current_state;
    int pin;
};

typedef struct {
  String type;
  String chip_id;
  String mac_address;
  Peripheral peripherals[10];
} DeviceConfig;

```

I am not sure if its an issue during serialization or something else... :/ Any help would be highly appreciated :) .

**UPDATE** When I added three items inside attachments, then the serialized json string is missing some keys for only the last item. Seems like only the last item on the list is having problem getting serialized.

# Answer
ArduinoJson stores strings differently depending on their types:

* for `const char*`, it saves a pointer;
* for other types (`char*`, `String`...) it copies the string.

Because ArduinoJson stores the copy of the string in the `JsonDocument`, you must increase the capacity of the `JsonDocument`.

In your case, you pass `Peripheral::current_state`, which is a `String`, so ArduinoJson makes a copy in the `JsonDocument`. Increasing `capacity` by a few bytes should solve the problem.

Note that the ArduinoJson Assistant also computes the number of bytes required to store all the strings. Look for "Additional bytes for strings duplication" on the right panel.
> 2 votes

---
Tags: arduino-ide, string, json, struct
---


title: 74HC595 not working properly

text:
# Question
Title: 74HC595 not working properly
I've used the following code to light 8 yellow leds sequentially but it only runs as it's supposed to be on Proteus. However in my breadboard the 8 leds keeps blinking all together, the resistors used are 220 ohms. Also when i'm trying to change the value of the variable "leds" to be for example 0x0F, it doesn't light, I've read in the Arduino shiftout tutorial that 0.1F capacitor on the latch pin will even the flickers so now I'm really confused.

```
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

byte leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(100);
  }
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);

}

```

# Answer
> 1 votes
SOLVED! i've tried many solutions to make it work but it just didn't and here are the solutions i tried a) to use 0.1µf or 10µf between VCC and ground pin of the 74hc595 . b) to set the clockPin and dataPin zero before sending data . c) replacing the resistors from 220 ohm to 470 .

however, i connected pin13 of the 74HC595 to an arduino pin and drive it to zero so the 8 output are ready to go then digitalWrite(out\_enable\_Pin, HIGH) ,send data as shown in the following code then digitalWrite(out\_enable\_Pin, LOW) again .

```
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int out_enable_Pin=13;
int resetPin=5;
char leds = 0;

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(out_enable_Pin, OUTPUT);
  pinMode(resetPin, OUTPUT);
}

void loop()
{
  digitalWrite(out_enable_Pin, LOW);
  digitalWrite(resetPin, HIGH);

  for (int i = 0; i <255; i++)
  {
    leds=i;
    updateShiftRegister();
    delay(1000);
  }
}

void updateShiftRegister()
{
    digitalWrite(out_enable_Pin, HIGH);
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, MSBFIRST, leds);
   digitalWrite(out_enable_Pin, LOW);
   digitalWrite(latchPin, HIGH);
}

```

---
Tags: c++, led, shift-register
---


# Question
Title: Can an arduino Uno control led, sound and smoke?
I'm pretty new to this and I've not seen anyone answer this question yet - so I figured I would ask.

I have a vape mod that is set up to expel smoke with a trigger. I want to merge this trigger to the arduino so that the arduino can then have 2 single buttons. One would trigger a specific led set (8 LEDS), the vape mod, and sound through 2 external speakers for about 5 seconds. I'd like the second button would trigger another specific LED set (8), vape mod and sound (through two external speakers) for 3 seconds. I have acquired a 555 chip, which I've researched can control the timing of the triggers yet can't find anything about how much power is needed for these types of things.

If I'm able to have the LEDs, Sound, and Vape mod separately how do I combine these to control them all with a single push of a trigger?

However, again, the main thing I'm wanting to know is if an Arduino Uno can trigger all of these devices at a single time or if it would drain too much power?

Any help is truly appreciated! Also, if there is anything that you think I need to take into consideration that I haven't already - feel free to make suggestions. Like I said, I'm just starting out and I know I should start with simpler projects but I'm just really interested in whether or not this can be done.

All the best,

# Answer
The arduino has more than enough **processing** power to manage those tasks mentioned. You probably won't need that 555. Playing music is possible as long as the arduino doesn't have to process the file itself. But switching on an external player is no problem (with what so ever circuitry).

The **electrical** power is another story, you probably will need extra power-supplies, but nobody can say without knowing your exact setup.
> 1 votes

---
Tags: arduino-uno, programming, communication, timers, rgb-led
---


# Question
Title: Uploading Firmware to Atmega1284p using ESP8266 with AVRISP as programmer
I am trying to flash a new Firmware to my Ender 3 Pro.

I am using the ESP8266 as an ISP via AVRISP over Wifi.

I have a 10mF capacitor between the ground and reset of the ESP8266

I followed this thread: ESP8266 as ISP program for ATMega16

When uploading I get the following output on console:

```
C:\Users\Chry>"I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/bin/avrdude" -C "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"
-v -V -p atmega1284p -c arduino -P net:192.168.178.59:328 -b 115200 -D -U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "I:\3dPrints\Firmware Pack Source Folder\Windows Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : net:192.168.178.59:328
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_drain(): read error: Falscher Parameter.

avrdude: ser_drain(): read error: Falscher Parameter.

avrdude: ser_drain(): read error: Falscher Parameter.

         AVR Part                      : ATmega1284P
         Chip Erase delay              : 55000 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   128    0 no       4096    8      0  9000  9000 0xff 0xff
           flash         65    10   256    0 yes    131072  256    512  4500  4500 0xff 0xff
           lock           0     0     0    0 no          1    0      0  9000  9000 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
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
         Hardware Version: 4744608
         Firmware Version: 0.2
         Topcard         : STK502
         Vtarget         : 1.8 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

avrdude done.  Thank you.

```

I can't seem to get it to work. Does anyone have any ideas?

I tried programming it directly: I use the standard Arduino ISP sketch on my ESP8266 and try to upload that way. Directly connected the ESP8266 to my computer. I get sync-problems now: avrdude: stk500\_getsync() attempt 9 of 10: not in sync: resp=0x61 The Board in the arduino IDE is set to Sanguino 1284p and the programmer is set to Arduino as ISP.

# Answer
I assume that you have to wrap the directory in the option `-U flash:w:C:\Users\Chry\AppData\Local\Temp\arduino_build_166520/TH3DUF_R2.ino.hex:i` with `"`s. I don't promise that it'll work with that change, but `C:\Users...` will definitely confuse the parser due to the `:`!
> 1 votes

---
Tags: esp8266, avr, avrdude
---


# Question
Title: HLW8032 UART sends random data ( Registers Overflow often)
I designed my own version of smart socket just like the Sonoff with power metering chip HLW8032. And when I read the data in ESP-12F the data doesn't have a fixed format. To troubleshoot the issue, I bought **HLW8032 Breakout Board** and analyzed the data sent by HLW8032, and I found the results are the same as the board I designed.

And that made me think that I may be reading the data from the Serial port the wrong way.

HLW8032 sends 24 Bytes on the serial and the format should be like this:

```
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9C 2A 39 61 00 00 79
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9D C2 9F 61 00 00 78

```

The data that I receive is in this format,

```
F2 5A 2 D3 70 6 BC D4 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FB EC 17 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FD 84 7D 61 0 1 38 F2 5A 2 D3 70 6 AA 59 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 2 D3 70 6 AA 59 0 3D 4F
4 98 B4 4D E1 80 FE FF 1 61 0 1 38 F2 5A 1 61 0 1 38 F2 5A 2 D3
70 6 AA 59 0 3D 4F 4 98 B4 4D E1 80 FE FF F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FE FF 1 61 0 1 38 F2 5A 2 D3 70 6 AA 59 38 F2 5A 2 D3 70 6 AA 59
0 3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 4F 4 98 B4 4D E1 80 10 1B
D4 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0 3D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 13 4E 9E 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 14 E8 3 61 0 1 39 E1 80 16 82 67 61 0 1 39
F2 5A 2 D3 70 6 AA 59 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0

```

We can see that the registers overflows again and again. The code that I use to read the data is:

```
#include <SoftwareSerial.h>
#define BAUD_RATE 4800

SoftwareSerial swSer(13, 12);

void setup()
{
  Serial.begin(BAUD_RATE);
  swSer.begin(BAUD_RATE);
}

byte data[24];
void loop()
{
  if (swSer.available() > 0) {
    int a = swSer.readBytes(data, 24);
    yield();
  }

  // Display
  for (int i=0;i<24;i++)
  {
    Serial.print(data[i],HEX);
    Serial.print(" ");
  }
  Serial.println();
}

```

Schematic:

I feel that there is no issue in my hardware design, and the issue seems to be in the sketch.

---

What can be the possible problem with my setup?

---

How do I make the output of HLW8032 Stable with no overflow of registers?

---

Is there any library someone can recommend me to read the data from HLW8032 on **SoftwareSerial**?

**Note:** After some troubleshooting I found that delay() cause the problem to be more worse. And won't receive a stream of Bytes whose first byte , second nibble is **F** like F2, F4, as from the datasheet , first four bits are 1s by default.

# Answer
> 2 votes
First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.

Then I used an HLW8032 Library (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.

So in short my issue resolved using two things:

1. I swaped UART0 to GPIO15 and GPIO13 using `Serial.swap()`
2. Used a library for the HLW8032

Thanks to @Juraj who provided the useful link about Serial Swap in ESP8266.

> Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

```
#include "HLW8032.h"

HLW8032 HL;

void setup()
{
    HL.begin(Serial,4);
    Serial.begin(4800);
    Serial.swap();
}

unsigned int V;
void loop()
{
    HL.SerialReadLoop();

    if(HL.SerialRead == 1)
    {
    V = HL.GetVol();
    }
}

```

With this I can't print and see my debug prints on GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.

---
Tags: serial, esp8266, softwareserial, uart
---


# Question
Title: Stream video from camera to mobile and send control signal back from mobile to Arduino via WiFi
I want to make an Ardunio based project in which I want to stream live video from camera (which is connected to Arduino borad ) to my Android app via WiFi and send back actions/control signals from my android app to Arduino to controller servo motor which are connected to Arduino board. Right now I only have Arduino mega with me. What else components are going to be required?

# Answer
> 1 votes
You need good MPU with enough buffer size and nand size for such an intense process

Search esp modules

Thanks.

---
Tags: arduino-mega, wifi, camera
---


# Question
Title: How to add indicator lights to button sketch
I would like to add leds to each button switch in the first code, The first code sends midi messages to a DAW I would like it to also turn on a led as an indicator light. The switch needs to turn the light on if off and off if on. The second code is an example that does this, it works well with one button. I would like to have the 3 buttons on pins 0, 1, 2 and the leds on pins 3, 4, and 5.

```
#include <Bounce.h>

const int channel = 1;
Bounce button0 = Bounce(0, 5);
Bounce button1 = Bounce(1, 5);
Bounce button2 = Bounce(2, 5);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
}
void loop() {
  button0.update();
  button1.update();
  button2.update();

  if (button0.fallingEdge()) {
    usbMIDI.sendNoteOn(60, 99, channel);  // 60 = C4
  }
  if (button1.fallingEdge()) {
    usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4
  }
  if (button2.fallingEdge()) {
    usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4
  }

  if (button0.risingEdge()) {
    usbMIDI.sendNoteOff(60, 0, channel);// 60 = C4
  }
  if (button1.risingEdge()) {
    usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4
  }
  if (button2.risingEdge()) {
    usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4
  }
  while (usbMIDI.read()) {
  }
}

```

Second sketch:

```
/*********************
Simple toggle switch
Created by: P.Agiakatsikas
*********************/

int button = 0;
int led = 13;
int status = false;

void setup(){
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
}

void loop(){
//a) if the button is not pressed the false status is reversed by !status and the LED turns on
//b) if the button is pressed the true status is reveresed by !status and the LED turns off

if (digitalRead(button) == true) {
  status = !status;
  digitalWrite(led, status);
} while(digitalRead(button) == true);
  delay(50); // keeps a small delay
}

```

# Answer
I'd suggest creating an array of MIDI button structs. For each entry you'd have a button object, an LED pin, and a BOOL to track the state of thate button.

Write a function that loops through the array of structs, checks the state of each one, and does the work to play/stop the notes and toggle the LED states based on the state of each button.
> 1 votes

---
Tags: programming, led, button, debounce
---


# Question
Title: Are there any standard ways of reporting a runtime error?
I'm new to Arduino but I'm an experienced programmer. I'm wondering if there are any common functions for reporting errors in Arduino programs? For example, in JavaScript we have the alert() function, or on Unix you can write a message to standard error and exit.

Ideally, if the serial port is available then an error message would be printed there, or if there is an LED then maybe we should blink it. This would need to be configurable based on what the programmer wants to do with available hardware.

Looking the example sketches, error reporting seems pretty horrible. I'm wondering if any libraries handle this better?

# Answer
> 1 votes
As pointed out by Majenko in a comment, you can hardly define a standard facility for error reporting when you don't know what kind of I/O hardware will be available on any particular project. Printing to the serial port is the most common method though, as it tends to always be available during the development phase, while the Arduino is tethered to the development computer. I personally tend to just do something like

```
Serial.println(F("Error: the warp field coil is busted."));

```

and be consistent with the error prefix, so that a program receiving this can tell it's an error by matching the line against `/^Error: /`.

While it is OK for user code, reporting errors through `Serial` is certainly *not* a good practice for library code. Alas, it is done way too often in Arduino libraries. I've seen at least one library (don't remember which one) that allows the user to provide a reference to a `Print` object (defaulting to `Serial`) to be used for this purpose. This is way better, as it allows the user to handle the error messages any way she chooses. It is also very easy to turn off the error reporting altogether by implementing a do-nothing `Print`, which would be a `/dev/null` of sorts.

Note that the avr-libc allows you to print to `stderr`, as long as you have first implemented `stderr->put`... While this method is the closest you can get to the standards you are used to, it may not be portable to non-AVR Arduinos. And it is worth noting that we tend to avoid the `printf()` family of functions on Arduinos, as they tend to be quite large compared to the `print()` and `println()` methods.

---
Tags: programming, coding-standards
---


title: char buffer to String in Arduino UNO

text:
# Question
Title: char buffer to String in Arduino UNO
```
String getAPIData()
{
  char res_buffer[450];
  int numdata = inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", res_buffer, 450);
  String result = String(res_buffer);
  Serial.println(result);
  Serial.println(numdata);
  return result;
}

```

Output on Serial:

```
15:52:07.208 ->
15:52:07.208 -> 393

```

But, When I print the buffer by loop I got the below output:

```
HTTP/1.1 200 OK
Date: Mon, 16 Sep 2019 06:28:59 GMT
Server: Apache
X-Powered-By: PHP/7.2.20
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Set-Cookie: PHPSESSID=5b21eeac22dcf61f2e4d2efd579d437c; path=/
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: Accept-Encoding,User-Agent
Content-Type: text/html; charset=UTF-8

-1

```

I am not sure why the char buffer is not converting to String in Arduino UNO.

Any known issues ? Please suggest if any correction required.

# Answer
Do not use String. And especially do not use String in the way you are using it.

You can read more about why not here.

Instead stick to just using `char*` buffers.

The correct way of doing what you want is to define the buffer outside your function and then pass that buffer to the function to be populated:

```
int getAPIData(char *buf, int maxlen) {
  return inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", buf, maxlen);
}

```

Then you call it with:

```
char *my_buffer[450];
getAPIData(my_buffer, 450);
Serial.println(my_buffer);

```
> 2 votes

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


title: How do I extract code from an arduino?

text:
# Question
Title: How do I extract code from an arduino?
I updated and uploaded some code on another computer that got wiped and didn't send the new code to my current computer, the updated code is still on the board but I don't have access to it. How do I get it back?

# Answer
> 21 votes
The short answer: You don't.

With enough know-how, you could probably extract the executable binary from the Arduino, but the source code is not installed on the device. You would need to run a decompiler on the binary. (Or read the machine code directly.) The output of a decompiler is usually pretty ugly however, and will look quite different from the original source-code. It won't have meaningful variable names, class names, or function names, and the code structure will likely be a little different than the original source code.

## EDIT:

As mckenzm pointed out in his answer, you could download the binary image from your Arduino, and then copy it onto another Arduino, but all that would let you do is to make an exact copy of the program. You wouldn't be able to modify it at all.

# Answer
> 12 votes
You never can get the actual code back ... by reading the flash you might be able to get the executable/runtime code, but this doesn't look at all similar as your code, although it's functionally the same.

For example, all function names, all variable names will be just numbers (or non recognizable names), and all C statements are converted in machine language instructions, probably so many, you will need much knowledge to find out which instructions belong to which (original) C statements.

# Answer
> 9 votes
1. You read the contents of flash and save it to a file. It can then be re-flashed if your need is not to edit, but duplicate.

* This reads all flash, including the bootloader, and also PROGMEM data.
2. Use avr-objdump (or similar) to disassemble the instructions.

* Again, PROGMEM data is going to be interpreted as opcodes, and may not be valid opcodes.
    * You may want to dump the fuses as well, for redirected vectors and such.
3. Use pattern analysis to recognise source patterns as compiled. Then iteratively compile and compare fragments.

This is harder than is looks, whilst most Arduino code is very simple, the libraries can be be wild and woolly. At least the hex file is human readable, but little endian.

It might be easier to "walk through" the assembly and perform a translation of the perceived behaviour. OK for 10 instructions, but harder for 16K of them.

You will also need the Atmel/Microchip \*def.inc files for the MPU component enumerations so that you know your DDRB from you DDRC a good disasembler should know.

You can do this well enough for Blink, and recognise stack pointer initialization.

It is much easier without a bootloader, as booting should jump to main and main can start at 0 other than after the vectors.

Of course lock bits will ruin your day, and it may just be better for character to code it again.

---
Tags: arduino-uno, programming, servo, c
---


# Question
Title: What do these pins mean? Where should I plug them in?
I am trying to collect data from the arduino into a SD card for the first time, so I bought the adapter at my local electronics/arduino shop. However, I could not find an explanation as to what each pin does, and the other adapters that I have seen online have different pins, so I am not sure what to do with the pins (except for the obvious ones, GND and VCC)

The order of pins is as follows: CD, DO, GND, SCK, VCC, DI, CS.

Could you help me figure out what they mean and where to plug them into my arduino?

# Answer
> 9 votes
This is called the SPI interface (See Serial Peripheral Interface, Wikipedia. The pin names typically used for SPI are:

* GND : Power Ground
* VCC : Power input
* CS : Chipselect
* SCK/SCLK (SD-Clock): SPI Clock
* MOSI (SD-DI, DI) : SPI Master out Slave in
* MISO (SD-DO, DO) : SPI Master in Slave out
* CD: Card Detect (see comment of rollinger below (thanks).

On an Arduino Uno the SPI pins are:

* CS – digital 10; this can be in principle any pin
* SCK – digital 13
* MOSI – digital 11
* MISO – digital 12

# Answer
> 4 votes
* CS = Chip select
* DI = Data In (MOSI)
* VCC
* SCK = Serial Clock
* GND
* DO = Data Out (MISO)
* CD (not sure what it stands for, but this pin isn't used when connecting to an Arduino. I think it's used for faster transfers.)

Note that SD card run at 3.3Volt, not 5V. Also the input pins of the SD can't handle 5Volt signals. So you need to convert the 5V signals coming out of the UNO to 3.3V before connecting to the SD card.

# Answer
> 3 votes
CD could be one of two things:

a) a simple mechanical switch on the socket, usually used for Card Detect. Measure from the pin to Gnd and see if contact is open/closed when a card is plugged in.

b) the fifth IO pin to a uSD card. See the chart on the middle of this data sheet

https://www.molex.com/pdm\_docs/sd/472192021\_sd.pdf

You will see there are 4 data lines for parallel operation (Dat0, Dat1, Dat2, and CD/Dat3), and the Clock and Command (CMD) pin. Arduino uses serial operation over the SPI bus tho, so in this case CD is likely card detect from what appears to be a mechanical lever switch at the bottom of the socket.

This drawing shows how the pins are used http://www.dotmana.com/weblog/wp-content/uploads/izQKT.png

# Answer
> 2 votes
Your question's been well answered, but I just wanna point out, when you get the library code that lets you access the SD card, there will probably be instructions on what pins to wire up where. That's nearly always the case. Particularly since this one uses the SPI pins.

There's also loads of instruction websites that would take you through it. The cheap Chinese stuff is nearly always copies of designs from the West, as seen on popular websites. So the instructions usually apply. Arduino is bloody great! Good luck in your adventure.

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


# Question
Title: How do I use PlatformIO to flash ESP-12F (ESP8266MOD)
In PlatformIO while creating a project , in the board selection there is no ESP-12F in the boards. While there is ESP-12E. I can flash ESP-12F while choosing ESP-12E from the boards without any flashing issue. But there are some runtime issues, the one that I noticed is the LED doesn't blink when flashed from PlatformIO , but works fine, when flashed using Arduino IDE using the same code. So there may be some difference in the configurations.

> C:\Users\USER\\.platformio\platforms\espressif8266\boards

In this directory I found the esp-12e board which is a JSON format.

```
{
  "build": {
    "core": "esp8266",
    "extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP12",
    "f_cpu": "80000000L",
    "f_flash": "40000000L",
    "flash_mode": "dio",
    "ldscript": "eagle.flash.4m1m.ld",
    "mcu": "esp8266",
    "variant": "nodemcu"
  },
  "connectivity": [
    "wifi"
  ],
  "frameworks": [
    "arduino",
    "simba",
    "esp8266-rtos-sdk",
    "esp8266-nonos-sdk"
  ],
  "name": "Espressif ESP8266 ESP-12E",
  "upload": {
    "maximum_ram_size": 81920,
    "maximum_size": 4194304,
    "require_upload_port": true,
    "resetmethod": "nodemcu",
    "speed": 115200
  },
  "url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
  "vendor": "Espressif"
}

```

How do I add ESP-12F to the PlatformIO boards and flashing without any issue.

# Answer
At the PlatformIO community I asked the same question, and pfeerick suggested to add a build flag.

> It’s most likely the onboard LED is on GPIO2, not GPIO1 so try adding
>
> **build\_flags = -D LED\_BUILTIN=2** to your **platformio.ini** … hopefully that kicks in before the **pins\_arduino.h** defintion.

But It didn't did the trick. And the compiler throws a bunch of warnings. What I did to make it work is to ignore **LED\_BUILTIN** constant and use 2 instead.

```
#include <Arduino.h>
void setup() {
 pinMode(2, OUTPUT);
}

void loop()
{
  digitalWrite(2,LOW);
  delay(200);
  digitalWrite(2,HIGH);
  delay(200);
}

```
> 0 votes

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


# Question
Title: SD card example freezes at line SD.begin() what should I do?
I have a 16GB SD card which is formated with FAT32. I'm trying to run the example codes presented for SD in Arduino. The SD card is inserted in the data logging shield and the CS pin in this shield is connected to pin 10. I first tried the Cardinfo example and this is the result:

The SD card is not empty, there exist a few files in it but this example was unable to show this files. I then tried the example ReadWrite and the code freezes on line SD.begin(10). I have no Idea where this problem is coming from.

# Answer
I had the same problem when I used a big SD card, maybe because some cards have a more modern format.

If you have smaller / older cards, try them and see if those work; than you rule out it is not a circuit/connection problem.
> 0 votes

# Answer
I found another SD with 16GB capacity, and fortunately it worked. So the problem was because of the SD but I don't know what was the exact problem. I post the photo of this SD cards.
> 1 votes

---
Tags: arduino-uno, shields, sd-card
---


# Question
Title: Impossible to connect ESP32 with Mosquitto on Raspberry using certificates
I installed Mosquitto broker in Raspberry in my local network. I generated certificates in Raspberry as follows:

```
sudo openssl genrsa -out ca.key 2048
sudo openssl req -new -x509 -days 3600 -key ca.key -out ca.crt
sudo openssl genrsa -out server.key 2048
sudo openssl req -new -out server.csr -key server.key
sudo openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3600

```

I modified the Mosqutto configuration file (.conf) as follows:

```
allow_anonymous false
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key
tls_version tlsv1.2

```

I restarted Mosquitto everything ok

I downloaded the ca.crt file from Raspberry to my PC with Filezilla from my PC I use MQTT.fx to connect I set the certificate. **WORKS WELL**

The problem: with ESP32 I can't connect when I set the certificate with `espClient.setCACert(ca_cert);` MQTT connecting ...

> \[E\] \[ssl\_client.cpp: 33\] handle\_error (): X509 - Certificate verification failed, e.g. CRL, CA or signature check failed

Someone can help me, I can't understand if something is missing in the code or there is some error in generating the certificates

Please help many thanks Michael

this is my code:

```
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ESPmDNS.h>

/* change it with your ssid-password */
const char* ssid = "XXXXXX";
const char* password = "XXXXXXX";
/* this is the MDNS name of PC where you installed MQTT Server */
const char* serverHostname = "home";

const char* ca_cert = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDmDCCAoCgAwIBAgIJAKV4GE+4y/G4MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV\n" \
"BAYTAlRWMRAwDgYDVQQIDAdUcmV2aXNvMRUwEwYDVQQHDAxDYXN0ZWxmcmFuY28x\n" \
"DDAKBgNVBAoMA1BTUzEMMAoGA1UECwwDUFNTMQ0wCwYDVQQDDARob21lMB4XDTE5\n" \
"MDkwODE3NDIzOFoXDTI5MDcxNzE3NDIzOFowYTELMAkGA1UEBhMCVFYxEDAOBgNV\n" \
"BAgMB1RyZXZpc28xFTATBgNVBAcMDENhc3RlbGZyYW5jbzEMMAoGA1UECgwDUFNT\n" \
"MQwwCgYDVQQLDANQU1MxDTALBgNVBAMMBGhvbWUwggEiMA0GCSqGSIb3DQEBAQUA\n" \
"A4IBDwAwggEKAoIBAQC2rPN7VQXtzLCl1LufJkzLK9xedrbW72K2vBZ34VNOl+tG\n" \
"ffNx2QQLQC0Jh5GzB79dZweqAjCRBbIEpx0IGvHWrHDUQMJrvg4BcmDr0eqNCup/\n" \
"tBItlEcCdvmWFfm3IBezOVBDFiQWmC4jvAC/G3DPlftHiPI1k3cDewKNJEJykxeD\n" \
"8H/4KTAz+wJXyGZiviZYv8OYOTRMa3nEhg1vaQTMgCwEVBavg5fsEQkZLArBNJQM\n" \
"Gmw0qDdJEMDGOGWPogxRAKrxvNnXr4mIebzPj9/UTrJnfzVOPEHZ9Uz5BU/psGCL\n" \
"cnMkBeNEa/JyLR14Hu8e+xa/pOCpJ9Dqhi/BTji5AgMBAAGjUzBRMB0GA1UdDgQW\n" \
"BBRIz+15SpOBqo0O+vOtgYvPj4LqWDAfBgNVHSMEGDAWgBRIz+15SpOBqo0O+vOt\n" \
"gYvPj4LqWDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQC08Crs\n" \
"w7LPX+Bd80NwPuxgBmMU4U/pCw8AyzzSgckHmay0K8KuHXhSvZjdl6i0gjG/2xLa\n" \
"ghCtfFGIXPu1Lu226bhTWigmuFLYasG1MivTDz2LeUTFPQrtEO8KdsRUarPZW3Fj\n" \
"nOMyVDdzE4+HxvzvARDc1QbE9SX2ozQcNKQp4oRpunfT2+/OyzYgfMVA7MVKvehX\n" \
"VH49fRF1P1Ajizqr2eHDFImcMQTzepRT7IjfOiQ/8PoqrZGvGenMj5so1I9MtgyK\n" \
"gVUf1ZWPBgxmhVfla6vYBZiTGuZMHSDuF6/yFC1QnoXVq7K+bbIhAE8lsPNuOY7V\n" \
"dKidKIfBJiN378CC\n" \
"-----END CERTIFICATE-----\n";

/* create an instance of WiFiClientSecure */
WiFiClientSecure espClient;
PubSubClient client(espClient);

/*LED GPIO pin*/
const char led = 5;

/* topics */
#define COUNTER_TOPIC    "smarthome/room1/counter"
#define LED_TOPIC     "smarthome/room1/led" /* 1=on, 0=off */

long lastMsg = 0;
char msg[20];
int counter = 0;

void receivedCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.println(topic);

  Serial.print("payload: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  /* we got '1' -> on */
  if ((char)payload[0] == '1') {
    digitalWrite(led, HIGH);
  } else {
    /* we got '0' -> on */
    digitalWrite(led, LOW);
  }

}

void mqttconnect() {
  /* Loop until reconnected */
  while (!client.connected()) {
    Serial.print("MQTT connecting ...");
    /* client ID */
    String clientId = "ESP32Client";
    /* connect now */
    if (client.connect(clientId.c_str(),"XXXXX","XXXXXX")) {
      Serial.println("connected");
      /* subscribe topic */
      client.subscribe(LED_TOPIC);
    } else {
      Serial.print("failed, status code =");
      Serial.print(client.state());
      Serial.println("try again in 5 seconds");
      /* Wait 5 seconds before retrying */
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  /* set led as output to control led on-off */
  pinMode(led, OUTPUT);

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  /*setup MDNS for ESP32 */
  if (!MDNS.begin("esp32")) {
      Serial.println("Error setting up MDNS responder!");
      while(1) {
          delay(1000);
      }
  }
  /* get the IP address of server by MDNS name */
  Serial.println("mDNS responder started");
  IPAddress serverIp = MDNS.queryHost(serverHostname);
  Serial.print("IP address of server: ");
  Serial.println(serverIp.toString());
  /* set SSL/TLS certificate */
  espClient.setCACert(ca_cert);
  /* configure the MQTT server with IPaddress and port */
  client.setServer(serverIp, 26391);
  /* this receivedCallback function will be invoked
  when client received subscribed topic */
  client.setCallback(receivedCallback);

}
void loop() {
  /* if client was disconnected then try to reconnect again */
  if (!client.connected()) {
    mqttconnect();
  }
  /* this function will listen for incomming
  subscribed topic-process-invoke receivedCallback */
  client.loop();
  /* we increase counter every 3 secs
  we count until 3 secs reached to avoid blocking program if using delay()*/
  long now = millis();
  if (now - lastMsg > 3000) {
    lastMsg = now;
    if (counter < 100) {
      counter++;
      snprintf (msg, 20, "%d", counter);
      /* publish the message */
      client.publish(COUNTER_TOPIC, msg);
    }else {
      counter = 0;
    }
  }
}

```

# Answer
> 1 votes
@sempaiscuba and Bruno I solved by regenerating the certificates in this way you have to do this comfortably script in Raspiberry

```
#!/bin/bash

IP="192.168.0.11"
SUBJECT_CA="/C=SE/ST=Italy/L=Roma/O=himinds/OU=CA/CN=$IP"
SUBJECT_SERVER="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Server/CN=$IP"
SUBJECT_CLIENT="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Client/CN=$IP"

function generate_CA () {
   echo "$SUBJECT_CA"
   openssl req -x509 -nodes -sha256 -newkey rsa:2048 -subj "$SUBJECT_CA"  -days 365 -keyout ca.key -out ca.crt
}

function generate_server () {
   echo "$SUBJECT_SERVER"
   openssl req -nodes -sha256 -new -subj "$SUBJECT_SERVER" -keyout server.key -out server.csr
   openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
}

function generate_client () {
   echo "$SUBJECT_CLIENT"
   openssl req -new -nodes -sha256 -subj "$SUBJECT_CLIENT" -out client.csr -keyout client.key
   openssl x509 -req -sha256 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
}

function copy_keys_to_broker () {
   sudo cp ca.crt /etc/mosquitto/certs/
   sudo cp server.crt /etc/mosquitto/certs/
   sudo cp server.key /etc/mosquitto/certs/
}

generate_CA
generate_server
generate_client
copy_keys_to_broker

```

as you see OU changes for each file. Remember to restart Mosquitto

```
sudo systemctl stop mosquitto.service
sudo systemctl start mosquitto.service

```

let me know how it goes bye Michele

---
Tags: esp32, mqtt
---


# Question
Title: #include <ESP8266WiFi.h> Error with WiFiClientSecureBearSSL.h
I am new to the Arduino world and it seems that this simple problem is keeping me at the start line.

* I use the Generic ESP8266 Module as Board
* In my sketch I just write:

```
#include < ESP8266WiFi.h >
void setup(){}
void loop(){}

```

The **ERROR** is :

BearSSLHelpers.h:148:34: error: 'virtual const unsigned char\* BearSSL::HashSHA256::oid()' marked override, but does not override

```
 virtual const unsigned char *oid() override;

                              ^

```

How am I going to solve that? Any help is appreciated.

# Answer
You installed the latest git version of the ESP8266WiFi library into your libraries folder and this version is not compatible with the 2.5.2 version of the esp82666 Arduino core.

The ESP8266WiFi library is part of the esp8266 boards package. It should not be installed separately. Delete the library from your libraries folder.
> 1 votes

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


# Question
Title: Current mouse pointer position with Digispark attiny85
I am trying DigiMouse library for attiny85 Digispark board.

It allows to emulate the mouse quite well. However, I also need to know the current cursor position. Is there a way to get it?

# Answer
> 1 votes
There is no way for a mouse of any kind (especially not one as minimal as DigiMouse.h) to know the current cursor position - USB just doesn't provide that kind of facility.

Instead you need to implement an "absolute" mouse (aka a "tablet"). However DigiMouse doesn't implement such a facility. So you would have to implement your own tablet driver.

A normal mouse sends a "delta" for the position. That is, a difference in position from whatever the current position is. An absolute mouse, or tablet, sends the position on the screen as a proportion of some maximum set of dimensions. Ideally that would be the same dimensions as your screen, but doesn't have to be.

The main differences between DigiMouse and whatever you would implement for a DigiTablet would be the "HID Report Descriptor". This defines what the data that is sent means and how the computer should interpret it.

---
Tags: attiny, digispark, mouse
---


# Question
Title: ESP32 WiFiClient request missing response
I am facing problem with ESP32. I use basic example for WiFiClient and making request to my server. The problem is that the response should be 15000 bytes long, but very often I got only 2750 or less.

```
char buffer[15000];
while (client.available()) {
  char c = client.read();
  buffer[i++] = c;
}
Serial.println(i);

```

# Answer
You are assuming that all 15000 bytes are available all the time.

They won't be.

Instead of "while available read something" you need to "While not enough has been read, then if available read something".

When reading from (assuming) HTTP you first need to read and interpret the headers (the lines before a single blank line). One of these will be the "Content-Length:" header, which will tell you exactly how many bytes are in the body of the response. Then you use that to read the right number of bytes from the body.

So the sequence is:

1. Read line by line for the headers interpreting the ones you need to, until:
2. You receive a single blank line
3. Read the data byte-wise until you have read the number of bytes indicated in the Content-Length header.

If you aren't reading from an HTTP server and you are certain that the data is exactly 15000 bytes in length then you need to skip to point 3 above. Never assume that all the data is there. If there is data then read it, and repeat until you have totalled 15000 bytes.
> 1 votes

---
Tags: wifi, esp32
---


title: DS18b20 Order of sensors on a cable

text:
# Question
Title: DS18b20 Order of sensors on a cable
I have a string of 10x DS18b20 sensors on a single two wire line (parasitic power). Below is a table of the sensors, Where they are located on the wire, and in what order where they discovered.

```
Serial              Order on wire*   Order discovered
286305560100002c    1                7
28a158610100006a    2                3
28ad48610100006b    3                6
2851ae60010000ad    4                4
289b426101000089    5                8
28cd1161010000ce    6                5
2864026101000030    7                1
280c766101000026    8                2

```

I read this document on how the OneWire discovers sensors on the bus. https://www.maximintegrated.com/en/app-notes/index.mvp/id/187

My question: Is there a way to detect the order of the sensors on a wire?

# Answer
There is no way to detect position on the bus because all devices are connected in parallel. This is why a serial or "chain" wire, added to the newer devices, is required.

(To complicate matters, what is the "order of devices" - or even the meaning of "order" in a center-fed bus, or a circular, star, or other branched network? Order is just something we perceive when looking at an end-fed linear network. Electrons don't care. Think of a capacitor (unfortunately, the bus behaves like one but that's another story) with two plates, several centimeters square, and a dozen 1-wire devices connected from plate to plate. Now what is their order? Ow, my brain hurts! Let's go back to linear buses.)

The discovery order is a function of the set of binary device IDs on the bus. There are two ways I know of to come to know the physical ordering, both empirical (i.e., by observation):

1. Connect the set of devices one at a time, to a temporary bus such as a breadboard. With an Arduino, read the their IDs and tag them (human readable). With knowledge of the discovery alogrithm, or by running actual discovery on an Arduino with all devices connected, write down the IDs in the order they are discovered which is invariant for a given set of device IDs. Assemble your wired bus with the devices in this order.
2. (The reverse of 1 and quicker to build, and is what you've already shown in your question: Wire the bus. With a simple Arduino program, repeatedly sample all devices on the bus and report print their indices and temperatures (the indices will be in discovery order). One at a time, warm each device with your hand and notice which device index is affected. Write down the physical position (first, second, ...) and the index. This is the mapping table between position and index. Include it in your control algorithm.
> 1 votes

# Answer
what you can apparently do is use the User Data space set aside for the alarm and add an ID in there. I have not done this yet but am looking at this option as my sensor array has over 40 sensors in a line and ideally I would like the top one to be 0 and the last one in the chain to be 40.
> 1 votes

# Answer
I found this application note.

APPLICATION NOTE 4037
Regain Location Information by Leveraging the 1-Wire® Chain Function—A Simple Signaling and Protocol Method Determines Device Physical Location

https://www.maximintegrated.com/en/app-notes/index.mvp/id/4037
> 0 votes

---
Tags: 1-wire, ds18b20
---


# Question
Title: how to do Arduino to esp8266 communication
I am trying to do Arduino to ESP8266 communication, but I am not able to send data to esp8266. However I can receive data from esp8266.

Here if my Arduino code:

```
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(0, 1); // RX | TX

void setup()
{
  Serial.begin(115200);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Enter 1 to turn led high & 2 to turn led low.");
}
// the loop function runs over and over again forever
void loop() {
  // listen for communication from the ESP8266 and then write it to the serial monitor
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }

  // listen for user input and send it to the ESP8266
  if ( Serial.available() )       {
    ESPserial.write( Serial.read() );
  }

}

```

Here is esp8266 code:

```
void setup()
{
  Serial.begin(9600);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  Serial.println("ESP -- Hello");
  delay(1000);
  // listen for user input and send it to the ESP8266
  if ( Serial.available() )  {

    int ledState = Serial.parseInt();
    if (ledState == 1) {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      Serial.println("ESP Led On\n");
    }
    if (ledState == 2) {
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      Serial.println("ESP Led Off\n");
    }
  }
}

```

Once I upload both sketches, then I can see it terminal " ESP -- Hello " keep printing comming from esp8266 but when I enter 1 or 2, its not sent to esp8266 due to which I never see "ESP led on/off" messages , so correct me guys what mistake I am making.

# Answer
using SoftSerial on the hardware serial isn't working on Arduino properly as sometime data receive and sometime not with garbage added so Using digital pins other 2, & 3 other than hardware serial resolved the issue.
> 0 votes

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


title: Blink Adafruit_NeoPixel

text:
# Question
Title: Blink Adafruit_NeoPixel
I wish to blink all the strip. In the code below it just blink the first LED, how can I fix it?

Code:

```
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define NUM_LEDS 24

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

void loop() {
  strip.setPixelColor(0, 255, 255, 255);
  strip.show();
  delay(1000);
  strip.setPixelColor(0, 0, 0, 0);
  strip.show();
  delay(1000);
}

```

# Answer
The first argument of `setPixelColor` is is the number of the led. In your case 0, so the first led.

Instead use a `for` loop to set all the leds from 0 until (excluding) 24 (which is stored in `NUM_LEDS`).

```
void loop()
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

```

To make the code better (shorter, but more important more maintainable, and reducing code duplication), create a separate function:

```
void loop()
{
  setLeds(255);
  setLeds(0);
}

void setLeds(int intensity)
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, intensity, intensity, intensity);
  }

  strip.show();
  delay(1000);
}

```
> 3 votes

---
Tags: programming, neopixel
---


# Question
Title: Is there way to wirelessly connect a arduino drone‘s camera?
Is there way to wirelessly connect a arduino drone‘s camera and stream to a set device from 10 km away?

# Answer
You could try using the most common solution for streaming low latency drone video, called FPV. You basically connect an AV video output from a camera to a transmitter and use a receiver on the ground to receive the AV video. After this you can connect it to any AV display (or a usb AV decoder if you want to use a computer) and you'll get an almost real time video feed of what is happening on your drone. To get long range you would need to buy a powerful transmitter, good receiver and decent antennas for bout of them. You can find different configurations for different ranges online.
> 1 votes

# Answer
Most (commonly available) RF links' communication distance is more limited than that (10 Km). If your flying locations are within a cell service area, a cell radio aboard the drone will probably give you the most universally available connection. Note that your streaming rate may vary with the location and cell congestion at that particular time, and may sometimes be limited, especially for video.
> 0 votes

---
Tags: wireless, camera, stream
---


# Question
Title: Using an Arduino Nano to program (as ISP) a standalone 328p
I uploaded the ArduinoISP sketch to an Arduino Nano to use it as a programmer for other chips.

It worked successfully to program an ATtiny45, I did the usual wiring between them, and added a 10uF between RST and GND of the Nano. Everything worked.

Now I'd like to program a standalone ATmega328p with the Nano, I did the usual wiring as well (see this tutorial), as well as this 10uF cap.

But it does't work:

> avrdude: Device signature = 0x000000 avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check.

The reason might be because this 328p comes from an Arduino Uno, probably configured to be ext-clocked by a crystal. Whereas I don't have any crystal here and wanted to clock the 328p with the internal clock.

**Question: how can I restore the 328p to factory default / internal clock, if I don't have a crystal?**

Or what other reason can this error be?

Edit: a solution is found here: Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

# Answer
You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)

Or, you could use a high voltage programmer.

Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.

You can then reset the fuses, so it doesn't need a crystal.
> 1 votes

# Answer
That error basically says the bootloader you are trying to burn does not *appear* to be for that device. This could be due to corruption or (more likely in your case) harvesting and reconfiguring the hardware.

If the error does not appear when you try to load the bootloader for the Uno (original device you harvested it from for those harvesting from other configurations), you will know it is the latter.

Either way, you can try to -f it by running avrdude to burn the bootloader via command line (as it says). I've successfully saved stuff with a corrupt bootloader this way although i've never found it worth the hassle to harvest and reconfigure- if you pulled it off the uno, surely you can stitch it to a clock.

If your clock is off by a bit, you may just need to get lucky over several attempts :)
> 0 votes

---
Tags: programming, arduino-nano, atmega328, avr, isp
---


title: Sending serial data in an interrupt

text:
# Question
Title: Sending serial data in an interrupt
An ATMEGA328-P chip is used with a toggle switch attached to pin 8 and a momentary switch attached to pin 9. My objective is to send the following information over serial:

1. The status of pin 8, every second.
2. Count the number of presses of pin 9, sending the value as the counter increments

I understand that to achieve point 2 I will need to utilise interrupts, but I have become stuck in the way I am trying to use them.

I am familiar with the following code's simple style:

1. Within the loop...
2. Poll the status of the input
3. Send status over serial

Code A:

```
const int SWITCH_1 = 8;
const int READ_INTERVAL = 1000;

int val_s1 = 0;

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

    pinMode(SWITCH_1, INPUT);
    digitalWrite(S1, HIGH);
}

void loop() {
    val_s1 = digitalRead(SWITCH_1);
    Serial.print("S1:");
    Serial.print(val_s1);
    Serial.print("\n");

    digitalWrite(LED_BUILTIN, HIGH);
    delay(10);
    digitalWrite(LED_BUILTIN, LOW);
    delay(READ_INTERVAL);
}

```

When introducing the concept of interrupts, I have tried to retain the simplistic style of code A for testing purposes. The next snipped attempts to achieve the following:

1. Attach an interrupt to pin 9 when the voltage rises
2. No need for loop function (?)
3. Within interrupt callback function...
4. Increment the counter
5. Send the counter value over serial

Code B:

```
void c1_rise();

const int COUNTER_1 = 9;
const int READ_INTERVAL = 1000;

volatile int val_c1 = 0;

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

    pinMode(COUNTER_1, INPUT_PULLUP);
    attachInterrupt(COUNTER_1, c1_rise, RISING);
}

void loop() {
}

void c1_rise() {
    val_c1 ++;
    Serial.print("C1:");
    Serial.print(val_c1);
    Serial.print("\n");
}

```

I've tried to learn where I'm going wrong, but I have become stuck and have decided to ask my questions here.

* Observation: I expect to see some data sent over serial when the button is pressed, but actually nothing observable happens.
* Problem 1: This might be because the interrupt isn't being attached at all.
* Problem 2: This might be because I misunderstand the limitations of interrupt callback functions.

While trying to solve problem 1, Arduino documentation implies that to use the `attachInterrupt` function, parameter 1 must be an interrupt, from `digitalPinToInterrupt`, but if I use that function I receive the following error message: **error: ‘digitalPinToInterrupt’ was not declared in this scope**.

From reading up about how interrupts behave, I found problem 2: it seems that even though I have declared the integer as **volatile**, using Serial from within a callback function isn't allowed. This is the limit of my knowledge currently, I hope that someone can help me out.

# Answer
> 8 votes
You cannot use Serial inside an interrupt. Transmitting Serial relies on interrupts being available, and from inside an interrupt they aren't.

All Serial communication must be done from `loop()`.

So you need to just count the switch toggles and check to see if that value has changed in your loop.

```
volatile uint32_t toggles = 0;
uint32_t old_toggles = 0;
uint32_t ts = 0;

void setup() {
    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    attachInterrupt(0, toggle, RISING);
}

void loop() {
    if (toggles != old_toggles) {
        old_toggles = toggles;
        Serial.print("C1: ");
        Serial.println(toggles);
    }

    if (millis() - ts >= 1000) {
        ts = millis();
        Serial.print("S1: ");
        Serial.println(digitalRead(3));
    }
}

void toggle() {
    toggles++;
}

```

# Answer
> 1 votes
**Problem**

In essence, attachInterrupt uses a macro called `ISR` (stands for Interrupt Service Routine) to register a user provided function to handle an external interrupt event.

The issue you are encountering is that `ISR` also wraps the call to your function with special instructions to clear the global interrupt flag of your microcontroller, and set it again after your function returns. This is a good idea, and almost always what you want, because it prevents the possibility of infinitely recursive interrupts.

However, this behaviour will prevent `Serial` from working correctly, since it relies on interrupts being enabled to do its thing.

**Solution**

Although this is the default behaviour, there is nothing stopping you from enabling interrupts again inside your `c1_rise` function, as in:

```
void c1_rise() {
    val_c1 ++;
    interrupts();
    Serial.print("C1:");
    Serial.print(val_c1);
    Serial.print("\n");
}

```

Alternatively, but perhaps more involved, you can use the `ISR` macro directly by including `avr/interrupt.h`, and use `ISR(vect, NO_BLOCK)` to override the default behaviour.

Of course, you should be careful when overriding the default behaviour --- its there for a reason!

For more details about working with interrupts, I recommend reading this documentation.

---
Tags: serial, interrupt, atmega328, serial-data
---


# Question
Title: How can I make my arduino start when a magnet is sensed, and stay running until the application determines it was to shut down
My thought was to use a magnetic reed switch to turn on the arduino. But how do I keep it running if the magnet is moved? The idea is that the application will determine when it is ok to shut off the power to the arduino.

I don't want any power usage when the system is dormant since it could be weeks between magnetic triggers.

Doug

# Answer
> 1 votes
You can connect a power MOSFET in parallel to the reed switch, that is controlled by the Arduino:

simulate this circuit – Schematic created using CircuitLab

The Arduino powers up, when the reed switch is activated. Then you can activate (drive HIGH) the pin connected to the MOSFET, so that the Arduino is still provided with the needed power through the MOSFET, if the reed switch turns off. If the correct time comes to turn the Arduino off, you can release the digital pin (drive LOW or high impedance/input), so that it get's pulled to low. That will deactivate the MOSFET, which cuts the power off the Arduino.

# Answer
> 1 votes
Put your Arduino into deep sleep and attach an interrupt to a pin that is monitoring your reed switch. Once triggered it can run your code before deep sleeping again

# Answer
> 1 votes
The LowPower library will help you to minimize the amount of power used by putting the Arduino to sleep. The Arduino will awaken once the magnetic reed switch triggers it, then you can execute some code before it goes back to sleep again.

There is an example sketch that may work for you:

```
// **** INCLUDES *****
#include "LowPower.h"

// Use pin 2 as wake up pin
const int wakeUpPin = 2;

void wakeUp()
{
    // Just a handler for the pin interrupt.
}

void setup()
{
    // Configure wake up pin as input.
    // This will consumes few uA of current.
    pinMode(wakeUpPin, INPUT);
}

void loop()
{
    // Allow wake up pin to trigger interrupt on low.
    attachInterrupt(0, wakeUp, LOW);

    // Enter power down state with ADC and BOD module disabled.
    // Wake up when wake up pin is low.
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

    // Disable external pin interrupt on wake up pin.
    detachInterrupt(0);

    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

```

---
Tags: arduino-nano
---


# Question
Title: Not getting any output from ECG sensor AD8232
I am trying for the beginning to run a simple Arduino code in order to test the functionality of the ECG sensor. What I am getting on the output are some random values around 600 or around 200. I connected everything the same as in any tutorial about AD8232: GND -\> GND, 3.3V -\> 3.3V, L0+ -\> digital pin 10, L0- -\> digital pin 11, output -\> analog pin A0. I placed the sensor pads on my body like in pictures (forming a triangle), but regardless of putting the electrodes or not, I always get the same floating signal. Here is Arduino code:

```
int ecg;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(10,INPUT);
  pinMode(11,INPUT);

}

void loop() {
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
    Serial.println('!');
  }
    else{
    // send the value of analog input 0:
    Serial.println(analogRead(A0));
    }
    //Wait for a bit to keep serial data from saturating
    delay(1);
}

```

When I run this code I get only "!" on the output, no matter where I put the electrodes on my body. When I comment "if" and "else" parts of the code and print directly only reading from the pin A0, I get those random floating values, like on the image.

I also tried another custom built ECG sensor, but the results are the same. I haven't found the solution anywhere. It is not about the noise, because when I touch the metal box of my PC, I only reduce the values but there is still nothing on the output.

# Answer
> 1 votes
The problem was that I connected GND on the other half of the protoboard and there was no connection. I thought that the whole length of the protoboard is on the same potential for + and -, so GND wasn't connected. After connecting GND pin correctly, all worked perfectly.

---
Tags: arduino-uno, sensors, analogread
---


# Question
Title: exit status 1 error compiling for board arduino/Genuino Uno when tone code is used
I am just trying to use an ultrasonic sensor with a buzzer but the buzzer doesn't respond to my code. I mean it doesn't make any sound. I tested it to check if by sending 5 volts to it, it will make a sound.. and it did... but using this code below... for some reason, it doesn't make any sound....

```
#include <NewPing.h>
#define TRIGGER_PIN 11
#define  ECHO_PIN 12
#define buzzer 13

NewPing sonar1 (TRIGGER_PIN, ECHO_PIN);

long inches1;
int sound = 250;

void setup (){

  Serial.begin (9600);

  pinMode (TRIGGER_PIN, OUTPUT);
  pinMode (ECHO_PIN, INPUT);
  pinMode (buzzer, OUTPUT);

}

void loop () {

  inches1 = sonar1.ping_in();
   if (inches1 <= 5 ){
 //   sound = 250;
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(1000);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(1000);
    Serial.print (inches1);
    Serial.print ('\n');
   }
  delay (200);
}

```

# Answer
If you have a look at the complete error message you will see that there is a collision between the libraries **NewPing** and **Tone**.

```
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\NewPing\NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

```
> 2 votes

---
Tags: arduino-uno, sound
---


title: can't power up arduino from dc jack

text:
# Question
Title: can't power up arduino from dc jack
Yesterday I was working on Arduino based bluetooth car. I was using adafruit motor shield v1. Arduino and shield were on same power supply(11v li-ion cell battery). Every thing was fine. I decided to add some leds to my car. I connected two leds with 5v on shield pins(leds were in series and were multi-colored so 5v was okay). It worked for sometime but later it stopped working. Green led on arduino was on while other were off. I disconnected shield and supplied arduino from dc jack, same result. Then I connected arduino with usb cable then everything was fine. Now it works because I supply arduino from usb and shield is working too either from usb supply or external supply. What could possibly go wrong?

# Answer
It would appear that the output of the power regulator pin has been vaporized.

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator. Here is that data sheet for that part. From that data sheet we see the physical image of the part.

It appears that pin 2 has been vaporized. If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics. Note the red "X" indicating the vaporized pin 2.

The schematic and the data sheet both indicate the regulator's TAB is also an output. If true it is difficult to explain why pin 2 vaporized. Perhaps this particular version of the regulator does not use the TAB as an output. Or perhaps the Arduino R3 PCB and schematic do not agree.

Added later...

There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin. Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1. However, to be sure, you would have to check the voltage before D1 and after U1.
> 1 votes

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


title: how to switch more 230v with arduino?

text:
# Question
Title: how to switch more 230v with arduino?
i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

# Answer
You have to use a relay that can handle minimum 415 volts (and keep some reserve).

Also take the current/amperage into account (possibly use multiple relays).
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Why can't I control speed of the motor? (M1 and E1)
When `myservo_1,myservo_2,myservo_3,myservo_4` is commented, I can't control the speed of my M1 motor. But only when I uncomment `myservo_1` and so on, I can control the motor speed again.

Can someone help me? My codes are listed down below:

```
#include <Servo.h>
Servo myservo_1;
Servo myservo_2;
Servo myservo_3;
Servo myservo_4;

int SensorL = 0;
int SensorR = 0;
int SensorM = 0;

#define E1 10
#define M1 12
#define E2 11
#define M2 13
int pos = 0;
int incomingByte = 0;

void setup()
{
  Serial.begin(9600);
  myservo_1.attach(9);
  myservo_2.attach(8);
  myservo_3.attach(7);
  myservo_4.attach(6);
  pinMode(SensorL, INPUT);
  pinMode(SensorR, INPUT);
  pinMode(SensorM, INPUT);
  pinMode(M1, OUTPUT);
  pinMode(M2, OUTPUT);
//  pinMode(E1, OUTPUT);
//  pinMode(E2, OUTPUT);
}

void loop()
{
  SensorR = digitalRead(2);
  SensorL = digitalRead(3);
  SensorM = digitalRead(5);

  if (SensorL == LOW && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" FORWARD ");
    //delay(1);
  }
  if (SensorL == HIGH && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" LEFT ");
    //delay(1);
  }
  if (SensorL == LOW && SensorR == HIGH && SensorM == HIGH) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" RIGHT ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == HIGH && SensorM == HIGH) //stop
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 0);
    analogWrite(E2, 0);
    Serial.println(" STOP ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == LOW && SensorM == LOW) //move left
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" LEFT ");
    //delay(1);
  }

  if (SensorL == LOW && SensorR == HIGH && SensorM == LOW) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" MoVE Right ");
    //delay(1);
  }

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
    {
      {
        if (incomingByte == 'J')//ARM OPEN
        {
          myservo_1.write(0);
          Serial.println(" ARM OPEN ");
        }
        if (incomingByte == 'L')//ARM CLOSE
        {
          myservo_1.write(180);
          Serial.println(" ARM CLOSE ");
        }
        if (incomingByte == 'I')//ARM UP
        {
          myservo_2.write(0);
          myservo_3.write(180);
          Serial.println(" ARM UP ");
        }
        if (incomingByte == 'K')//ARM DOWN
        {
          myservo_2.write(180);
          myservo_3.write(0);
          Serial.println(" ARM DOWN ");
        }
        if (incomingByte == 'U')//ROTATE LEFT
        {
          myservo_4.write(0);
          Serial.println(" ROTATE LEFT ");
        }
        if (incomingByte == 'O')//ROTATE RIGHT
        {
          myservo_4.write(180);
          Serial.println(" ROATE RIGHT ");
        }
        if (incomingByte == 'M')
        {
          myservo_1.write(90);
          myservo_2.write(90);
          myservo_3.write(90);
          myservo_4.write(90);
          Serial.println(" ALL STOP ");
        }
        if (incomingByte == 'N')//ARM STOP
        {
          myservo_1.write(90);
          Serial.println(" ARM STOP ");
        }
        if (incomingByte == 'B')//UP DOWN STOP
        {
          myservo_2.write(90);
          myservo_3.write(90);
          Serial.println(" UP DOWN STOP ");
        }
        if (incomingByte == 'V')//ROTATION STOP
        {
          myservo_4.write(90);
          Serial.println(" ROTATION STOP ");
        }
        if (incomingByte == 'W')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 200);
          analogWrite(E2, 0);
          Serial.println(" FORWARD ");
        }
        if (incomingByte == 'Z')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" FORWARD ");
          delay(100);
        }
        if (incomingByte == 'S')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" REVERSE ");
        }
        if (incomingByte == 'A')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" LEFT ");
        }
        if (incomingByte == 'D')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" TURNING RIGHT ");
        }
        if (incomingByte == 'X')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 0);
          analogWrite(E2, 0);
          Serial.println(" STOP MANAUAL ");
        }
        if (incomingByte == 'w')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW FORWARD ");
        }
        if (incomingByte == 's')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW REVERSE ");
        }
        if (incomingByte == 'a')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW LEFT ");
        }
        if (incomingByte == 'd')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW RIGHT ");
        }
      }
    }
  }
}

```

# Answer
The Servo library uses `timer 1` to send the signals to the servos. But `timer 1` is also used to run PWM on pins 9 and 10. It can't however do both.

So since Motor E1 uses pin 10, and `timer 1` is already used by the Servo library, PWM, and by extension, `analogWrite` doesn't work.

E2 uses pin 11, which uses `timer 2` for it's PWM, so is therefor no affected.

So move E1 to one of the PWM pins, other than 9 and 10, and thing should start working again.

I however don't know why M1 doesn't work.
> 1 votes

# Answer
* Please correct your code there are several mistakes, such as
    1. the lines at beginning of loop SensorR = digitalRead(2); SensorL = digitalRead(3); SensorM = digitalRead(5); doesn't make any sense.. as you not defined 2,3,5 pin as input. And for taking analog input please change pins 2,3,5 and analog pins..
    2. Motor Pin M1 and M2 are connected 12,13 which are not pwm pins so you can't use to change the speed of your Motor.. Please make this code sensible....
> 0 votes

---
Tags: arduino-uno, programming, sensors, motor, servo
---


# Question
Title: Turn on/off low current device (LED) with Arduino
I am just starting with Arduino and my first project consists in switching a LED light with Arduino.

I know a relay must be use to control AC high voltage device (i.e. 240V), however, as my LED seems to be powered by DC 7V voltage (7V - 0.43A written on the power supply which is integrated within the outlet, so I can only access the low voltage wire), I am wondering how to control such a device.

Do I still need a relay or the Arduino can handle this on its own?

# Answer
Use a power MOSFET transistor. This one from Sparkfun is an example: https://www.sparkfun.com/products/10213

If you use a relay you will probably need transistor and a separate power supply to drive the relay coils anyway, and will also need a **flyback diode** to protect the control circuit of the relay from the "back EMF" of the relay coils.

**DO NOT** try to drive relay coils directly from an Arduino digital pin. It will almost certainly fry the Arduino pin, and might destroy the entire Arduino.

A MOSFET transistor like the one I linked can be controlled directly from an Arduino GPIO line, and can switch DC loads of up to 60V and 30A.
> 0 votes

# Answer
No You can easily achieve this by using a NPN Transistor....

simulate this circuit – Schematic created using CircuitLab

You can use BC548 NPN transistor for this is..

But make sure that ground of both emitter and arduino should be same....
> -1 votes

---
Tags: arduino-nano, electronics, voltage
---


# Question
Title: How to connect IR Transmitter and Receiver Module?
The IR Transmitter and Receiver module has both receiver and transmitter in same board. I tried Arduino IR Remote library example to decode Remote signal using below connection, but its not working.

* IR MODULE: ARDUINO
* Ground -\> Ground
* 5V -\> 5V
* RXD -\> PIN 11
* TXD -\> PIN 10

The board also has 3 pin connector (Gnd, 5v, S). How to connect pins to Arduino to receive/decode and send IR signals? (Can't able to find any tutorial for this type of board)

**Example Code:**

```
#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

```

# Answer
> 2 votes
The device in the question is commonly sold on aliexpress.com and the likes of ebay.com. As you might guess there is little in the way of documentation. Without documentation we can only speculate. As such, I expect that the module handles all the modulation and demodulation. It is likely all you need to do is use the Arduino serial library and connect the TX and RX to the Arduino's RX and TX pins. However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the Arduino software serial library which will "emulate" a serial port an an unused (alternate) set of pins.

(This is an example of a similar well documented device with access to the schematic and source code. Armed with this type of knowledge you can turn this device into what ever you want. In other words, you probably don't even need an Arduino. You can just program this device and be done with your project.)

# Answer
> 1 votes
I think you need to switch RX and TX in your code. Looking at the video that @nick-gammon reffered to. TX on audrion is RX on device.

# Answer
> 0 votes
it use UART protocol so your code is wrong.

Here link with code

# Answer
> -1 votes
For that module you dont need library for easy example for sample for send HIGH and LOW status but. it doesnt work for control IR protocol. for that you need the basic conection Just (data-gnd-Positive) in that example data is for pin = 11

---
Tags: ir
---


# Question
Title: When I verify the sketch I get several errors
I am extremely new to Arduino coding and have downloaded a sketch for the PCA9685 to use with model railroading and turnout control. When I verify the sketch I get several errors ... I don't even know how to resolve and could use some assistance. There are two sketches:

# 1:

```
    /***************************************************
  This sketch can be used to operate any number of turnouts on a
  Model Railroad. Code blocks can be added to accomodate any number
  of servos. This sketch uses only two servos for this demonstration.

  The pushbutton can be replaced with a SPST switch
  commonly used on a control panel. Three pin Bicolor LED can be used
  in place of two seperate LEDs in each circuit.

  10K Ohm pulldown resistor used on switch
  330 Ohm resistor used on LEDs. One per pair of LEDs

  Created 03/02/2019 by Tom Kvichak
  https://tomstrainsandthings.com/
  Additional Arduino Projects can be found at the above web address

 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

int buttonPin0 = 2;   // Can add as many buttons as needed
int ledPin0C = 3;     // C designates Closed position of turnout
int ledPin0T = 4;     // T designates Thrown position of turnout
int buttonState0 = 0;

int buttonPin1 = 5;
int ledPin1C = 6;
int ledPin1T = 7;
int buttonState1 = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutFinal!");
  pwm.begin();
  pwm.setPWMFreq(60);
  delay(30);

  pinMode(ledPin0C, OUTPUT);
  pinMode(ledPin0T, OUTPUT);
  pinMode(buttonPin0, INPUT);
  pinMode(ledPin1C, OUTPUT);
  pinMode(ledPin1T, OUTPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {
  ///////////
  buttonState0 = digitalRead(buttonPin0);
  if (buttonState0 == HIGH) {
    pwm.setPWM(0, 0, 370);
    digitalWrite(ledPin0T, LOW);
    digitalWrite(ledPin0C, HIGH);
  }
  else  {
    pwm.setPWM(0, 0, 285);
    digitalWrite(ledPin0C, LOW);
    digitalWrite(ledPin0T, HIGH);
  }
  //////////
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH) {
    pwm.setPWM(1, 0, 370);
    digitalWrite(ledPin1T, LOW);
    digitalWrite(ledPin1C, HIGH);
  }
  else  {
    pwm.setPWM(1, 0, 285);
    digitalWrite(ledPin1C, LOW);
    digitalWrite(ledPin1T, HIGH);
  }
  //////////
}

```

# 2:

```
    /***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 8 servos, one after the other on the
  first 8 pins of the PCA9685

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These drivers use I2C to communicate, 2 pins are required to
  interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

#define SERVOMIN  110 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  510 // this is the 'maximum' pulse length count (out of 4096)

// May have to adjust values to match your servos
// Test your servo with the procedures below

// our servo # counter
uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutTest!");
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  delay(50);
}
///////////////////Functions//////////////////////

void driveMin() {
  pwm.setPWM(servonum, 0, SERVOMIN);    //Use to test low range
}
void driveMax() {
  pwm.setPWM(servonum, 0, SERVOMAX);    //Use to test high range
}
///////////////End Of Functions//////////////////

void loop() {

  for( int angle =0; angle<181; angle +=15){  // testing only right now
    delay(500);
    pwm.setPWM(1, 0, convert2angle(angle) );   // May only need this for sweeping the servo
  }

}
int convert2angle(int myang){
   int pulse = map(myang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
   Serial.print("Angle/Pulse: ");Serial.print(myang);
   Serial.print(" / "); Serial.println(pulse);
   return pulse;
}

```

**ERROR MESSAGES:**

```
pca9685_TurnoutTest:23:25: error: redefinition of 'Adafruit_PWMServoDriver pwm'

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:21:25: note: 'Adafruit_PWMServoDriver pwm' previously declared here

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void setup()':

pca9685_TurnoutTest:35:6: error: redefinition of 'void setup()'

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:33:6: note: 'void setup()' previously defined here

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void loop()':

pca9685_TurnoutTest:52:6: error: redefinition of 'void loop()'

 void loop() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:48:6: note: 'void loop()' previously defined here

 void loop() {

      ^

Using library Wire at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\Wire
Using library Adafruit-PWM-Servo-Driver-Library-master at version 2.0.0 in folder: C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master
exit status 1
redefinition of 'Adafruit_PWMServoDriver pwm'

```

# Answer
> 1 votes
You seem to compile a sketch from a folder, where more than 1 .ino file is placed. I guess this from the paths, that are mentioned in the error messages.

The Arduino IDE supports you to organize your code into multiple .ino files, so that big code can be read way easier. For this it put's together all .ino files in the folder of the main sketch, so that they get compiled together.

Since you have at least 2 full sketches in the same folder, this leads to a redefinition error, since these resources (the variable `pwm` and the functions `setup()` and `loop()`) are already defined by the first sketch, when the compiler gets the second sketch.

You have to put all your individual sketches into own folders. Then the error will not appear. I tried to compile your two sketches individually and that worked fine.

---
Tags: i2c, servo, pwm, adafruit
---


# Question
Title: Interface a mobile phone's finger print scanner with arduino
Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

# Answer
> 1 votes
Long-shot, but if the phone is still functional enough to unlock with a fingerprint, try sensing the overall screen brightness when locked and when unlocked, and use that as the "Fingerprint matched" signal. Obviously this won't work with a truly dead phone.

A *lot* of processing goes into reading and storing or matching a finger-print. The magic is in the software, not (only in) the sensor. An Arduino (Uno class or similar) is way under-powered for the task. Perhaps one of the Arm- or other high-end Arduinos would have the capability if you had or could write the necessary software.

Short answer: No.

# Answer
> 0 votes
Possible but not directly as the arduino compatible fingerprint sensor contains image formation and saving mechanism which means that those sensors scan a fingerprint form image and send the scan status not the finger print image....

As in case of fingerprint sensor of phones, the sensor directly send the whole image...

so you have to use FPGA (Field Programming Gate Arrays) to make communication between that...

But this is a very expensive way... As FPGA are very expensive but have huge functionality means you can design any circuit any sensor any controller you want using FPGA

# Answer
> 0 votes
In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

* Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
* The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
* As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
* The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
* You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)

All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.

---
Tags: arduino-uno, arduino-nano
---


title: Deep Sleep NodeMCU with Door Sensor

text:
# Question
Title: Deep Sleep NodeMCU with Door Sensor
I have a very simple code of door sensor (magnetic) which gives results in 1 & 0 format. But I want to run the NodeMCU only when a door is open or close. Rest of time I want to keep it in deep sleep mode. Here is my code looks like :

```
int doorClosed = 1;

#define REED_SWITCH D5

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

  Serial.begin(115200);
  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  pinMode(REED_SWITCH, INPUT_PULLUP);
}

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

   Serial.println(digitalRead(REED_SWITCH));

    if ((digitalRead(REED_SWITCH) == HIGH) && (doorClosed == 1))
    {
      Serial.println("DOOR OPEN!!");
      doorClosed = 0;
      digitalWrite(BUILTIN_LED, LOW);
      ESP.deepSleep(0);
    }
    else if ((digitalRead(REED_SWITCH) == LOW) && (doorClosed == 0))
    {
      Serial.println("DOOR CLOSED!!");
      doorClosed = 1;
      digitalWrite(BUILTIN_LED, HIGH);
      ESP.deepSleep(0);
    }
    delay(500);
}

```

Here I am able to put the NodeMCU in deep sleep. But it never wakes up. How can I wake up my chip. After attaching the D0 with RST, I don't event get Serial Logs. I am not sure what kind of behaviour is this. If someone can help me to fix this code will be great!

Thank you!

# Answer
According to this guide:

> The RST pin of the ESP8266 is always HIGH while the ESP8266 is running. However, when the RST pin receives a LOW signal, it restarts the microcontroller.
>
> If you set a **Deep Sleep timer** with the ESP8266, once the timer ends, GPIO 16 sends a LOW signal. That means that GPIO 16 when connected to RST pin can wake up the ESP8266 every time the timer ends.

The only way to wakes up ESP8266 from deep sleep mode **without timer** is set a LOW signal on RST pin.

Example without timer:

```
ESP.deepSleep(0);

```

Connect D0 (GPIO 16) to RST is available only when ESP8266 is in sleep mode **with timer**.

Example with 30sec timer:

```
ESP.deepSleep(30e6);

```

In your case, you can use deep sleep with timer and connect Door sensor to D0 and will act as switch between the RST and D0.
> 0 votes

# Answer
My response is late but herewith my experience that may be of help to others.

NodeMcu in deep sleep will wake-up from external source on receiving a pulse from high to low on the RST pin.

An ADXL345 accelerometer raises an interrupt HIGH on sensing motion and remains high until (I2C) READ to prevent multiple devices from interfering with each other

The following post was instrumental in my finding a solution

https://electronics.stackexchange.com/questions/158015/how-to-turn-continuous-signal-into-a-short-pulse-using-logic-gates
> 0 votes

---
Tags: esp8266, nodemcu
---


title: Why Arduino pins don't output 0 volt?

text:
# Question
Title: Why Arduino pins don't output 0 volt?
```
void setup() {
  pinMode(5, OUTPUT);
}

void loop() {
  analogWrite(5, 0);
  // or
  //digitalWrite(5, LOW);
}

```

Output is 0.003V and the tiny voltage causes the circuit to draw 20uA.

Is there anyway to get absolute 0V from Arduino PWM pin?

# Answer
It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.

LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".
> 3 votes

---
Tags: pwm, voltage
---