# Question
Title: avrdude: stk500_recv(): programmer is not responding: lilypad arduino
i realise this is probably the most common error that is asked about on this forum, but it is a major issue for me. i have an arduino lilypad main board (with the ATMega328P, boot loader already burned), and a generic FTDI serial to usb adapter plugged into my windows 10 laptop. When i try to upload the Blink program from the Arduino IDE, it fails with the error:

`avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfe`

i am using a windows 10 laptop, the Arduino IDE from the windows store. this is a new lilypad, and i have never been able to upload to it. take note that when i reset the board, the pin13 light does flash (but not the way the Blink program specifies, obviously.

i have already tried:

* Rebooting my computer
* Restarting the IDE
* Turning the COM port on and off
* Taking out the RX/TX wires from the FTDI converter
* Pressing the reset button right before uploading (or during uploading)
* Changing which board it is set as in the IDE
* Unplugging and re-plugging the USB-Serial converter

if you have any other possible solutions they would be appreciated, thanks

# Answer
> 1 votes
Last time I bought one of the Lilypads, it did not have a bootloader. I had to buy a SMD programmer adapter that presses down over the 328P chip to bootload it as the board did not break out the ICSP pins to any pads.

I think I got mine here https://hobbyking.com/en\_us/atmel-atmega-socket-firmware-flashing-tool.html but I haven't seen them in stock for a while. Very handy tool tho. Another option is to tack wires to the appropriate uC pins and, connected to a 2x3 header that your Programmer can connect to. Remove the wires when done.

---
Tags: serial, programmer
---


title: Problem with ESP8266, wrong voltage?

text:
# Question
Title: Problem with ESP8266, wrong voltage?
I recently bought a new ESP8266 because I'm pretty sure I used 5V instead of 3.3V on my old one. But it seems the new one behaves the same as the old one.

I'm using the sketch:

https://i.stack.imgur.com/BZRd4.jpg

When I open up the serial monitor and type \[b\]AT \[/b\]I get not response (on the 115200 baud). If I boot up the power supply while the device is connected I get this in the serial monitor:

```
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DOUT
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

Fatal exception 0(IllegalInstructionCause):
epc1=0x40215021, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

```

When I googled the log it seems to be related to the voltage. Could it be the same problem again? If so, what did I do wrong?

# Answer
> 1 votes
The ESP8266 has a relatively high peak current requirement compared to general microcontrollers. This is rarely fully understood. There is a lot of information on the Internet that says the current requirements is about 70mA. But that is a long term operational average. The peak current requirements can be as high as 1/2 an Amp.

When the ESP8266 starts one of the first things it does is an analog calibration. This is where it draws more current. If the power supply can not maintain the minimum required voltage at that current the voltage dip will cause a failure. The duration of this dip can be very short. A digital scope needed to see the fault.

I tend to recommend the use of ESP8266 modules that have an onboard regulator. Modules like the Wemos and Nodemcu type boards.

Using modules like the ESP-01 or the ESP-12 type modules (no regulators) are a lot more touchy. What you need to do is keep the 3.3v regulator as close as possible to those modules, and short solid connections. It also helps to have some additional capacitance across the 3.3v connections at the module.

Breadboards are convenient to use but they also can be the source of poor connections.

Consider what I have wrote here, how it applies to your setup. You may also want to solder an additional capacitor on the module. Vcc to ground. Something like 200-470uF, right onto the top of the module.

---
Tags: esp8266
---


# Question
Title: Arduino: incorrect calculation of long integer
I'm doing a simple calculation with integers (on Arduino with ESP8266 12E), but I can't get the expected result and can't find the error. Can someone guide me?

```
#define A      200
#define B      A * 62
#define C      500

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

   unsigned long aux = 0;

   aux = (B * 500) / C;    // (12400 * 500) / 500 = 12400
   Serial.printf("aux = %d\n", aux);
   aux = aux * C;          // 12400 * 500 = 6200000
   Serial.printf("aux = %d\n", aux);

   // ERROR: Should result in "500", but is resulting in "1922000"
   aux = aux / B;          // 6200000 / 12400 = 500

   Serial.printf("aux = %d\n", aux); // It's printing "1922000"
}

```

# Answer
In your #define of B you missed parenthesis (). Change your definition to:

```
#define B      (A * 62)

```

Without parenthesis you first divide 6200000 by 200 and then multiply result by 62, which is not what you intend.
> 11 votes

# Answer
Fully-parenthesizing macros (as noted in answer by dmz) solves one class of problem.

Another thing you should do is, in any arithmetic expression which involves literal constants, use the `L` suffix on at least one of the constants involved if there's any chance the result will exceed 32767 (the maximum guaranteed-representable value for `int`). The type of an arithmetic operation in C is based on the types of the operands of that operation only; the type of the variable to which the result is assigned is irrelevant.

(edit) For example:

```
long q, r;
unsigned char v = 231;
unsigned char w = 197;

q = v * w * 5;
r = v * w * 5L;

```

`q` might contain 30927, since after the Usual Arithmetic Conversions (6.3.1.8) \[in this case, the Integer Promotions (6.3.1.1-2)\] all operands are of type `int` and it's possible for `INT_MAX` to be 32767 in which case each operation would be performed modulo 32768.

`r` will contain 227535, since the constant `5L` is of type `long` and thus all operations in this expression will be performed on values of type `long`.
> 3 votes

# Answer
As explained in previous answers, fully parenthesizing the macros is the standard solution to this problem in C. However, on Arduino you are programming in C++, and in C++ it is considered good practice to replace this usage of `#define` by explicit constants:

```
const int A = 200;
const int B = A * 62;
const int C = 500;

```

Not only this makes the initial problem go away, it also provides some type safety: you can choose to give these constants other types (e.g. `long`) if appropriate.
> 0 votes

---
Tags: esp8266
---


# Question
Title: What are the purposes of the different LED lights on a Arduino UNO board?
The LEDs namely L, TX and RX on the board. Furthermore, whenever the board is connected, the L LED blinks to the frequency of the delay that I set. \[Eg: delay(1000);\] If I miss any other LED, do mention their purposes as well! Thank you

# Answer
> 4 votes
'L' shows the state of pin13 which is programmable by you for any purpose, whether to read or write to an external device, or just for turn the LED on and off as you have done.

'RX' and 'TX' show the states of the Receive and Transmit pins, respectively, and allow you see when serial communication is taking place.

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


# Question
Title: Problem with MP3 Shield and function calling combination
I wrote this code to control my Christmas tree. It plays the Holy Night Code perfectly but never transitions to the next song. In addition, it plays random notes after the song is finished. Does anyone know what the error is?

```
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

#define TREEONE 3
#define TREETWO 4
#define TREETHREE 5
#define TREEFOUR 10

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for basement 50 for testing

const uint16_t monoMode = 1;

byte song = 1;
byte totalsongs = 10;
int num = 0;
int i;

//put arrays here
const PROGMEM uint16_t arrayTimesMC[] = {670, 249, 116, 249, 100, 249, 132, 249, 125, 249, 102, 249, 116, 249, 82, 249, 130, 249, 118, 249, 94, 249, 125, 249, 100, 249, 110, 249, 95, 249, 134, 249, 156, 249, 125, 249, 107, 249, 142, 249, 110, 249, 73, 249, 96, 249, 119, 249, 115, 249, 83, 249, 101, 249, 168, 249, 120, 249, 111, 249, 108, 249, 102, 249, 104, 249, 106, 249, 115, 249, 122, 249, 136, 249, 100, 249, 99, 249, 136, 249, 138, 249, 113, 249, 111, 249, 117, 249, 148, 249, 115, 249, 102, 249, 100, 249, 108, 249, 140, 249, 115, 249, 93, 249, 148, 249, 119, 249, 91, 249, 136, 249, 84, 249, 185, 249, 104, 249, 126, 249, 148, 249, 83, 249, 74, 249, 97, 249, 105, 249, 166, 249, 128, 249, 95, 249, 158, 249, 122, 249, 220, 249, 42, 249, 66, 249, 180, 249, 387, 249, 236, 249, 350, 249, 3571, 249, 622, 249, 744, 249, 711, 249, 707, 249, 727, 249, 691, 249, 682, 249, 570, 198, 0, 249, 333, 249, 67, 249, 401, 249, 103, 249, 355, 249, 107, 249, 712, 249, 687, 249, 749, 249, 688, 249, 424, 249, 53, 249, 371, 249, 92, 249, 330, 249, 112, 249, 387, 249, 98, 249, 709, 249, 704, 249, 702, 249, 693, 249, 785, 249, 33, 147, 0, 171, 0, 249, 93, 249, 64, 124, 0, 165, 0, 249, 100, 249, 82, 149, 0, 137, 0, 249, 56, 249, 66, 148, 0, 142, 0, 249, 124, 249, 59, 216, 0, 190, 0, 249, 87, 249, 14, 171, 0, 105, 0, 74, 0, 249, 46, 249, 38, 150, 0, 183, 0, 249, 67, 249, 46, 152, 0, 192, 0, 249, 55, 249, 30, 182, 0, 136, 0, 172, 0, 166, 0, 249, 73, 162, 0, 160, 0, 175, 0, 141, 0, 249, 56, 179, 0, 158, 0, 155, 0, 160, 0, 249, 54, 249, 58, 249, 91, 119, 0, 112, 0, 162, 0, 200, 0, 136, 0, 152, 0, 181, 0, 199, 0, 249, 59, 249, 64, 122, 0, 142, 0, 156, 0, 216, 0, 154, 0, 130, 0, 160, 0, 209, 0, 249, 49, 249, 102, 125, 0, 132, 0, 205, 0, 224, 0, 158, 0, 164, 0, 162, 0, 172, 0, 174, 0, 139, 0, 173, 0, 148, 0, 169, 0, 170, 0, 113, 0, 178, 0, 170, 0, 108, 0, 124, 0, 249, 10, 144, 0, 100, 0, 208, 0, 138, 0, 249, 225, 215, 0, 249, 59, 249, 4, 249, 77, 249, 84, 249, 32, 249, 90, 249, 54, 249, 89, 249, 20, 89, 0, 249, 43, 249, 50, 249, 69, 249, 58, 249, 89, 249, 67, 249, 48, 249, 50, 249, 88, 249, 58, 249, 59, 249, 108, 249, 157, 239, 0, 249, 78, 249, 74, 249, 25, 249, 104, 249, 111, 249, 32, 249, 56, 249, 76, 249, 42, 249, 104, 249, 36, 249, 58, 249, 88, 249, 48, 249, 73, 249, 73, 249, 78, 249, 39, 249, 94, 249, 124, 249, 67, 249, 92, 249, 60, 249, 47, 150, 0, 169, 0, 249, 101, 249, 5, 166, 0, 144, 0, 249, 102, 249, 22, 196, 0, 173, 0, 249, 81, 249, 12, 136, 0, 209, 0, 249, 69, 249, 325, 249, 77, 249, 303, 249, 142, 249, 373, 249, 124, 249, 365, 249, 122, 249, 354, 249, 34, 249, 367, 249, 104, 249, 402, 249, 86, 249, 404, 249, 110, 249, 332, 249, 51, 249, 381, 249, 92, 249, 402, 249, 76, 249, 406, 249, 38, 249, 404, 249, 48, 249, 420, 249, 64, 249, 418, 249, 82, 249, 369, 249, 63, 249, 442, 249, 11, 249, 362, 249, 92, 249, 423, 249, 70, 249, 380, 249, 57, 249, 369, 249, 104, 249, 354, 249, 98, 249, 410, 249, 72, 249, 424, 249, 50, 249, 768, 249, 61, 170, 0, 131, 0, 153, 0, 206, 0, 249, 40, 129, 0, 162, 0, 146, 0, 184, 0, 249, 103, 129, 0, 156, 0, 131, 0, 186, 0, 249, 79, 176, 0, 131, 0, 141, 0, 194, 0, 249, 60, 146, 0, 154, 0, 135, 0, 201, 0, 249, 67, 147, 0, 155, 0, 143, 0, 194, 0, 249, 220, 102, 0, 104, 0, 249, 55, 249, 56, 249, 374, 249, 725, 249, 723, 249, 673, 249, 689, 249, 711, 249, 744, 249, 751, 249, 617, 249, 753, 249, 698, 249, 760, 249, 74, 161, 0, 212, 0, 249, 17, 249, 50, 132, 0, 172, 0, 249, 64, 249, 34, 149, 0, 191, 0, 249, 94, 249, 96, 124, 0, 151, 0, 249, 66, 249, 18, 203, 0, 146, 0, 228, 0, 132, 0, 249, 62, 162, 0, 170, 0, 175, 0, 162, 0, 249, 79, 164, 0, 218, 0, 166, 0, 148, 0, 249, 38, 249, 37, 249, 66, 123, 0, 138, 0, 166, 0, 194, 0, 166, 0, 155, 0, 165, 0, 165, 0, 249, 23, 249, 100, 142, 0, 162, 0, 150, 0, 172, 0, 142, 0, 136, 0, 168, 0, 249, 10, 249, 14, 249, 114, 151, 0, 249, 41, 162, 0, 249, 118, 249, 16, 163, 0, 152, 0, 249, 90, 249, 30, 167, 0, 167, 0, 249, 121, 249, 16, 192, 0, 168, 0, 249, 71, 249, 74, 123, 0, 163, 0, 249, 115, 249, 32, 155, 0, 166, 0, 249, 90, 249, 45, 139, 0, 149, 0, 249, 117, 249, 62, 182, 0, 189, 0, 249, 42, 249, 39, 142, 0, 173, 0, 145, 0, 156, 0, 249, 60, 183, 0, 141, 0, 155, 0, 182, 0, 249, 39, 175, 0, 170, 0, 155, 0, 149, 0, 249, 103, 249, 42, 249, 118, 118, 0, 132, 0, 136, 0, 222, 0, 134, 0, 136, 0, 162, 0, 184, 0, 249, 36, 249, 106, 142, 0, 120, 0, 140, 0, 232, 0, 184, 0, 139, 0, 158, 0, 214, 0, 239, 0, 249, 156, 110, 0, 112, 0, 228, 0, 192, 0, 168, 0, 146, 0, 176, 0, 172, 0, 163, 0, 112, 0, 173, 0, 239, 0, 120, 0, 172, 0, 146, 0, 173, 0, 140, 0, 136, 0, 191, 0, 92, 0, 125, 0, 165, 0, 162, 0, 216, 0, 249, 55, 158, 0, 128, 0, 249, 95, 249, 60, 221, 0, 127, 0, 249, 102, 249, 24, 148, 0, 155, 0, 249, 74, 249, 62, 153, 0, 138, 0, 249, 115, 249, 64, 165, 0, 147, 0, 249, 77, 249, 56, 143, 0, 163, 0, 249, 100, 249, 58, 168, 0, 146, 0, 249, 80, 249, 45, 158, 0, 168, 0, 249, 110, 249, 31, 168, 0, 134, 0, 249, 38, 104, 0, 187, 0, 134, 0, 160, 0, 132, 0, 135, 0, 142, 0, 249, 108, 145, 0, 157, 0, 154, 0, 152, 0, 249, 82, 136, 0, 163, 0, 165, 0, 146, 0, 249, 459, 117, 0, 146, 0, 249, 90, 130, 0, 166, 0, 154, 0, 194, 0, 249, 68, 154, 0, 140, 0, 158, 0, 168, 0, 249, 97, 155, 0, 146, 0, 134, 0, 184, 0, 249, 708, 249, 710, 249, 741, 249, 708, 249, 419, 126, 0, 119, 0, 82, 0, 112, 0, 84, 0, 98, 0, 86, 0, 109, 0, 98, 0, 113, 0, 249, 63, 55, 0, 158, 0, 135, 0, 210, 0, 161, 0, 138, 0, 249, 61, 141, 0, 195, 0, 139, 0, 155, 0, 223, 0, 248};
const PROGMEM byte arrayTreeMC[] = {17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 5, 4, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 5, 4, 9, 8, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 3, 2, 3, 2, 5, 4, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 31, 30, 31, 30, 31, 30, 31, 30, 5, 4, 5, 4, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 31, 30, 31, 30, 31, 30, 31, 30, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 17, 16, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 5, 4, 11, 10, 17, 16, 15, 14, 3, 2, 5, 4, 17, 16, 3, 2, 5, 4, 3, 2, 9, 8, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 5, 4, 3, 2, 5, 4, 5, 4, 5, 4, 9, 8, 17, 16, 5, 4, 9, 8, 9, 8, 9, 8, 17, 16, 13, 12, 3, 2, 3, 2, 5, 4, 9, 8, 9, 8, 17, 16, 9, 8, 3, 2, 5, 4, 9, 8, 9, 8, 9, 8, 17, 16, 3, 2, 5, 4, 5, 4, 5, 4, 9, 8, 9, 8, 9, 8, 17, 16, 17, 16, 17, 16, 5, 4, 3, 2, 3, 2, 5, 4, 5, 4, 5, 4, 9, 8, 17, 16, 3, 2, 5, 4, 5, 4, 9, 8, 17, 16, 9, 8, 3, 2, 5, 4, 3, 2, 9, 8, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 17, 16, 17, 16, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 9, 8, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 31, 30, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 9, 8, 31, 30, 17, 16, 9, 8, 17, 16, 17, 16, 3, 2, 5, 4, 9, 8, 17, 16, 31, 30, 5, 4, 9, 8, 17, 16, 3, 2, 5, 4, 9, 8, 17, 16, 3, 2, 5, 4, 3, 2, 9, 8, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 5, 4, 3, 2, 9, 8, 3, 2, 5, 4, 3, 2, 17, 16, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 9, 8, 17, 16, 3, 2, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 17, 16, 3, 2, 5, 4, 3, 2, 5, 4, 11, 10, 21, 20, 11, 10, 21, 20, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 17, 16, 17, 16, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 17, 16, 9, 8, 5, 4, 3, 2, 3, 2, 5, 4, 9, 8, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 9, 8, 17, 16, 13, 12, 11, 10, 21, 20, 11, 10, 21, 20, 3, 2, 11, 10, 29, 28, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 21, 20, 11, 10, 21, 20, 11, 10, 31, 30, 11, 10, 21, 20, 11, 10, 31, 30, 11, 10, 21, 20, 11, 10, 31, 30, 11, 10, 21, 20, 11, 10, 31, 30, 11, 10, 21, 20, 11, 10, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 21, 20, 11, 10, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 5, 4, 9, 8, 3, 2, 17, 16, 5, 4, 9, 8, 3, 2, 17, 16, 5, 4, 9, 8, 3, 2, 5, 4, 17, 16, 3, 2, 9, 8, 5, 4, 17, 16, 3, 2, 5, 4, 9, 8, 3, 2, 17, 16, 5, 4, 31, 30};
const PROGMEM uint16_t arrayTimesHN[] = {28, 246, 1542, 246, 646, 246, 390, 246, 38, 246, 1222, 246, 70, 246, 358, 246, 70, 246, 326, 246, 70, 246, 1542, 246, 326, 246, 70, 246, 358, 246, 70, 246, 650, 246, 290, 246, 70, 246, 680, 246, 320, 246, 70, 246, 1550, 246, 1540, 246, 640, 246, 330, 246, 70, 246, 1250, 246, 70, 246, 360, 246, 70, 246, 330, 246, 0, 246, 1550, 246, 390, 246, 0, 246, 360, 246, 70, 246, 650, 246, 320, 246, 100, 246, 620, 246, 360, 246, 70, 246, 1540, 246, 1250, 246, 40, 246, 650, 246, 670, 246, 650, 246, 650, 246, 350, 246, 40, 246, 360, 246, 40, 246, 640, 246, 360, 246, 40, 246, 610, 246, 680, 246, 620, 246, 710, 246, 350, 246, 40, 246, 330, 246, 70, 246, 1540, 246, 680, 246, 640, 246, 650, 246, 360, 246, 40, 246, 630, 246, 660, 246, 640, 246, 360, 246, 70, 246, 650, 246, 640, 246, 330, 246, 70, 246, 330, 246, 70, 246, 640, 246, 650, 246, 640, 246, 360, 246, 70, 246, 620, 246, 640, 246, 650, 246, 360, 246, 70, 246, 610, 246, 680, 246, 640, 246, 330, 246, 100, 246, 650, 246, 610, 246, 360, 246, 70, 246, 360, 246, 40, 246, 640, 246, 650, 246, 640, 246, 650, 246, 680, 246, 610, 246, 650, 246, 680, 246, 610, 246, 650, 246, 670, 246, 650, 246, 680, 246, 640, 246, 650, 246, 360, 246, 40, 246, 640, 246, 650, 246, 250, 246, 250, 246, 246};
const PROGMEM byte arrayTreeHN[] = {31, 30, 17, 16, 17, 16, 17, 16, 9, 8, 9, 8, 5, 4, 5, 4, 9, 8, 5, 4, 3, 2, 5, 4, 5, 4, 9, 8, 17, 16, 5, 4, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 31, 30, 31, 30, 31, 30, 17, 16, 17, 16, 9, 8, 9, 8, 5, 4, 5, 4, 9, 8, 5, 4, 3, 2, 31, 30, 5, 4, 9, 8, 17, 16, 7, 6, 17, 16, 9, 8, 5, 4, 3, 2, 5, 4, 31, 30, 31, 30, 9, 8, 9, 8, 5, 4, 17, 16, 9, 8, 5, 4, 9, 8, 3, 2, 9, 8, 5, 4, 9, 8, 9, 8, 9, 8, 5, 4, 17, 16, 9, 8, 5, 4, 9, 8, 3, 2, 9, 8, 5, 4, 3, 2, 21, 20, 21, 20, 5, 4, 9, 8, 5, 4, 21, 20, 21, 20, 21, 20, 9, 8, 3, 2, 11, 10, 11, 10, 17, 16, 17, 16, 17, 16, 9, 8, 21, 20, 29, 28, 21, 20, 9, 8, 3, 2, 19, 18, 19, 18, 23, 22, 9, 8, 5, 4, 19, 18, 19, 18, 5, 4, 9, 8, 17, 16, 11, 10, 11, 10, 17, 16, 5, 4, 17, 16, 17, 16, 11, 10, 11, 10, 5, 4, 3, 2, 21, 20, 21, 20, 17, 16, 3, 2, 19, 18, 13, 12, 15, 14, 29, 28, 21, 20, 9, 8, 5, 4, 3, 2, 5, 4, 19, 18, 31, 30, 31, 30, 31, 30, 30};

//put arrays here

void setup() {
  initSD();
  initMP3Player();

  pinMode(TREEONE, OUTPUT);
  pinMode(TREETWO, OUTPUT);
  pinMode(TREETHREE, OUTPUT);
  pinMode(TREEFOUR, OUTPUT);

  digitalWrite(TREEONE, HIGH);
  digitalWrite(TREETWO, HIGH);
  digitalWrite(TREETHREE, HIGH);
  digitalWrite(TREEFOUR, HIGH);
}

void loop() {
  MP3player.playTrack(2);
  OHolyNight();
  delay(92000);
  MP3player.stopTrack();

  MP3player.playTrack(3);
  MetallicaChristmas();
  delay(192000);
  MP3player.stopTrack();
}

void initSD() {
  if (!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if (!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

void AllLights() {
  digitalWrite(TREEONE, LOW);
  digitalWrite(TREETWO, LOW);
  digitalWrite(TREETHREE, LOW);
  digitalWrite(TREEFOUR, LOW);
}

void MetallicaChristmas() {
  for (i = 0; i < sizeof(arrayTimesMC); i++) {
    delay(pgm_read_word_near(arrayTimesMC + i));
    num = pgm_read_byte_near(arrayTreeMC + i);

    if (num > 15) {
      if ((num % 2) == 0) {
        digitalWrite(TREEONE, HIGH);
      } else {
        digitalWrite(TREEONE, LOW);
      }
    }
    if ((num % 16) > 7) {
      if ((num % 2) == 0) {
        digitalWrite(TREETWO, HIGH);
      } else {
        digitalWrite(TREETWO, LOW);
      }
    }
    if ((num % 8) > 3) {
      if ((num % 2) == 0) {
        digitalWrite(TREETHREE, HIGH);
      } else {
        digitalWrite(TREETHREE, LOW);
      }
    }
    if ((num % 4) > 1) {
      if ((num % 2) == 0) {
        digitalWrite(TREEFOUR, HIGH);
      } else {
        digitalWrite(TREEFOUR, LOW);
      }
    }
    if (i == sizeof(arrayTimesMC)) {
      break;
    }
  }
}

void OHolyNight() {
  for (i = 0; i < sizeof(arrayTimesHN); i++) {
    delay(pgm_read_word_near(arrayTimesHN + i));
    num = pgm_read_byte_near(arrayTreeHN + i);

    if (num > 15) {
      if ((num % 2) == 0) {
        digitalWrite(TREEONE, HIGH);
      } else {
        digitalWrite(TREEONE, LOW);
      }
    }
    if ((num % 16) > 7) {
      if ((num % 2) == 0) {
        digitalWrite(TREETWO, HIGH);
      } else {
        digitalWrite(TREETWO, LOW);
      }
    }
    if ((num % 8) > 3) {
      if ((num % 2) == 0) {
        digitalWrite(TREETHREE, HIGH);
      } else {
        digitalWrite(TREETHREE, LOW);
      }
    }
    if ((num % 4) > 1) {
      if ((num % 2) == 0) {
        digitalWrite(TREEFOUR, HIGH);
      } else {
        digitalWrite(TREEFOUR, LOW);
      }
    }
    if (i == sizeof(arrayTimesHN)) {
      break;
    }
  }
}

```

# Answer
Since KIIV didn't write an answer to this question, I will do it.

You are using this for loop:

```
for (i = 0; i < sizeof(arrayTimesHN); i++)

```

The `sizeof()` function will return the size of the array in bytes. Since the array is of type `uint16_t`, each element has a size of 2 bytes (16 bit). Concluding: The `sizeof()` function will return a number twice as high, as the actual element count of the array. The delays and state number, that you use for the LEDs, will be read from memory, that lies after the array. We don't know, what is saved there (or if there is actually some valid data or only random data), so this will seem random. That random notes are played by the MP3 Player must be a problem with the library (I'm not sure about that). What does the library do, if a song is finished, but you didn't call the `stopTrack()` method yet?

---

In the LED functions (for example `OHolyNight()`) you are using delays, but you also set a big delay after the execution of the function. I guess, the big delay is the duration of the song. So you delay twice. The first comes with the accumulated delays in the LED function (while the LED lights are changing). The second delay will kick in after that (when the LED function is finished). Maybe you thought, that it doesn't proceed to the next song, because you didn't wait for 92 seconds (your first big delay).

---

Lastly, in your LED functions you have this if statement:

```
if (i == sizeof(arrayTimesHN)) {
  break;
}

```

This is unnecessary, you used a for loop with the condition `i < sizeof(arrayTimesHN)`, so that `i` cannot ever be equal to `sizeof(arrayTimesHN)` inside of the loop.
> 0 votes

---
Tags: arduino-uno, shields
---


title: String compare when using Serial

text:
# Question
Title: String compare when using Serial
I try to detect commands given by user in Serial Monitor, but `strcmp` fails to flag as identical.

What do I do wrong ?

Is there a better way not reading as `String` and convert to `char` for comparison ?

Guy

```
char* additional_callbacks [] = {"command_1", "command_2", "command_3"};

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

void loop() {
  if (Serial.available() > 0) {
    char tmpchar[50];

    Serial.print("entered_text:");
    String str = Serial.readString();
    str.toCharArray(tmpchar, 50);
    Serial.println(tmpchar);

    for (int i = 0; i < sizeof(additional_callbacks) / sizeof(char*); i++) {
      if (strcmp(tmpchar, additional_callbacks[i]) == 0) {
        Serial.println("match");
      }
    }
    Serial.flush();
  }
  delay(50);
}

```

# Answer
> 1 votes
In your for() loop, use Serial.println() to display both strings before the compare. You'll be able to see why the compare is failing.

Update:

> it seemed identical.

Something has to be different for the test to fail. If the strings look identical then there must be some non-printing characters that differ: \r, \n, , , missing \0 ), etc.

Try printing your buffers byte-by-byte in hex for a few more bytes than the string length, to be sure there is an where it should be.

Or print the buffers with this hexdump function which lists a specified memory range in both ASCII and hex:

```
/***

Name:       hexdump

Function:   Dump memory contents to terminal

Description:Dump a specified range of memory in hex and ASCII

Parameters: byte *mem       - starting address
            uint16_t len    - # of bytes

Returns:    void

Notes:      Based on: http://grapsus.net/blog/post/Hexadecimal-dump-in-C
            Formats with sprintf(); outputs with Serial.print().
            Modified to print ...0 - ...F of each hex-block containing
            any of the requested memory range. Data not in the range are
            not shown.

***/

void hexdump(byte *mem, uint16_t len)
{
   byte *p, *pfirst, *plast;    // -> curr byte, first & last hex-blocks to print from
   char buf[10+1];              // sprintf o/p buffer

   // Print entire hex-blocks that contain the requested mem range,
   // except only show data within the range.
   pfirst = (byte *)((uint16_t)mem & 0xFFF0);           // beg of 1st  hex-block
   plast = (byte *)((uint16_t)(mem + len) | 0xF);       // end of last hex-block

   for( p = pfirst;  p <= plast;  ++p ){

      /* Print block addr */
      if( ((byte *)((uint16_t)p & 0xF)) == 0 ){
         sprintf_P(buf, PSTR("%06X: "), (unsigned int)p);
         Serial.print(buf);
      }

      // Print hex data, or if outside mem range, print spaces
      if( mem <= p && p < (mem + len) ){
         sprintf_P(buf, PSTR("%02hhX "), *p);
         Serial.print(buf);
      }
      else
         Serial.print("   ");                   // outside requested range - just spaces

      // Maybe print gutters and/or ASCII data
      if( ((uint16_t)p & 0xF) == 0x7 )
         Serial.print(" ");                     // narrow gutter after 8 bytes
      // If at end of hex block, print a gutter & re-print the block as ASCII
      if( ((uint16_t)p & 0xF) == 0xF ){
         Serial.print("  ");                    // wide gutter after 16 bytes

         // Print as ASCII.
         // Note: In this loop, we re-use the outer loop's index, 'p', to rescan
         // the hex block. We must leave 'p' as we found it!
         for( p = (byte *)((uint16_t)p & 0xFFF0);  ; ++p ){
            if( !(mem <= p && p < mem+len) )
               Serial.print(' ');               // not in requested mem range
            else if( !isprint(*p) )
               Serial.print('.');               // not printable
            else
               Serial.print(*(char *)p);        // print as ASCII

            if( ((uint16_t)p & 0xF) == 0xF ){
               break;                           // end of hex-block
            }
         }
         Serial.print('\n');
      }
   }
}

```

# Answer
> -1 votes
You try to compare Serial input

> command\_1\r\n

with

> command\_1

and these two are **not** equal.

---
Tags: serial, string
---


# Question
Title: Does enabling the Timer1 CompareA interrupt instantly triggers an interrupt?
I am learning Arduino interruptions and I am unable to explain the behavior of a minimalistic interrupt driven project. The project is the following: an Arduino UNO is connected to two LEDs, on ports 9 and 10, and a button on port 2. The button is listened to for RISING interruptions, which are expected to trigger the following 3 seconds sequence: LED1 `HIGH` (one second); both LEDs `HIGH` (one second); LED2 `HIGH` (one second); during which pressing the button should have no effect.

```
#define led1Pin 10
#define led2Pin 9
#define buttonPin 2

void setup() {

  cli();//stop interrupts

  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(led1Pin, LOW);
  digitalWrite(led2Pin, LOW);
  attachInterrupt(digitalPinToInterrupt(buttonPin), f, RISING);

  TCCR0A = 0;// set TCCR2A register to 0
  TCCR0B = 0;// set TCCR2B register to 0 (sets timer0 prescaler values to "disable timer")
  TCCR2A = 0;// set TCCR2A register to 0
  TCCR2B = 0;// set TCCR2B register to 0 (sets timer2 prescaler values to "disable timer")

  //set timer1 interrupt at 1Hz
  TCCR1A = 0;// set TCCR1A register to 0
  TCCR1B = 0;// set TCCR1B register to 0

  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1
  TCCR1B |= (1 << WGM12);   // turn on CTC mode 1 (compare to OCR1A)
  TCCR1B |= (1 << CS12) | (1 << CS10);// CS12|CS10 => Prescaler 1024
  TIMSK1 = 0;// disable timer compare interrupt

  sei();
}

volatile int index=0;

volatile byte previousState=LOW;
volatile byte state = LOW;

void loop() {
  if (state && !previousState) {
    digitalWrite(led1Pin, HIGH); index=1;
    TCNT1H = 0;
    TCNT1L = 0; //initialize counter value to 0
    TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
    previousState = HIGH;
  }
}

void f() {
  state = HIGH;
}

ISR(TIMER1_COMPA_vect){ //timer1 interrupt 1Hz
  switch(index) {
  case 1:
    digitalWrite(led2Pin, HIGH); index=2;
    break;
  case 2:
    digitalWrite(led1Pin, LOW); index=3;
    break;
  case 3:
    digitalWrite(led2Pin, LOW); index=0;
    state=LOW; previousState=LOW;
    TIMSK1 = 0;// disable timer compare interrupt
    break;
  default:
    break;
  }

}

```

Code adapted from https://www.instructables.com/id/Arduino-Timer-Interrupts/

Upon pressing the button, `state` is set to `HIGH`, which assuming `previousState` and `state` were `LOW`, should get the loop to perform a set of action once as it will set `previousState` `HIGH`.

These actions are the following: set `led1Pin` to `HIGH`, set `TCNT1H` and `TCNT1L` to 0, which should put the Timer1 counter to 0, and then set `TIMSK1` to `0b00000010`, that is, `1 << OCIE1A`, to accept the interrupt when it will be triggered, supposedly one second from the instruction that set the counter to 0, as the timer fires interrupts at 1Hz.

But while the expected behaviour is LED 1 on for one second, both LEDs on for one second, then LED 2 on for one second, the observed behaviour is the following, from my tests:

* First time pressing the button since Arduino reset : LED 1 and LED 2 on for one second, LED 2 on for one second.
* Button presses properly ignored until LED 2 turns off.
* Subsequent button presses : either proper behaviour (LED1 on, both LEDs on, LED2 on); or "first press" behaviour (both LEDs on, LED2 on). In both cases, the cycle sometimes instantly restart (\[optional : LED1 on;\] both LEDs on; LED2 on; LED1 on; both LEDs on; LED2 on), with each state taking one second.

The non-deterministic nature of the problem lets me think I'm mishandling interruptions. The project behaves as if enabling timer compare interrupts instantly triggered one, despite setting the relevant registers to 0 before that. I was unsuccessful in finding information regarding this that would explain the problem.

Is there asynchronous behaviour when setting the `TCNT1H` and `TCNT1L` registers to 0 ? Can a compare match interruption somehow be buffered ? And how comes the cycle sometimes execute twice ?

# Answer
> 1 votes
> The project behaves as if enabling timer compare interrupts instantly triggered one

This can indeed happen, and it's likely what you are experiencing.

Explanation: an interrupt fires when three bits are simultaneously set:

* the “interrupt flag” that signals the detection of some specific event
* the “interrupt enable” bit associated with that particular interrupt
* the “global interrupt enable” bit that is set by the `sei()` instruction

In your case, the relevant interrupt flag is `OCF1A` (Timer/Counter1, Output Compare A Match Flag), in register `TIFR1` (Timer/Counter1 Interrupt Flag Register). This flag is raised by a “timer compare” event, i.e. when the timer value hits the value stored in `OCR1A`. If the interrupt fires, the flag is automatically cleared when the CPU starts executing the corresponding ISR. Alternatively, the flag can be cleared manually by overwriting it with a logic 1 (yes, that's kind of backwards). It is worth noting that the flag records the compare events whether or not the interrupt is enabled.

You normally expect the interrupt flag to be the last of these three bits to be set, so that the interrupt is triggered by the compare event. But this need not be the case. In your program, it is likely that the interrupt flag is raised one second after startup. The global interrupt enable is set by your `sei()` at the end of `setup()`. Thus, at this point, as soon as you set the interrupt enable bit the interrupt fires immediately.

The standard solution to this problem is to clear the interrupt flag right before setting the interrupt enable bit:

```
TIFR1  |= _BV(OCF1A);   // clear timer compare flag
TIMSK1 |= _BV(OCIE1A);  // enable timer compare interrupt

```

---
Tags: arduino-uno, interrupt, timers
---


# Question
Title: Arduino reads hc-05 device connecting status
Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

# Answer
In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.

`AT+BIND?` gives you which device you currently paired.
> 1 votes

# Answer
Different Bluetooth adapters (using the HC-05 module) provide different signals, besides its Rx and Tx. Most bring out a "key" input that puts the module into command mode where serial communication is between the external pins and the module itself - 'AT' commands & queries to the module's firmware. When the module is not in command mode, the firmware just passes serial data through the Bluetooth radio, ignoring the content. Some provide an LED- or State signal that you can read (or observe on an LED) to know whether the devices is paired (communicating) or unpaired (in command mode).

On some, this is a simple logic signal; on others it is a square wave of 1/2 to 1 Hz which means your code has to track the signal to know whether it is static (typically High when paired) or toggling (for unpaired/waiting to pair).

You need to read your module's datasheet to find out the behavior of this signal on your particular module. If you connect an LED to this signal, or your module has one on the board, you can often make a good enough guess by observing it with a stopwatch. Either way, you then need an Arduino function that samples the LED periodically, remembering what state it saw and for how long, to decide whether the LED is blinking or is steady.
> 0 votes

---
Tags: serial, communication, softwareserial, hc-05, arduino-pro-micro
---


# Question
Title: Teensy not pulling down despite digitalWrite(x,LOW)
I'm trying to switch a ATX PSU on and off by serial command. My code is as follows:

```
#include <Arduino.h>
#define PIN_LOW_FOR_POWER PIN_F0

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

void loop() {
  String sCode = Serial.readStringUntil('\n');
  if (sCode == "M80"){
    digitalWrite(PIN_LOW_FOR_POWER, LOW);
  }
  else if (sCode == "M81"){
    digitalWrite(PIN_LOW_FOR_POWER, HIGH);
  }
  else{
    Serial.println("Unknown command");
    return;
  }
  Serial.println("OK");
}

```

I'm getting "OK" back, and the power switches. After sending M81 I read 5V across the pin and ground, but after sending M80 for some reason I read 2.37V and not 0V. If I switch to "F1" (keep the wire connected to F0) I do read 0V.

The ATX PSU needs F0 to be pulled down in order to turn on. I soldered the ground of the ATX PSU to the Teensy ground, and the wire to be pulled down (green) to F0. I supply the 5V to the Teensy through USB, so the VCC pin is left unconnected.

The PSU does turn on if I manually create a short between F0 and ground.

Why doesn't the Teensy pull F0 down, and how do I resolve this? (All I could come up with is something of internal resistance within the Teensy being too high, which seems unlikely to me. (If the resistance within the PSU and wires between "green" and ground is equal to the resistance within the Teensy this would happen, right?))

PS: It turns out I bought a fake Teensy from China, if it's related. Ordered a new one for a different project, but still had this one laying around.

# Answer
> 0 votes
You forgot to set the IO pin to OUTPUT. Unless you do so all you are doing (if the Teensy core follows the Arduino API to the letter) is controlling the internal pullup.

```
pinMode(PIN_LOW_FOR_POWER, OUTPUT);

```

---
Tags: electronics, teensy
---


# Question
Title: What is the sizeof() Arduino's built in HIGH and LOW?
This might be a stupid question to ask but I'm curious. I decided to test this myself and I got a value of 2 for both HIGH and LOW, why would it output 2?

# Answer
> 1 votes
In Arduino AVR Boards, HIGH and LOW are currently macros:

https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/Arduino.h#L40-L41

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

```

This means that `sizeof(HIGH)` is equivalent to `sizeof(0x1)`. `0x1` is an integer constant. The default type of integer constants is int. On an 8 bit microcontroller like the ATmega2560 used by your Arduino Mega, an int is 16 bits.

That is why `sizeof(HIGH)` returns 2 (16 bits / 8 bits/byte = 2 bytes).

---
Tags: arduino-mega
---


# Question
Title: How to send characters to Arduino serial using Linux command line without tail -f?
I want to send characters to Arduino serial port which makes the Arduino turn on/off an LED. Here is the code:

```
int led_main=8;

void setup()
{
    pinMode(led_main, OUTPUT);

    Serial.begin(9600);
}

void loop()
{
    char chr;

    if (Serial.available())
    {
        chr = Serial.read();

        if (chr == '0')
        {
            digitalWrite(led_main, LOW);
        }
        else if (chr == '1')
        {
            digitalWrite(led_main, HIGH);
        }
    }
}

```

The Arduino is recognized as either `/dev/ttyACM0` or `/dev/ttyACM1` in my system. When I run the command `echo "1" > /dev/ttyACM0`, it doesn't work. But, when I open a second terminal, run `tail -f /dev/ttyACM0`, and then in the first terminal, run `echo "1" > /dev/ttyACM0`, it turns on the LED as expected. So why do I have to open a second terminal and keep monitoring the output with `tail -f` in order for this to work? Is there a way to do this with a single command?

# Answer
> 2 votes
Arduinos have auto-reset circuit to reset the board if new connection is initiated on USB. It is good for convenient upload or to reset for debugging at Serial Monitor open. But it causes troubles if you want to communicate with MCU from computer over USB from command line tools, scripts, python, C++, C#, Java. Always on new connection the board resets.

One solution is to disable the auto-reset circuit. Other option is to wait a second after the connection while the board resets.

---
Tags: arduino-uno, serial, linux, ubuntu, command-line
---


title: trying to use millis()

text:
# Question
Title: trying to use millis()
I'm learning how to use the millis() function. Instead of having it in the main body of the program I wanted to place it in a function so I can change the time interval with which an led will flash. I modified the code blinkWithoutDelay. My code is below. The output I get is an LED that is always on. I did print the output of the ledState to the serial monitor. Its changing from on to off repeatedly. So I think the led is really flickering too fast to see. I took a screenshot from the serial monitor. The output is below.

```
const int LED2 = 2;
int ledState2 = LOW;

void timeCheck(int interval)
{
    unsigned long cMillis = millis();
    unsigned long pMillis;

    if (cMillis - pMillis > interval)
    {
        pMillis = cMillis;

        if (ledState2 == LOW)
        {
            ledState2 = HIGH;
        }
        else
        {
            ledState2 = LOW;
        }
        digitalWrite(LED2, ledState2);
        Serial.println(ledState2);
    }
}

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

void loop()
{
    unsigned long flashtime = 1000;
    timeCheck(flashtime);
}

```

# Answer
> 2 votes
The problem here is that the variables you declare in your function are not static. The rest of the code works as expected.

Where you declare the variables at the beginning of your function is correct. There is only one variable in question though as it is the cause of the error you are seeing.

What you need to do is change the variable

```
unsigned long pMillis;

```

to

```
static unsigned long pMillis = 0;

```

By not having the `pMillis` as a static variable, each time the function is called the value of `pMillis` is undefined, which means it is unpredictable whether  `(cMillis - pMillis > interval)` will be true or false. But with the `static` declaration the Arduino knows to keep the previous value for the next time you call the function.

An excerpt from Wikipedia:

> In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program....
>
> A static local variable is different from a local variable. It is initialized only once no matter how many times that function in which it resides is called.

# Answer
> 0 votes
Put it out, so it will be global. LedStaye should be bool: `const int LED2 = 2;
bool ledState2 = LOW;
unsigned long pMillis;`

`void timeCheck(int interval)
{
 if (millis() - pMillis > interval)
 {
 pMillis = millis();
...`

# Answer
> 0 votes
You have used `pMillis` variable locally. Thats why when you call the function, `pMillis` initialized as 0. So set `pMillis` variable globally.

---
Tags: millis
---


# Question
Title: '"/dev/ttyACM0": Permission denied' on Ubuntu 18.04
I'd like to say that I'm a noob at both Arduino & Ubuntu (have some command line experience).

I've set port permissions, joined the relevant groups (tty,uucp,dialout & plugdev). I know that the IDE recognizes the board because ttyACM0 only shows up when the board is plugged in. I've searched the Internet and Stack Exchange and Arduino troubleshooting guide and tried all the suggestions. It's not Genuino but a knock-off that's recognized as an Uno. I've got to be missing something.

Are there any relevant logs or a way to monitor whats going on in realtime?

Verbose upload output:

```
Arduino: 1.8.5 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/snap/arduino-mhall119/5/hardware/tools/avr/bin/avrdude -C/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_241052/Blink500.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/harry/snap/arduino-mhall119/5/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

```

# Answer
> 1 votes
As stupid as it may sound but "have you tried turning it off and on again?". Changes to groups only become effective when you have logged out of your account

---
Tags: arduino-uno, uploading, linux
---


# Question
Title: What is the typical form for a finished Arduino project?
I just started with Arduino. I am an experienced software developer so the programming side was already mostly known to me, and I am surprised at just how easy Arduino have made the hardware side of things, and how easy to use the various libraries are. So for my first non tutorial project, I want to make air quality sensor web servers to be placed in several rooms throughout my house. I will then have a program running on my PC which collects readings from each sensor and stores then somewhere, to be analyzed later.

All I have right now is an Arduino UNO R3 starter kit, and I am having a WiFi shield delivered today. I feel confident that I can have a working version using the kit that I have shortly after the shield gets delivered.

But my question is: what is the best (some combination of easiest and cheapest) way to crank out half a dozen of these?

Presumably, most experienced makers don't include a breadboard in their finished products? I suppose I should buy a soldering iron.

Should I buy half a dozen UNO R3s and half a dozen WiFi shields (along with air quality sensors)? Or is there a cheaper option that is intended for semi-productionizing an Arduino project?

PS: I feel like the tags I have included barely intersect with the purpose of this question, so if you know of any more appropriate ones, feel free to suggest/edit.

# Answer
I'm in the same boat as you (SW engineer by trade who likes to tinker with electronics, and is a "maker" at heart.)

I think the answer to your question is "it depends." For a one-off, a breadboard might be fine.

For half-a-dozen, you might want to get project cases and perf-boards, and solder up your design. (For the Mega, there is a very nice prototyping "shield" that brings all the pins from the Mega up on headers and has quite a bit of working room for soldering up circuits.) If you want to make more than a handful, though, you'd probably want to create a custom PC board. You can either create a design in a CAD program and send it off to be small-batch manufactured, or you can buy the equipment to do it yourself. If you make hundreds of units, you should think about ditching the Arduinos and designing a completely custom board using the AVR-family microcontroller and only the components you need.

(I'm still at the breadboard/hand soldered perf-board stage myself, and haven't created any custom PC boards yet, just read about it.)
> 1 votes

# Answer
The "final" form of an Arduino "project" is not an Arduino project at all.

Arduino and the associated shields and breadboards are just development tools. They are intended to be used *during development* only.

As soon as you want to take the next step (certainly if you don't want to be laughed at by professionals) and create a product you need to learn about building your own PCBs. That means taking the schematics of all the shields and boards you are using and combining them all into one schematic, then designing a board from that schematic - and that, of course, means being able to understand what a schematic means.

It's kind of like taking the step from playing with LEGO® to building a house (or a garden shed maybe). There's a lot of learning you have to go through between the two stages.

There are plenty of online resources to get you started with schematic design and PCB layout, but to do it properly takes years of proper training. If you are serious about moving from just tinkering as a hobby you should consider formal training with a reputable educational establishment.
> 1 votes

---
Tags: arduino-uno, sensors, wifi, shields
---


# Question
Title: Detecting the down time of a system by subtracting the time when the sytem gives ON signal and when it goes OFF
```
int pin_state = LOW;
struct Channel {
    byte pin;
    byte state;
    byte count;
    unsigned long fell, rose;  // times of fall and rise
};

const int CHANNEL_COUNT = 3;
Channel channels[CHANNEL_COUNT] = {
    { 2, LOW, 0, 0 },
    { 3, LOW, 0, 0 },
    //{ 4, LOW, 0, 0 },
    //{ 5, LOW, 0, 0 },
    //{ 6, LOW, 0, 0 }
};

void setup()
{
    for (int i = 2; i <= CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    //Serial.println("pin,fell,rose,low time");
    Serial.println("Minutes, Seconds, Count");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i)
    {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == LOW && new_state == HIGH)   // input rose
        {
            c.rose = millis();
            c.count = c.count + 1;
        }
        else if (c.state == HIGH && new_state == LOW)  // input fell
        {
            c.fell = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

void display_channel(const Channel &c)
{
  int minutes, seconds;
  unsigned long difference;
  difference = c.fell - c.rose;
  seconds = int(difference/1000);
  if (seconds >= 60)
  {
       minutes = seconds / 60;
       seconds = seconds % 60;
  }
    //Serial.print(difference/1000);
    //Serial.print(",");
    Serial.print(minutes);
    Serial.print(",");
    Serial.print(seconds/1000);
    Serial.print(",");
    Serial.println(c.count-1);
    //Serial.print(",");
  }

```

In this code, I tried to measure the time taken between the two events (when the ON signal comes and when the signal goes OFF) in two different channels simultaneously. But the code doesn't give any output and the serial monitor is empty except for the statement in the main function.

It would be useful if anyone could find where exact;y the problem is and a valid solution to it would be helpful.

edit : I made the following changes but still output is never displayed. Any error is still ON the program?

# Answer
> 2 votes
You have the same state being tested twice:

```
if (c.state == LOW && new_state == HIGH)   // input rose

```

and:

```
else if (c.state == LOW && new_state == HIGH)  // input fell

```

If "A", else if "A". It makes no sense. I think you wanted the second one to be the opposite:

```
else if (c.state == HIGH && new_state == LOW)  // input fell

```

Also, this calculation in `display_channel` doesn't work:

```
if (seconds >= 60)
{
  seconds = seconds % 60;
  minutes = minutes + 1;
}

```

For example, if seconds is 378, then seconds ends up as 18, and minutes as some undefined number plus 1.

That whole block should be replaced with:

```
minutes = seconds / 60;
seconds = seconds % 60;

```

In your code:

* `minutes` starts off undefined
* You add only 1 to `minutes` regardless of how many minutes have passed.

---
Tags: arduino-uno, millis
---


# Question
Title: How can I pulse a stepper motor whilst also wanting to handle other tasks?
A Polulo `A4988` driver board listens for a `LOW -> HIGH` pulse on a digital pin to step a stepper motor.

A simple way to pulse this with a delay of say `100μs`, is to use the `delayMicroseconds` function:

```
#define STEP_PIN  3
#define DELAY     100

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

void loop(){
    //heavy computation taking time
    digitalWrite(STEP_PIN, LOW);
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(DELAY);
}

```

Although this works, the issue is that all the time that the processor spends in the `delayMicroseconds` function is *wasted*. This means that if I wanted to, for example, handle inputs from a serial line, I would have no time to do this. In addition, the time for these computations to complete would result in the pulse time increasing which is not ideal as the speed of the stepper would no longer be uniform.

How can I efficiently pulse the stepper at the correct time, whilst leaving my self room to run other tasks between pulses?

---

P.s. This is for this project: https://github.com/joeiddon/chess\_robot.

# Answer
Instead of delaying between pulses, loop around the main `loop()` function as fast as possible *constantly checking the time to see if we should pulse the motor*.

This means that computations can occur in the loop (so long as they are reasonably fast).

To implement this, the `micros()` function can be used to get an unsigned long representing the microseconds that have passed since the start of the program.

Then in each loop cycle, we need to check if the difference between the current time and the last time that we pulsed is `>=` the pulse delay. In which case, we send a pulse to the motor

However, instead of setting the last pulse time variable to the current time, we instead increment the last pulse variable by the delay time. This has the affect that even if we were slightly late in pulsing, we pretend that we *did* in fact pulse at the right time so that they do not drift over time.

This would look something like:

```
#define STEP_PIN  3
#define DELAY     100

uint32_t last_pulse;

void setup(){
    pinMode(STEP_PIN, OUTPUT);
    last_pulse = micros();
}

void loop(){
    //heavy computation taking time
    if (micros() - last_pulse >= DELAY){
        last_pulse += DELAY;
        digitalWrite(STEP_PIN, LOW);
        digitalWrite(STEP_PIN, HIGH);
    }
}

```

---

*Note that there is a slight subtlety here in that the result from `micros()` and therefore the value of `last_pulse` will overflow after `~70` minutes. However, because we are taking a **difference** of two unsigned numbers, this method will still work, so long as `micros()` is never a whole cycle ahead of `last_pulse` which in practice will never be the case.*
> 1 votes

---
Tags: loop, stepper-motor, a4988
---


# Question
Title: ESP8266 error: espcomm_upload_mem failed while uploading sketch
First of all, I would like to apologize for posting this error once again to this community. However, I have been studying articles for last many days to resolve this error. Unfortunately, I did not get any solution which could resolve my problem.

Below is the error which I get when uploading a sketch (even the example sketch):

warning: espcomm\_sync failed
error: espcomm\_open failed
error: espcomm\_upload\_mem failed
error: espcomm\_upload\_mem failed

Here are the connections:
Vcc - 3.3V
RST - 3.3v
CH\_PD - 3.3v
Tx - Rx
Rx - Tx
GPIO0 - GND
GND - GND

I tried various combinations like Tx to Tx, Rx to Rx, pulling off GPIO0. Pulling off reset and ch\_pd. Supplying external power source, supplying power directly from Arduino using 3.3V. Supplying power from Arduino 5V using an LD33V regulator. I have even tried uploading the code using USB to TTL. But every time I get exactly the same error.

# Answer
Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).

Even so, I got this error a few times. You must keep two things in mind:

1. In operation mode, the CH\_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.
2. In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.

EDIT: Here are some photos of the setup
> 1 votes

# Answer
Please verify you're choosing the right board -Generic ESP for ESP-01.
> 1 votes

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


# Question
Title: Nodemcu 1.0 and boot mode (1,6) after soft reset
I have a problem with a nodemcu 1.0 (lolin) board. Sometime a soft reset is performed from the watchdog and the board freezes in boot mode (1,6) (I have to manually reset the board to restart it). I have read many thinks on this topic and I have carefully avoided to use the GPIO0, GPIO2 and GPIO15. I have also verified that these pins are correctly pulled-up (GPIO0 and GPIO2) and pulled-down (GPIO15) but when the board frezes I have noticed that the voltage of the GPIO0 is not 3.3V but 2.0V. Has anybody experienced a similar problem? Could you help me in solving it?

I wish you all a happy new year. Cheers.

# Answer
> 0 votes
The esp8266 has a bug (documented). After Serial upload the program is started without reset and then at soft reset the state of "start bootloader" is still active.

---
Tags: esp8266, reset
---


# Question
Title: Arduino Ethernet Shield 2: How can I automatically determine the MAC Address?
I'm using an Arduino Mega. I know that Ethernet Shield 2's come with a sticker with the MAC Address printed on it. This would imply to me that this address is hardcoded into the shield. Is there any way to recover the MAC without manually entering it in the sketch? Thanks!

# Answer
> 3 votes
No, the W5500 chip does not have a mac address. You can give it any mac address that you want. The router might not like some mac addresses though.

There are online mac address generators.

The sticker with the mac address is an extra service. It is unique number. But it is just a number on a sticker, it is not related to that specific shield.

Often the mac address DEADBEEFFEED was used. But when two different Arduino boards use the same mac address, the router thinks it is the same device. When there are two devices with the same mac address at the same time connected, that is for sure a way to mess up the router.

# Answer
> 0 votes
This is an old question, but I wanted to share my code which fixes this. Basically, the next code generates a "locally managed address" and stores it to EEPROM. On subsequent starts, it read the address from EEPROM so that you would generally get the same IP address from the DHCP server.

If you do not have EEPROM, you may have another memory that survives programming cycles (SPI Flash, RTC RAM, etc) - you'll need to update the sketch for that.

```
#include <EEPROM.h>

// If defined, report information about MAC ADDRESS INITIALISATION
#define ENABLE_MAC_INIT_MESSAGES

// Local mac address, initialiser can be removed (when using initMacAddress)
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};

void initMacAddress() {
  // Rather than having a fixed MAC address for an Arduino sketch,
  // this implements a different, random address which is persistant
  // by storing it to EEPROM (which only works when EEPROM is available).

  // Here the MAC ADDRESS IS LOCATED AT ADDRESS 0 OF THE EEPROM
  for(int i=0;i<6;i++) {
    mac[i]=EEPROM[i];
  }

  // Generating a new MAC address if the address found is not locally
  // Administrated.  This test requires that the 2 lower bits of the first
  // byte are equal to "2" (bits 1 and 0).
  // Normally it is only required that bit 1 is "1", but checking bit 0 for a 0
  // allows to detect an uninitialized EEPROM.
  if((mac[0]&0x03)!=2) { // Is this a locally administered address?
    // No a locally managed address, generate random address and store it.
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println("GENERATE NEW MAC ADDR");
    #endif
    // make sure random numbers used are not always the same
    randomSeed(analogRead(0));
    for(int i=0;i<6;i++) {
      mac[i]=random(256);
      if(i==0) {mac[0]&=0xFC;mac[0]|=0x2;} // Make locally administered address

      EEPROM.update(i,mac[i]);

      #ifdef ENABLE_MAC_INIT_MESSAGES
        if(mac[i]<10) {Serial.print('0');}  // Print two digets
        Serial.print(mac[i],HEX);Serial.print(":");
      #endif
    }
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println();
    #endif
  }
}

void setup() {
  initMacAddress();
  /*...*/
}

```

EDIT: An anonymous use suggested a call to randomSeed(analogRead(0)); to ensure that the generated value is random. This (may) need to be done only once in the program. It's best done in the 'setup()' as the analog pin that can actually be used depends on the application - one might also use more complex & random initialisation schemes.

---
Tags: arduino-mega, shields, ethernet
---


title: Lowest power possible in Arduino

text:
# Question
Title: Lowest power possible in Arduino
I have googled all around and I know about some tricks to make ATmega328 not being a power hog. I am using **Arduino Nano V3.0**.

However, I didn't find out what is the minimal consumption possible with it?

My project consists of an Arduino that will wake up each 10 seconds and, by bluetooth (BT) will scan for existing devices, and if one specific device is not listed, it will lit a LED for 5 seconds and then go to sleep again.

In sum:

1. Sleep for 10 secs
2. Wake up
3. Scan for BT devices
4. If device ABC is in the list go to 1.
5. Lit LED
6. Delay 5 secs
7. Go to 1.

For bluetooth I will use **NRF8001**, because it is the most efficient BT module I know so far.

Can you give me some ideas of what tricks should I use to make this ATmega328 and BT module last like one year with a **500mAh battery**? Has anyone tried this that can share his experience? Is ATmega328 the right uC for this? I am using it just because I already have code/libraries for it.

---

> Creating the new tag 'nrf8001' requires at least 150 reputation. Try something from the existing tags list instead.

# Answer
The issues regarding efficiency of power are:

1. The CPU speed
2. The Voltage
3. The Power Regulator (not supply)
4. The Peripherals

Address each one of these and don't over look any of them. Or any sub component. But note that some are more impacting than others.

1. while it is possible to lower the speed, It is more practical to just sleep. As you have indicated you are going to do.
2. Running at 3V instead of 5V is a big savings. Note that the 328 can run as low as 1.8V
3. DON'T use Linear Regulators. Most all Arduino's have a 7-12V to 5V(or 3.3V) Linear Regulator. This just burns the difference between the supply (aka battery) and the VCC, used.
4. pay attention to the peripherals. Likely this means getting rid of not needed devices. Example the USB to Serial chip that exists on the Nano. What is the lowest voltage can the radio run at? Must it run at a regulated voltage. Use the largest possible resistor values. Such as on pull ups. A 500K pull up will draw less current than a 10K. Where if too big any capacitance may slow it down. Which is likely acceptable.

One of the biggest savings is running directly off of the Battery without a Linear Regulator. Where the ATmega328P can run from 3V down to 1.6V. It would be recommend to use the Brown Out detector.

Also note that ALL batteries have a self discharge rate. This will determine the maximum possible life of the battery, then minus your devices consumption.
> 6 votes

# Answer
Read the link in @j-g-faustus 's comment - very thorough. http://www.gammon.com.au/power \- it starts with a stock board running at 50milliAmps and ends up at 0.002 milliAmps.

You will also need to find out the power consumption for your BT module - this may dwarf the power arduino's power consumption. The same goes for the LED.

Normal LEDs run at about (ballpark!) 20 milliamps - this means that on the coin battery mentioned by @Omer, 200milliAmp-hours/20 milliAmps = 10 hours of led light.

You can measure the power draw with a multimeter; stick your probes between the + of the battery and whatever the battery would normally connect to (you will have to disconnect the battery of course) - if using a 9v battery, plug in the negative, disconnect the positive, turning the snap connector 90 degrees; then you can put one probe on the battery, the other on the (open) snap connector. Measure Arduino awake + led on + BT connected and sending data. Measure again with everything off/idle/sleeping. Work out how much time it will spend in each state; this will give you an average number of milliamp-hours.
> 2 votes

# Answer
These are essentially notes in support of other answers:

One year = 8765 hours.

So average drain for 1 year life from 500 mAh
= 500 mAh/8765h
= 57 uA average.
To get one year on a 500 mAh battery you need to have average drain under say 50 uA

An efficient modern LED
is usefully bright at 1 mA and
probably very acceptable at 0.1 mA.

Best LEDs are 30 Cd+ at 20 mA
so 150 mCd mean at 0.1 mA
and your eye-brain sees more like the peak.

0.1 mA at 1% duty cycle for one year
= 8765 x 0.1 x 1/100
= 8.765 mAh
or about 2% of your battery capacity.
> 2 votes

# Answer
Easy Very Low Power BLE in Arduino covers using Arduino IDE and nRF52832 chips to code very low power projects, i.e. \<100uA continuously, waiting for connection or while connected and sending data.

The \<100uA current is at max tx power and can be further reduced by reducing Tx power and increasing the advertising and connection intervals. Ignoring the LED, you should be able to get close to the 1year on a 500mAH battery.

Currently working on adding two small solar cells (50mm x 30mm) to extend battery life. These cheap cells ($0.60) don't need full sun and work well in the shade or out of the sun near a window or under a desk lamp.
> 2 votes

# Answer
Lowest possible power consumption for an Arduino is 0mA - just disconnect it's Vcc :)

And seriously, when there are many factors involved, it is hard to include all of them into the proper equations, considering different factors that affect the current consumption such as temperature, humidity, quality and distance of the wires etc. Best would be to perform measurements of the power consumption for, say, several cycles of steps 1 to 7, and do the average.

Remember that the ATmega chip will draw more current depending on the voltage, so you might want to keep voltage as low as possible.

Here is a nice project of an ATtiny (Arduino alike) that runs on a coin CR2032 battery (~200mAh) for **220 days** until it died, while wirelessly broadcasting the results and the measurements of the battery discharge rate, so you could actually achieve pretty good results working with a 500mAh battery.
> 1 votes

# Answer
For simple applications like this, you might find it more convenient to use a smaller board/MCU from the Arduino system. For example the Digispark uses an ATtiny85 rather than the standard ATmega328P. It's not clear that the MCU itself would use much less power (it's pretty much the same CPU core, after all, though you are powering less RAM) but the board has only the one MCU and the regulator on it. You can still power it from and program it via USB (at 5 V) for development, but for production use you can (as others have mentioned) provide 1.8 V power on the VCC line, ignoring the regulator, and you will not have to worry about the power usage of things like the USB interface (an FT232 on the Nano, but a whole second microcontroller on some other boards!) and other parts on the Nano.
> 1 votes

---
Tags: power, bluetooth, arduino-nano, atmega328
---


title: Why is this failing after 3 iterations?

text:
# Question
Title: Why is this failing after 3 iterations?
I simply cannot figure this out, why is this failing after 3 iterations? Other than that, what better way is there to do this? Thanks!

```
#define rotary_encoder_topic  "/rotary/encoder"
#define remote_button_topic  "/remote/button"
#define remote_2x_toggle_topic  "/remote/2xtoggle"
#define rotary_button_topic  "/rotary/button";
char* devices[] = { "ledrpi", "lamprpi", "mediaroom" };
int currentDevice = 0;

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

void incrementCurrentDevice() {
  currentDevice++;
  if (currentDevice >= sizeof(devices)) {
    currentDevice = 0;
  }
 Serial.println(concatenateChars("Switched device to: ", devices[currentDevice]));
}

char* concatenateChars(const char* one, const char* two) {
  char result[150] = "";
  strcat(result, one);
  strcat(result, two);
  return result;
}

void loop() {
  Serial.println(concatenateChars(devices[currentDevice], remote_2x_toggle_topic));
  incrementCurrentDevice();
  delay(1000);
}

```

# Answer
> 1 votes
As Jaromanda X pointed out in the comments, `sizeof(array[0])` (size of first element) will not return the size of the literal strings, but the size of a `char` pointer.

---

It doesn't work (whatever that means for you), because `sizeof(devices)` doesn't return the number of entries in the array, but the size of the array in bytes, e.g. something like (following is wrong: 24 (1 byte per character plus 1 byte with the concluding null character for each string) ) 6 (The size of a `char` pointer is 2 bytes on most microcontrollers; I'm not sure, if this is the same for Node MCU). So after 3 iterations (which can use the string literals in the array) `currentDevice` doesn't go back to zero, but counts further. With the access to the array with exceeding index you are accessing memory, that doesn't belong to the array anymore (e.g. random data).

There is no native function, that gives you the length of an array. But it can be calculated with `sizeof(array)/sizeof(array[0])`, which is the size of the array in bytes divided by the size of one element in bytes. In your case you would have an array size of 6 and an element size of 2, resulting in a calculated element count of 3, which is correct.

Another simple solution, which is easier to understand for beginners, but not as flexible, is to set a constant or define, that contains the size of your array. You can then use it in your code, whenever you need the size, including, when you define the array.

---
Tags: nodemcu
---


# Question
Title: Software serial conflict with WiFi on ESP8266
I'm trying to use an ESP8266 (Wemos D1 mini) to read from a 19.2K serial port and report the results over WiFi. Programming is via Arduino IDE. The code to read the port works just fine if WiFi is not enabled. Once WiFi is enabled I lose chars from the input stream. I've seen several posts in various places that point to problems with using SoftwareSerial and WiFi at the same time, apparently having to do with timing conflicts. My latest attempt calls

```
WiFi.disconnect();

```

before the code that reads the chars from the serial stream, then calls

```
WiFi.reconnect();

```

after reading the serial stream but before making the calls to send data over the web. This did not work.

My code is reading from the serial port in a (blocking) loop, which other posts suggest is the problem. This is not a problem when there is no WiFi object connection. I could restructure the code to create a non-blocking read, but that would be a significant effort (and make the code much harder to understand), so before I go that route I'm wondering if there is a different solution.

# Answer
As noted, there are conflicts between Wifi and SoftwareSerial. The attempt in the question to disconnect WiFi is a step in the right direction, but not enough. You have to actually turn off the WiFi. The challenge is to reliably shut down the WiFi and then start it up again. This has been discussed extensively in the ESP8266/Arduino Git repository here and is referred to by some as "Issue 644". An sample implementation of the code to reliably is presented here.

Here's what the on/off functions look like. I strongly urge you to go to the code linked above and copy from there rather than here, though.

```
extern "C" {
#include "user_interface.h"
#define WIFI_RETRIES 25

int conn_tries = 0;
bool WiFiOff() {
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
    WiFi.forceSleepBegin();
    yield();

    /*
     * It can take a while for the ESP to disconnect, so we need
     * to give it a couple of seconds before returning a fail.
     */
    while ((WiFi.status() == WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() != WL_CONNECTED)
        return (true);
    else
        return (false);
}

/*
 * Turn the WiFi back on again with forceSleepWake().
 * NOTE:-  =Your= SSID and password must be in the
 *         user_config.h file.
 */
bool WiFiOn() {
    conn_tries = 0;

    WiFi.forceSleepWake();
    WiFi.mode(WIFI_STA);
    wifi_station_connect();
    WiFi.begin("corazon_del_bosque", "");

    /*
     * It may take a while for the ESP to re-connect, depending
     * upon external factors (e:- has the access-point moved out
     * of range since we were last connected?).  This loop will
     * give us a reasonable time to re-connect without blocking
     * permanently.
     */
    while ((WiFi.status() != WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() == WL_CONNECTED)
        return (true);
    else
        return (false);
}

```

I'm using this code in my program via the Arduino IDE. The author used it in PlatformIO. Other build systems may have other requirements.
> 3 votes

# Answer
WiFi uses interrupts. Alot. SoftwareSerial doesn't work well with interrupts. On the Arduino all interrupts are disabled while SoftwareSerial does its work. I don't know how it is implemented on the ESP8266, nor how interrupts operate on the ESP8266, so cannot comment on how to work around it.

However, if you can't use one of the hardware UART channels then maybe you need to start thinking outside the box. And by "the box" I mean "the ESP8266".

Maybe the ESP8266 isn't for you. It's a great chip for making a WiFi interface, but it's not good for much else. It simply lacks the internal peripherals to be useful. Maybe upgrading to the ESP32 would be a good option for you (that's the ESP8266's big brother). It has a far more feature-rich peripheral set.

Also don't be afraid of using more than one microcontroller. If the ESP8266 doesn't have the interfacing you need then add another MCU to it which does have the interfacing you need - and then get them to communicate using whatever interface you *do* have available (I2S, SPI, etc). Yes, it means more programming and a more complex project, but learning such things will certainly unlock more doors for future projects.
> 2 votes

---
Tags: esp8266, arduino-ide, wifi, softwareserial
---


# Question
Title: Connect Arduino to MySQL database online problem
I'm trying to connect Arduino with MySQL database on my online server.

I manage my project to work on WampServer locally on localhost, but when I try to move everything online I have problem... on the serial monitor I get the message that the server is connected and my sensor readings, but I can't put them in to my database on my online sever.

Here is my code:

---

**dbconnect.php**

```
<?php
$MyUsername = "*******";  // enter your username for mysql
$MyPassword = "*******%";  // enter your password for mysql
$MyHostname = "*************";      // this is usually "localhost" unless your database resides on a different server

$dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
$selected = mysql_select_db("tanjamayaarduino",$dbh);
?>

```

---

**add\_data.php**

```
<?php
    // Connect to MySQL
    include("dbconnect.php");

    // Prepare the SQL statement
    $SQL = "INSERT INTO tanjamayaarduino.temperature (sensor ,celsius, light, moisture1, moisture2) VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."','".$_GET["light"]."','".$_GET["moisture1"]."','".$_GET["moisture2"]."')";

    // Execute SQL statement
    mysql_query($SQL);

    // Go to the review_data.php (optional)
    header("Location: review_data.php");
?>

```

---

**Arduino code**

```
#include<Ethernet.h>
#include<SPI.h>
const int temperaturePin = A3;    //LM35 Temperature sensor
const int lightPin = A2;          //LDR photoresistor sensor
const int moisture1Pin = A4;          //Moisture1 sensor
const int moisture2Pin = A5;          //Moisture2 sensor

// **** ETHERNET SETTING ****
// Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
// Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x3A, 0xDC };
// For the rest we use DHCP (IP address and such)
IPAddress ip(192, 168, 2, 121);
EthernetClient client;
//IPAddress server(192, 168, 2, 100); // IP Adres (or name) of server to dump data to
// IP Adres (or name) of server to dump data to  (godaddy baza server 37.148.204.140) (User: tanjamayaarduino@188.121.42.33) (goddady glavna adresa na hostingot 188.121.46.1)
//IPAddress server(188, 121, 46, 1);
char server[] = "188.121.46.1";

int  interval = 5000; // Wait between dumps

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

  Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
  Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
  Serial.print("IP Address        : ");
  Serial.println(Ethernet.localIP());
  Serial.print("Subnet Mask       : ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("Default Gateway IP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("DNS Server IP     : ");
  Serial.println(Ethernet.dnsServerIP());
}

void loop() {
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)==1) {
    float tem = getTemp();
    Serial.println( tem );
    float lig = getLight();
    Serial.println( lig );
    float mois1 = getMoisture1();
    Serial.println( mois1 );
    float mois2 = getMoisture2();
    Serial.println( mois2 );

    Serial.println("-> Connected");
    if (client.connected()) {
      // Make a HTTP request:
      client.print( "GET /advertacs/test/arproekt/add_data.php?");
      Serial.println("-> add_data");
      client.print("serial=");
      client.print( "TempSensor" );
      client.print("&&");
      client.print("temperature=");
      client.print( tem);
      Serial.println("-> add_temp");
      client.print("&&");
      client.print("light=");
      client.print( lig);
      Serial.println("-> add_light");
      client.print("&&");
      client.print("moisture1=");
      client.print( mois1);
      Serial.println("-> add_mois1");
      client.print("&&");
      client.print("moisture2=");
      client.print( mois2);
      Serial.println("-> add_moi2");

      client.println( " HTTP/1.1");
      client.println( "Host:" );
      client.println(server);
      client.println( "Connection: close" );
      client.println();
      client.println();
      client.stop();
    }
  }
  else {
    // you didn't get a connection to the server:
    Serial.println("--> connection failed/n");
  }

  delay(interval);
}
float getTemp() {
  float temperatureC = (5.0 * analogRead(temperaturePin) * 100.0) / 1024; //converting from a 0 to 1023 digital range to 0 to 5 volts (each 1 reading equals ~ 5 millivolts
  return temperatureC;
}
float getLight() {
  float light;
  light = analogRead(lightPin) ;
  return light;
}

float getMoisture1() {
  float moisture1;
  moisture1 = analogRead(moisture1Pin) ;
  return moisture1;
}
float getMoisture2() {
  float moisture2;
  moisture2 = analogRead(moisture2Pin) ;
  return moisture2;
}

```

# Answer
There are two basic things wrong with your code. First is the formatting of your headers - you have mistakenly used `client.println` for sending the first part of the Host: header, so it becomes split onto two lines:

```
client.println( "Host:" );
client.println(server);

```

Secondly you are using the server's IP address instead of the actual host name in the Host: header. That means the server can't work out which website you are wanting to talk to and just rejects your request.

You need to have something more like:

```
client.print("Host: ");
client.println(servername);

```

where `servername` is the *name* of the server (`www.website.com`) *not* the IP address. You can put it all in one line if you don't ever want to change the website name, since it makes it slightly harder to find and edit:

```
client.println("Host: www.mywebsite.com");

```
> 2 votes

# Answer
First of all, are you now connected to SQL? If so, and it still doesn't work... Have you tried to escape your `"`, so instead of:

```
$SQL = "... VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."',...')";

```

doing something like:

```
$SQL = "... VALUES ('\".$_GET[\"serial\"].\"', '\".$_GET[\"temperature\"].\"',...')";

```

If it still doesn't work, once you send to SQL with your code, print on screen what you are effectively sending, copy it with your mouse, paste it in your phpadmin-sql console and execute it. There you should see any helpful tips on what is really happening. Hope this helps!
> 1 votes

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


# Question
Title: I keep gettint the error expected construcotr,destructor or type conversion before = token
```
#include <dht.h>
dht DHT;
#define DHT11_PIN 2     // what pin we're connected to  // DHT 11

String TextForSms ;
String humidity = " Humidity: %";
String temperature = "   Temperature";
String sign = " *C";
char fromc;

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

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  float h = DHT.humidity;
  float t = DHT.temperature;
  delay(2000);
  }

  TextForSms = TextForSms + t + "," + h + ",";
Serial.println(TextForSms);
     TextForSms = "";
   delay(1000);

```

# Answer
> 0 votes
This whole section:

```
  TextForSms = TextForSms + t + "," + h + ",";
Serial.println(TextForSms);
     TextForSms = "";
   delay(1000);

```

is outside a block. Code must be inside a block.

There are strict rules governing what can go where in a C or C++ program. I suggest you learn them.

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: Does direct port access interfere with PWM?
I think I've scoured the SE for questions about PWM, and fast digitalWrite etc, but I didn't see this point addressed.

I need to use direct writes to some digital pins. Some of the pins on the port are using analogWrite/PWM, though not the pins I'm accessing digitally.

In the digitalWrite function the Arduino core checks to see if PWM is in use and disables it if a digital write is attempted. Since the pins here are isolated -- no digital writes to PWM pins -- is this a needed step?

The reason I ask is that when accessing a port directly, as in `PORTD |= (PORTD & mask) | somebit`, you are in fact writing to the pins being used for PWM, you just aren't writing changed bits.

Am I overthinking this? Is it 'PWM-safe' to use direct port outputs on the neighbor pins?

# Answer
> 2 votes
A timer interrupt will be periodically toggling the PWM bit and might do so between your port read and port write.

The easy solution is to turn off interrupts during the read/modify/write portion of your port update sequence. This could cause a stretched PWM cycle. If you don't turn it off, you'd just glitch the PWM - creating an extra, short cycle. Which one is worse for your PWM recipient?

A better solution might be to to watch the port for the PWM bit to change, then jump in right afterward and make your port update. You could do his in either a blocking or a non-blocking manner.

Update:

> Watching the PWM bits seems as if it would be fairly slow, which somewhat defeats the purpose of the direct port writes.

Yes, it's less than ideal. There's a tradeoff here. Can your PWM consumer tolerate the potential occasional glitch, instead?

To be complete, there are a number of motivations to use direct I/O:

* Smaller code;
* Less I/O skew with multiple I/Os, or zero skew if the I/Os are in the same port;
* Less execution time on a time-critical path;
* Precise output timing;

among others. Those software solutions won't help much in any of those cases.

Can you reassign your output to another pin on a different port, avoiding the whole problem? That might be better than any of the "solutions". Adding hardware might accomplish the same thing - perhaps moving just the PWM to an ATtiny, for example.

Update 2:

> This seems so baked into the structure of the Arduino... does digitalWrite() itself actually overcome this?

It "addresses" it - overcomes it? As is so often the case, "that depends".

Here is the the source-code to digitalWrite() from: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino /wiring\_digital.c (on a Mac; the top-level folder or two will be different on Windows):

```
void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

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

    SREG = oldSREG;
}

```

Notice that the interrupts are saved and restored around the read/modify/write of the port register. So digitalWrite() already addresses the possibility. This method will stretch one phase of an occasional PWM pulse by a few microseconds.

Alternatively, ignoring the possibility of a collision and having one occur, seems more severe: the pulse could be begun or ended prematurely. This occurrence will take longer - the rest of the disturbed phase - to get back in sync.

So the criterion for how to manage x becomes "Which way has the lesser - or more tolerable - consequence for your PWM consumer?"

---
Tags: arduino-uno, pwm, digitalwrite
---


# Question
Title: Why can't I print boolean variable values (0 and 1) through println function?
source code :

```
int buttonPin = 8;
boolean buttonState = 0;

void setup()
{
   Serial.begin(9600);
   pinMode (buttonPin, INPUT);
}

void loop()
{
   buttonState = digitalRead(buttonPin);
   Serial.println(buttonState);
   delay(500);
}

```

But when, instead of boolean I specify an int data type for buttonState variable it produces the result I want i.e. 1 when pressed and 0 when not pressed. Is it related to the way these variables when stated with different data types give different values to the println() function to convert them into ASCII values?

# Answer
First, you are not supposed to use `boolean` with digitalRead.

The function prototype in Arduino.h is:

```
int digitalRead(uint8_t);

```

Thus, the *correct* data type for `buttonState` in your code is `int`. Then your other problem goes away. What I am guessing is happening is that the version of the IDE you are using does not have an overloaded function for `Serial.println` that takes a `boolean` argument, and the compiler is casting it to `byte`, in which case it would print as 0x00 (LOW) or 0x01 (HIGH) which are not printable characters.

Unfortunately the documentation for digitalRead on the Arduino site does not mention the datatype, it just mentions that it returns `HIGH` or `LOW` which isn't very helpful to help you work out what data type to use. BTW, neither of those values are, per se, booleans. If they had said it returns `true` or `false` you might reasonably put the result into a boolean field.

I have tried to get the Arduino developers to improve the documentation in this respect, something they have declined to do. I raised the issue almost 4 years ago, and no-one is even assigned to this particular task.

---

If you insist on using the boolean type, then a reasonable way of printing would be:

```
Serial.println(buttonState ? "HIGH" : "LOW");

```

---

## In response to some comments ...

> Works fine for me. – Majenko

...

> boolean is a typedef for bool. bool gets promoted to int, not byte - Majenko

What you mean by "is a typedef for bool" is *in some (later) versions of the IDE*.

Looking at, for example, Arduino pre-release version 0023 I see in the file wiring.h:

```
typedef uint8_t boolean;
typedef uint8_t byte;

```

So you can clearly see that boolean and byte are the same, and therefore that using boolean would be treated as byte. Now if you look at the Print class in that release:

```
class Print
{
  private:
    void printNumber(unsigned long, uint8_t);
    void printFloat(double, uint8_t);
  public:
    virtual void write(uint8_t) = 0;
    virtual void write(const char *str);
    virtual void write(const uint8_t *buffer, size_t size);

    void print(const String &);
    void print(const char[]);
    void print(char, int = BYTE);
    void print(unsigned char, int = BYTE);
    void print(int, int = DEC);
    void print(unsigned int, int = DEC);
    void print(long, int = DEC);
    void print(unsigned long, int = DEC);
    void print(double, int = 2);

    void println(const String &s);
    void println(const char[]);
    void println(char, int = BYTE);
    void println(unsigned char, int = BYTE);
    void println(int, int = DEC);
    void println(unsigned int, int = DEC);
    void println(long, int = DEC);
    void println(unsigned long, int = DEC);
    void println(double, int = 2);
    void println(void);
};

```

So you can see that the overload for `print` and `println` treats an unsigned char (effectively `uint8_t`) to be printed with `BYTE` default treatment and not `DEC` treatment.

`BYTE` is declared:

```
#define BYTE 0

```

And the writing is done thus:

```
void Print::print(unsigned long n, int base)
{
  if (base == 0) write(n);
  else printNumber(n, base);
}

```

What this boils down to is that both `byte` and `boolean` will be written as "binary" bytes, not converted into decimal.

As Majenko says, things are different today, and `boolean` is now equivalent to `bool` which is promoted to `int`.

---

ElectroManiac did not respond to a question about what version of the IDE s/he is using, however my point is that *for some versions of the IDE* my explanation is true.

---

> Oh, and assigning the return of digitalRead to a bool is perfectly valid ...

Yes, for `bool`, but the question was about `boolean`. Whilst we know, by reading the code and reading the documentation, that digitalRead will return a 0 or 1, the fact that the return type is `int` means that the compiler can potentially see that you are stuffing a 16-bit return value into a 8-bit variable which will possibly lead to data truncation.

I must admit I don't get a warning when compiling with the Arduino IDE, however there is certainly the potential for truncation. A test program written in C++ and compiled with the `-Wconversion` flag gives a suitable warning:

```
warning: conversion to ‘uint8_t {aka unsigned char}’ from ‘int’ may alter its value [-Wconversion]

```

(There is no warning if you are placing the result into `bool`, however that is not the version of the IDE that the OP is using).
> 3 votes

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


# Question
Title: Why wifiManager.setTimeout(60) is not working?
in this code I am using wifiManager.setTimeout(60); so that when it fails to connect to the wifi it should restart. However, wifiManager.setTimeout(60) is not working at all. It get stuck and display these lines :

\*WM: AutoConnect

\*WM: Connecting as wifi client...

\*WM: Using last saved values, should be faster

It never displays this :

"failed to connect and hit timeout"

which means wifiManager.setTimeout(60) is not working . Below is the code:

```
  #include <ESP8266WiFi.h>

 //needed for library
 #include <DNSServer.h>
 #include <ESP8266WebServer.h>
 #include <WiFiManager.h>

  void setup() {
       // put your setup code here, to run once:
       Serial.begin(115200);

      //WiFiManager
       //Local intialization. Once its business is done, there is no need to
       //keep it around
        WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

     //sets timeout until configuration portal gets turned off
     //useful to make it all retry or go to sleep
      //in seconds

      wifiManager.setTimeout(60);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
 //here  "AutoConnectAP"
 //and goes into a blocking loop awaiting configuration

  if(!wifiManager.autoConnect("AutoConnectAP")) {
     Serial.println("failed to connect and hit timeout");
     delay(3000);
     //reset and try again, or maybe put it to deep sleep
     //ESP.reset();
     ESP.restart();
     //ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(5000);
   }

   //if you get here you have connected to the WiFi
   Serial.println("connected...yeey :)");

    ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(3000);

 }

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

  }

```

I am using ESP8266 thing dev board. Can anyone please tell me what is wrong and how to resolve the issue ? Thank You!!

# Answer
Try using setConfigPortalTimeout(60) instead of setTimeout(60)

Because it has been updated in version 0.10 of WiFiManager library. see : https://github.com/tzapu/WiFiManager#010
> -1 votes

---
Tags: esp8266
---


# Question
Title: CPU information on Arduino Serial Monitor
how to show the

CPU temperature, CPU usage (percentage) and the memory usage(percentage)

in Arduino Serial Monitor.

# Answer
**CPU temperature**

Some Arduino boards have a microcontroller with a temperature sensor inside. For example the Arduino Uno can measure the temperature inside the microcontroller.

As far as I know, no one uses it. It is not accurate and a microcontroller should not get hot in the first place. The microcontroller or processor on the Arduino board can run at 100% load and it does not get hot.
The internal temperature sensor is not accurate enough to measure the ambient temperature.
The internal temperature is therefore (almost) useless.

See this page on the Arduino Playground and this forum thread for the internal temperature sensor.

**CPU usage**

There is no CPU usage. There is no idle task. The microcontroller or processor usually runs all the time at full speed.

It is possible to determine how long the Arduino board stays in delays (via the yield function).
With a external RTC clock it is possible to determine how long the Arduino board stays in sleep mode (some battery powered Arduino projects use the sleep mode).
However, those are very specific things. Perhaps a project requires to measure them, but there is no common use for them.

A good sketch is not supposed to do nothing, it is supposed to check all the inputs and check millis-timers and act if needed. The Arduino loop() function is supposed to run as often as possible to make the Arduino run fast and smooth.

**Memory usage**

The memory usage is something to be aware of when writing a sketch. An Arduino board has much less memory than a typical computer.

It is possible to determine the unused memory between the stack and the heap.
The function at the bottom of this page can be used to determine the amount of free memory.

I have also seen code to measure the high water mark (memory that is never used at all), but none of them work for all Arduino boards and the code is not reliable.
> 6 votes

---
Tags: serial, programming, memory
---


title: Sparkfun CAN Shield BMW OBD2 reading

text:
# Question
Title: Sparkfun CAN Shield BMW OBD2 reading
I bought the CAN-Shield from Sparkfun https://www.sparkfun.com/products/13262 and I also got the Uno from Sparkfun just to be sure everything works fine.

Some info about my car:

* BMW E91 2006
* OBD2 is available
* KWP 2000 and other lines are available like the ones with the same baud rates from the demo

I tried the SparkFun\_CAN\_Demo which is available on their website and GitHub.

My output is that CAN init is successful but I don´t know if that´s true... If I try to read the RPM, for example, I get a buffer with a size of 1 -\> " ".

My questions are:

* Did I something wrong with the MCP2515 how do I know if it´s dead?
* Does anybody know if the demo is working properly or not?
* What´s the right way to get data from an BMW with OBD2?

# Answer
First off I cannot say much about the library that you are using I have't tried that one yet as for the shield i have some of those and there are two versions of them check your PIN outs on them the cs pin is either on d9 or d10

the other thing is make sure that you are in the right operation mode ie. Normal and maybe give this library a try I have had lots of success with this one: https://github.com/coryjfowler/MCP\_CAN\_lib

as for the baud rate I have tried all types of ways of getting the right baud rate for certain vehicles but the best remains start small and step it up till you get the one that gives you reply

make sure that you ground the Arduino to the car as well it works without that but sometimes it does nothing If you are using the OBDII cable it should be grounded by default
> 1 votes

---
Tags: arduino-uno, can-bus
---