# Question
Title: Digispark ATtiny 85 erases flash after power loss
I have some issues with my Digispark ATtiny85 board. If I upload the blink sketch for example the LED starts blinking and everything looks fine. But as soon as I unplug the Digispark from the USB port and plug it back in nothing happens. I know that the programm starts with a delay of 5 seconds so programming via USB becomes possible, but still nothing. Its seems like the flash-memory (where the programm is stored) of the ATtiny 85 is empty.

Here is the example blink sketch:

```
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(0, OUTPUT); //LED on Model B
  pinMode(1, OUTPUT); //LED on Model A
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(0, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(1, HIGH);
  delay(1000);               // wait for a second
  digitalWrite(0, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(1, LOW);
  delay(1000);               // wait for a second
}

```

I also tried uploading the sketch from a Laptop running on Windows but without success.

I am using Linux Mint and Arduino IDE 1.8.10.

Since I am new to Microcontrollers, I would be grateful for explainations, tipps or useful links. Thank you!

# Answer
> 2 votes
I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.

EDIT:

As expected flashing the micronucleus bootloader using USBasp solved the problem on both of the boards. I've used burn-o-mat as the arduino was not seeing my programmer.

Just download the firmware from github (I've used this: https://github.com/f4goh/micronucleus/archive/master.zip )

and connect like so (here the guy is using arduino uno, doesn't matter): https://hamprojects.wordpress.com/2018/12/27/digispark-microcontrollers-implementation/

---
Tags: arduino-ide, attiny85, digispark
---


# Question
Title: MacOS 10.15.1 Catalina CU port always busy, and TTY port not selectable
I am trying to use an FTDI breakout board to connect to my custom made Arduino compatible board. I am using a new 16 inch macbook pro with USB-c ports, so I am using a dongle, in case that could be the problem.

Every time I try and upload a sketch I get the error: "can't open device "/dev/cu.usbserial-D306P6WW": Resource busy". When I check the /dev/ folder, both "/dev/cu.usbserial-D306P6WW" and "/dev/tty.usbserial-D306P6WW" show up, however in Arduino IDE I can only choose the "/dev/cu.usbserial-D306P6WW" option. I have installed FTDI VCP drivers, CH340 drivers and all kinds of other drivers to try and fix this issue. I have restarted countless times, and I have used a multitude of commands to check for programs hogging the usb port, but there is never a program. Plugging a harddrive into the same port causes no problems, so the port can't really be the problem. I am using a "FTDI FT231XS" board from Sparkfun.

# Answer
> 1 votes
Nevermind, updating my MacOS version to 10.15.3 magically fixed the problem...

---
Tags: arduino-ide, ftdi
---


# Question
Title: Arduino ESP8266 - stack ERROR - ESPExceptionDecoder to debug - need help to find ERROR
i have one project that can ready compiled. The function is break on the hardware an i need help to finde the error. I am a beginner and ask for help. How can I narrow the error down?

Sketch:

Platform

* Hardware: AZDelivery NodeMCU Lua Amica Modul V2 ESP8266 ESP-12E
* Core Version: latest git
* Development Env: Arduino IDE
* Operating System: Windows

Settings in IDE

* Module: Nodemcu v1.0
* Flash Size: 4MB
* Flash Frequency: 40Mhz
* CPU Frequency: 80Mhz
* Upload Speed: 115200

Problem Description

```
15:54:11.662 -> Fatal exception 3(LoadStoreErrorCause):
15:54:11.662 -> epc1=0x4000e041, epc2=0x00000000, epc3=0x00000000, excvaddr=0x4024bcc2, depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> Exception (3):
15:54:11.701 -> epc1=0x4000e041 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4024bcc2 depc=0x00000000
15:54:11.701 ->
15:54:11.701 -> >>>stack>>>
15:54:11.701 ->
15:54:11.701 -> ctx: cont
15:54:11.701 -> sp: 3ffffce0 end: 3fffffc0 offset: 01a0
15:54:11.701 -> 3ffffe80:  00000000 00000019 4024bcaa 00000000
15:54:11.701 -> 3ffffe90:  00000001 3fff16a4 00000000 000001ff
15:54:11.701 -> 3ffffea0:  00000000 00000019 401003fc 0001687b
15:54:11.701 -> 3ffffeb0:  00000000 00000000 00000001 4024bcaa
15:54:11.701 -> 3ffffec0:  00000000 00000019 3fff1134 4020ef28
15:54:11.701 -> 3ffffed0:  ffffffff 3fffc6fc 00000001 4024bcaa
15:54:11.741 -> 3ffffee0:  00000001 00000000 3fff1134 4020efc2
15:54:11.741 -> 3ffffef0:  00000019 00000000 3fff1134 4020f09d
15:54:11.741 -> 3fffff00:  40214e08 00000000 00001388 00000057
15:54:11.741 -> 3fffff10:  4020f060 3ffef254 4024bcaa 4021104d
15:54:11.741 -> 3fffff20:  3ffef10c 3ffef10c 3ffef254 40211275
15:54:11.741 -> 3fffff30:  007a1200 3ffef10c 3ffeeec0 402019b9
15:54:11.741 -> 3fffff40:  00000000 00000000 00000001 40100304
15:54:11.741 -> 3fffff50:  3ffef10c 00000000 3fff1134 4020f130
15:54:11.741 -> 3fffff60:  3ffef10c 3ffef254 0000000d 3ffef115
15:54:11.781 -> 3fffff70:  3ffef10c 3ffef254 3ffeeec0 402027dd
15:54:11.781 -> 3fffff80:  3fffdad0 00000000 3ffef728 3ffef768
15:54:11.781 -> 3fffff90:  3fffdad0 00000000 3ffef728 40202849
15:54:11.781 -> 3fffffa0:  3fffdad0 00000000 3ffef728 40212b68
15:54:11.781 -> 3fffffb0:  feefeffe feefeffe 3ffe8500 40101059
15:54:11.781 -> <<<stack<<<
15:54:11.781 ->
15:54:11.781 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,6)
15:54:11.781 ->
15:54:11.781 -> load 0x4010f000, len 1392, room 16
15:54:11.821 -> tail 0
15:54:11.821 -> chksum 0xd0
15:54:11.821 -> csum 0xd0
15:54:11.821 -> v3d128e5c
15:54:11.821 -> ~ld
15:54:11.861 ->

```

ESPExceptionDecoder Debug

```
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
PC: 0x4000e041
EXCVADDR: 0x4024bcc2

Decoding stack results
0x401003fc: millis() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_wiring.cpp line 188
0x4020ef28: ClientContext::_write_some() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 514
0x4020efc2: ClientContext::_write_from_source(DataSource*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 450
0x4020f09d: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
0x4020f060: WiFiClient::write(unsigned char const*, unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src\WiFiClient.cpp line 220
0x4021104d: Print::write(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266/Print.h line 60
0x40211275: Print::println(char const*) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\Print.cpp line 129
0x402019b9: commands::HandleShortCommand() at D:\Temp\arduino_build_652018\sketch/commands.h line 363
0x40100304: ets_post(uint8, ETSSignal, ETSParam) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 160
0x4020f130: ClientContext::_consume(unsigned int) at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFi\src/include/ClientContext.h line 557
0x402027dd: serialEvent() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 591
0x40202849: loop() at E:\Programme\Rasberry - Projekt\Projekt_FHEM\_Arduino\Firmware_SIGNALDUINO\SIGNALDuino-dev-r332_cc1101_200113\___funktionstuechtig_ESP\SIGNALESP/SIGNALESP.ino line 470
0x40212b68: loop_wrapper() at D:\Eigene Dateien\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\cores\esp8266\core_esp8266_main.cpp line 180

```

# Answer
> 1 votes
The problem is that code like

```
            MSG_PRINTLN(TXT_UNSUPPORTED1);

```

with

```
#define MSG_PRINTLN(...) { MSG_PRINTER.println(__VA_ARGS__); }

```

and

```
static const char TXT_UNSUPPORTED1[]        PROGMEM = "Unsupported short command";

```

On the ESP8266 calls the `println()` function which accepts a `char*`, expected from RAM. However since the string here was put into flash and not RAM, this function will crash upon execution.

The fix is to use the `__FlashStringHelper` class which calls the correct `println()` overload and doesn't crash.

See PR https://github.com/HomeAutoUser/ERROR\_search/pull/1 and https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html

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


title: Sound sensor only detect peaks

text:
# Question
Title: Sound sensor only detect peaks
I'm using this SparkFun Sound Sensor in my project for a simple ambient sound meter.

I'm just trying to monitor the raw analog envelope output for the moment.

My problem is that the output only changes with peak sounds, like a clap in my hands for example. But when the ambient sound is louder, people talking or loud music, the output doesn't change.

# Answer
> 1 votes
It seems you have to increase the gain, see inside the document

Sound dectector hookup guide

The following fragment:

Also take into account it needs between 3.5 and 5.5 V, while 5 V is ideal (see Quick start at the beginning of the same document.

---
Tags: arduino-nano, sound
---


title: Nodemcu powering with 5.2v and 2A?

text:
# Question
Title: Nodemcu powering with 5.2v and 2A?
I bought a this voltage regulator . DC-DC 5v 8A voltage regulator. ıts supported 8-35V input voltage . And i want to use this with 12v power supply. But i searched on the internet . Nodemcu max amp is 800mA. This device can provide 2A per usb output if i will plug the nodemcu with usb cable this what happen ? Does it burn ? How can i drop the amps ? i want to use other 3 usb output with other devices sensors and screen .

# Answer
Generally, we specify DC power supplies as constant voltage sources. In order to do this, power supplies deliver more or less current as demanded by the load in an attempt to keep the voltage constant regardless of the load.

When a constant voltage DC power supply specifies a maximum current, it is saying the power supply can only maintain the specified voltage while the current demand is less than the specified maximum current.

To be clear, unless you need a constant current power supply, a power supply should be picked based on the required constant voltage. And the capacity of that power supply, usually measured in Amps, should exceed the maximum combined current demand of all connected devices (loads).
> 1 votes

# Answer
It will not burn. The nodeMCU will only "pull" the amount of current (amps) it needs.
> 0 votes

---
Tags: esp8266, power, nodemcu, ch340
---


# Question
Title: How can I power an Arduino Nano with a LiPo battery, preferably 3.7v
I am a newbie to Arduino, so please bear with me. I am trying to figure out how to power an Arduino Nano with a LiPo battery. I want to use a 3.7v if possible, as my project needs to be lightweight. There are two possibilities I know *could* work:

-Taking a USB to Mini-B USB, cutting off the normal USB end, and soldering a connector (based on the battery I use) to that end. I would then plug the Mini-B USB into the Nano, giving it power.

-Using the 5v and Ground pins.

I would prefer to use the USB cable solution, however the 5v/Ground or any other solution is perfectly usable.

Also, would 3.7v be enough to power the Nano, two Infrared LEDS (Launch and Receiver), and a 7-segment LED display. I also have a button. Thanks, saddlepiggy!

# Answer
> 5 votes
In short: not reliably. The Arduino Nano expects either a 5V regulated supply or a 6-20V unregulated supply (https://www.arduino.cc/en/Main/ArduinoBoardNano). Even if you plugged it in and it worked initially, the battery voltage will decrease gradually as it discharges (LiPo cells can drop as low as ~3.2V), making it more and more unreliable. You'd technically be overclocking the processor, since the Nano runs at 16 MHz and the datasheet for the microcontroller requires at least a 4.5V supply to run above 10 MHz.

A safer solution would be to use a 2S LiPo battery (~7.4V), which would be plenty to supply the regulated input pin (VIN). On the other hand, if you're set on using a 3.7V LiPo, other Arduino boards (like certain versions of the Pro Mini) run at 3.3V.

As for your second question, 3.7V is plenty to power a few LEDs so long as they are connected in parallel (or to separate pins). The only thing you need to be aware of is current draw--more current means shorter battery life. For example, if your circuit draws 100 mA total from the battery, and your battery is specified at 500 mAh, you will get approximately (500 / 100) = 5 hours of battery life.

# Answer
> 5 votes
Late to the convo but quick comment in case anyone else reads this thread still. Arduino uses a linear regulator on Vin. In that case the “extra” voltage gets wasted. You’d get a much more efficient battery use by using a buck or boost circuit to provide it the correct 5V on the 5V pin (or usb) rather than feeding a 2S LiPo into Vin. It would work both ways but you’d get noticeably longer run time with a switching power converter.

---
Tags: power, arduino-nano
---


# Question
Title: Error while updating ThingSpeak using SIM808
im trying to update ThingSpeak from a SIM808 but I'm getting a network error. Please check below and let me know if there is anything wrong in my methodology.

I'm using terminal.exe to send commands via RS232.

```
AT
OK
AT+CREG?
+CREG: 0,5 //connected in roaming
AT+SAPBR=3,1,"Contype","GPRS"
OK
AT+SAPBR=3,1,"APN","www" //VODAFONE INDIA "www" is APN (as per the operator)
OK
AT+SAPBR=3,1,"USER","" //blank (as per the operator)
OK
AT+SAPBR=3,1,"PWD","" //blank  (as per the operator)
AT+SAPBR=1,1
OK
AT+HTTPINIT
OK
AT+HTTPPARA="CID","1"
OK
AT+HTTPARA="URL","https://api.thingspeak.com/update?api_key=MY_KEY&field1=VALUE"
OK
AT+HTTPACTION=0
+HTTPACTION: 0,603,0

```

Note: while I'm typing in the browser url box, https://api.thingspeak.com/update?api\_key=MY\_KEY&field1=VALUE, I can update my field. I can make calls, send SMS. I have an internet pack.

Please help.

# Answer
It worked with changing AT+HTTPARA="URL","http://api.thingspeak.com/update?api\_key=MY\_KEY&field1=VALUE" (from https:// to http://)
> 1 votes

# Answer
You have to send this command: AT+HTTPSSL=1
> 0 votes

---
Tags: shields, gsm, rs232
---


# Question
Title: Newbie Using Brown Out detector on Arduino Due for saving variables to eeprom?
Hi I'm a newbie and working on a project with Arduino Due(Atmel3X8E).I want to try and save the important variables to the eeprom during a power outage,using the brown out detector.Is it possible to do this? Thank you.

# Answer
Not a good idea - if the power goes down when you writing to EEPROM, your EEPROM data will be corrupted. The brown-out detector goal is to shut off the MCU, before it goes mad due to low power voltage.

The solution of this issue - use some huge capacitors (about 4700 mkF) - like a small UPS device.

When external power goes off, you well get enough time and power to store your bytes safely.

**How it works**

When +5V is okay, the capacitor is charged on, and the light diode (pins 1-2) inside of PC817 is on, so the transistor part of PC817 (pins 3-4) is open, and POWER\_GOOD signal is `LOW`.

When power goes off, capacitor starts to discharge and give power to the right part of scheme. The Schottky diode acts as a valve, that stops the power to go to the left part. The another diode, which is inside of PC817 now goes off, and the transistor goes to close - POWER\_GOOD signal goes to `HIGH` level and your program may start save data to EEPROM.

**Why the optocoupler?**

We need to investigate about internal AVR chip circuit. It has couple of diodes on each pin:

So, when we connect PIN directly to power, +5V, and connect AVR's VCC to +5V over the Schottky diode, we've got two diodes in parallel! This situation is very bad, because they may compete, which will conduct the current - and, in some cases, internal (which is weak), chip diode wins. All controller power current start flow thru this weak diode, heats it up and toasts the chip! Not very good.
> 10 votes

# Answer
An alternative solution to this is to use an "EERAM". This is an EEPROM with an SRAM buffer in front of it. A large capacitor is used to provide power while the contents of the SRAM are stored in the EEPROM.

It sounds complex, but it's simple since they are made as a dedicated chip. One good example is the 47C16 from Microchip. The EEPROM backup is completely transparent to the user, and you can use it just like an I2C connected SRAM chip (so no worries about wearing out the EEPROM by writing too often).

It's a chip I love so much that I made a breakout of the 3.3V version 47L16 (since I work mainly with 3.3V devices), and a library to support it.
> 2 votes

# Answer
I think the gbg's circuit will fail in many situations. It will cause interrupt only when the power source voltage is quite low. If there is no considerable load before the diode filtering caps of the power source will likely hold enough charge and the "5V" will be falling slowly. Arduino will drain the the backup capacitor before it gets "power bad" interrupt.

Since OP is using 12V power supply a simple brownout detector giving warning when this source drops under some reasonable value (i.e. 9V) is the best way. A Zener diode and transistor (or the optocoupler) should be enough because the value of the threshold is not critical.
> 2 votes

# Answer
I use FRAM for this. It's always write a byte if it was received, much faster and safety. Additionally you can use chain like approach to save data blocks in EEPROM for controlling of the data integrity. Try to use mosfet instead of diode and optocoupler when it powered from battery.
> 0 votes

---
Tags: arduino-due
---


title: Nextion Dual State Button

text:
# Question
Title: Nextion Dual State Button
I am having an issue with my Nextion display. I have uploaded the following code via Arduino IDE to my Arduino MEGA 2560.

My Nextion Editor shows the button as `ID:9` on `page0` named `floor`. I am not entirely sure if the code below is correct. I had one issue where the upload from the laptop to the Mega wouldn't finish, but I managed to bypass that issue by disconnecting the Nextion and swapping RX and TX cables from Nextion while the upload was in progress. Not sure how else I would fix that issue? (If anyone has any ideas haha)

All that is meant to happen is when the dual button state is changed, the onboard `LED_BUILTIN` is set to `HIGH` and if in its second state, is set to `LOW`.

# CODE

```
#include "Nextion.h"

NexDSButton bt0 = NexDSButton(0, 9, "floor");

int ledPin = LED_BUILTIN;

char buffer[100] = {0};

NexTouch *nex_listen_list[] =
{
    &bt0,
    NULL
};

void bt0PopCallback(void *ptr)
{
    uint32_t dual_state;
    NexDSButton *btn = (NexDSButton *)ptr;
    dbSerialPrintln("b0PopCallback");
    dbSerialPrint("ptr=");
    dbSerialPrintln((uint32_t)ptr);
    memset(buffer, 0, sizeof(buffer));

    if(dual_state)
    {
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }
}

void setup(void)
{
    nexInit();

    bt0.attachPop(bt0PopCallback, &bt0);

    dbSerialPrintln("setup done");
    pinMode(ledPin, OUTPUT);
}

void loop(void)
{
    nexLoop(nex_listen_list);
}

```

My issue is that the MEGA is identifying the touch event (as the TX LED on the MEGA flashes) however it is not turning on the MEGA's onboard built-in LED.

Any help would be greatly appreciated!

# Answer
This is part of the code I have been using for an extraction fan, The button text is tested and if the button matches the command the fan is turned on or off and the button text is changed accordingly. Hope this helps.

```
void b19PopCallback(void *ptr) //Extraction Fan
{
  NexButton *btn = (NexButton *)ptr;
  memset(buffer, 0, sizeof(buffer));
  btn->getText(buffer, sizeof(buffer));

  if (strcmp(buffer, "ON"))
  {
    //COMES BACK AS A FALSE (0) IF BOTH STRINGS MATCH
    digitalWrite(b_motor, LOW);
    strcpy(buffer, "ON");
    btn->setText(buffer);
  }

  else
  {
    digitalWrite(b_motor, HIGH);
    strcpy(buffer, "OFF");
    btn->setText(buffer);
  }

}

```
> 1 votes

# Answer
You can try int ledPin=13 instead of led\_builtin . Led builtin connected 13 pin. Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13 . Try this one.

```
#include "Nextion.h"
int ledPin = 13;
NexDSButton bt0 = NexDSButton(0, 1, "bt0");
uint32_t dual_state=0;

void setup(){
nexInit();
pinMode(ledPin, OUTPUT);
}
void loop(){
bt0.getValue(&dual_state);
delay(200);

if(dual_state==1) //When pressed dual state button dual_state =1
  {
    digitalWrite(ledPin, HIGH);
  }
  else if(dual_state==0)
  {
    digitalWrite(ledPin,LOW );
  }

}

```
> 1 votes

---
Tags: arduino-mega, arduino-ide, lcd, tft
---


title: HM-10 doesn't responde after RENEW

text:
# Question
Title: HM-10 doesn't responde after RENEW
Today I finally got two HM-10 modules. I did flash firmware using this tutorial. It worked until I didn't send `AT+RENEW` command. Now, LED blinks, I see device in BT terminal(Android phone) but I can't connect to it. Terminal says `Connection failed: write descriptor failed`. I tried sending commands over COM port from PC, but it doesn't responde. Also I connected pin 11 to GND, problem is still here. Strange thing - After firmware flash, `AT+HELP` doesn't exist, while `AT+HELP?` returns some website.

For second module, LED doesn't blink but I see module in BT terminal. It also stopped working after `AT+RENEW`. When I try to connect, I get same error.

# Answer
change your COM serial baud rate to 115200. I had the same problem and the moment I change the baud rate on my Serial Com or Serial monitor. it works for me
> 1 votes

---
Tags: bluetooth, ble
---


# Question
Title: How can an Arduino do multiple actions in parallel without interfering with each other?
I am working with my son (9) and we are having a great time learning. But, we've run into a problem and could use your help.

We have two separate loops that we want to run without interfering with the other. Currently we have two LEDs that are blinking in a sequence that has delays built in to keep them on/off.

We also have a Photocell circuit that turns another LED on/off depending on the light.

The problem is, the photocell circuit is lagging 1/2 second due to the light sequence from the other loop.

How do we fix this?

```
// this is declans photo cell and led program

const int photoCell    =  0;  // photo cell variable
const int ledLightButt = 11;  // Led light variable assignment

int lightCal;                 // idk what dis iz
int lightVal;                 // this is the reading from photo cell I think

void setup() {
    pinMode(13, OUTPUT);
    pinMode(12, OUTPUT);

    pinMode(ledLightButt, OUTPUT);
    lightCal = analogRead(photoCell);
}

void loop() {

    lightVal = analogRead(photoCell);

    if (lightVal < lightCal - 50) {
        digitalWrite(ledLightButt, HIGH);
    }
    else {
        digitalWrite(ledLightButt, LOW);
    }

    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    delay(250);

    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
    delay(250);

}

```

# Answer
The root of this behavior is that when the program runs delay() function - nothing else could run (digitalwrites, checks, conditions, etc.) until the delay() time is passed.

The effective solution for this is avioding the delay() function, and getting the same results (without the side-effect) using timers (like millis()) or other ways.

Googling "How to avoid delay()" will give you lot of information about how-to do it, one example can be found here: Arduino Playground - How and Why to avoid delay() function.

Good luck with that, and enjoy your programming experience!
> 2 votes

# Answer
we found some other code that helped us avoid the delay() functions. Now we are able to use the timestamp "Millis" to run our blinking lights AND have another if statement running the photocell & third LED.

Making progress! Thanks for the suggestions! Here is the code and it works great to turn the LED on and off based on the photocell, and have the other LED's flashing on their own.

```
const int photoCell =0;
const int ledPin = 13;
const int led2Pin = 12;
const int led3Pin = 11;
int lightCal;
int lightVal;
int ledState = LOW;
int led2State = HIGH;
long previousMillis = 0;
long interval = 250;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(led3Pin, OUTPUT);
  lightCal=analogRead(photoCell);
}

void loop() {
unsigned long currentMillis = millis();
lightVal = analogRead(photoCell);

if(currentMillis - previousMillis >= interval)
{
  previousMillis = currentMillis;
  if (ledState == LOW)
  ledState = HIGH;
  else
  ledState = LOW;
  if (ledState == LOW)
  led2State = HIGH;
  else
  led2State = LOW;

  digitalWrite(ledPin, ledState);
  digitalWrite(led2Pin, led2State);
}
if (lightVal < lightCal - 50)
{
  digitalWrite(led3Pin, HIGH);
}
else {
  digitalWrite(led3Pin, LOW);
}
}

```
> 1 votes

# Answer
I think that timing might be too hard for 9year old, So :
I will give an alternative: Synchronizing two Arduino's using main or software serial. this can be used to teach Server client (master/slave) architecture where client is set to finish loop quicker and wait for syncing data from server (master) to start next one.
Note that if you are sending numbers over serial to another Arduino use Serial.write() (rather then Serial.print(); it saves you from dealing with asci and char to int (no fun for kid only trouble)
There is a third option of a library which tries to imitate parallel syncing, but that is too much trouble and not a good habit to gain
> 0 votes

# Answer
You can use the library that support blink without delay. For example, You can refer to this example code:

```
#include <ezOutput.h> // ezOutput library

ezOutput led1(7);  // create ezOutput object that attach to pin 7;
ezOutput led2(8);  // create ezOutput object that attach to pin 8;
ezOutput led3(9);  // create ezOutput object that attach to pin 9;

void setup() {
  led1.blink(500, 250);       // 500 milliseconds ON, 250 milliseconds OFF. start immediately
  led2.blink(250, 250, 1000); // 250 milliseconds ON, 250 milliseconds OFF. start after 1000 milliseconds
  led2.blink(100, 100, 2000); // 100 milliseconds ON, 100 milliseconds OFF. start after 2000 milliseconds
}

void loop() {
  led1.loop(); // MUST call the led1.loop() function in loop()
  led2.loop(); // MUST call the led2.loop() function in loop()
  led3.loop(); // MUST call the led3.loop() function in loop()

  // DO OTHER WORK HERE

}

```

The tutorial is available here
> 0 votes

# Answer
There's a rather nice Adafruit tutorial on how to implement this (beyond the one listed already): https://learn.adafruit.com/multi-tasking-the-arduino-part-1

I disagree with the approach given, since it requires that all tasks be polled manually and that you implement it to each task, but the design itself is really clever.

You may also want to check out Makuna's Task library (https://github.com/Makuna/Task), or try my own solution: https://github.com/rdragonrydr/CoRTOS (which is designed to be as efficient and easy-to-use as possible). It's still a work in progress (more optimizations coming soon) but is definitely usable for nearly anything I can think of.
> 0 votes

---
Tags: led, loop
---


title: Spiffs vs Eeprom on esp8266

text:
# Question
Title: Spiffs vs Eeprom on esp8266
In my project, i have some data to save permanently. After some research i got many examples and informations to do that with eeprom. I used it effectively. After all i decide to deep dive to esp8266 and i got some information about spiffs. Now i know what spiffs is and what its purpose. But i am wondering what is difference between eeprom vs spiffs? I know both of them using flash memory as same and we can write and store data with them but why spiffs? Why eeprom ? What are their pros and cons or etc.?

# Answer
I don't think it makes any difference from a hardware point of view. The benefits of using the eeprom library is that it avoids rewriting unchanged data (if you use spiffs you might want to implement that as well) and that the esp is compatible with the arduino environment, where there is a real eeprom.

On the other hand, SPIFFS has its advantages (e.g. easy upload, space). It's up to you...
> 2 votes

# Answer
On the ESP8266 there's very little to choose from between the two. It all really boils down to what you want to store and how you best want to access it.

EEPROM emulation is ideal for small bits of data - configuration values and that sort of thing. Where you just want to store a few of values that would seldom change.

SPIFFS though is better at dealing with large amounts of data. Since it's a filesystem it can store actual files, and that makes it ideal for serving images and static data for web pages, for example.

A SPIFFS filesystem can be built on your PC from files of your choice and then uploaded over serial using `mkspiffs` and `esptool.py` or the SPIFFS tool that can be installed into the Arduino IDE. That means the files are very easy to update.

SPIFFS is not so great when it comes to writing data though - experiments have shown that it gets quite slow when writing often. EEPROM doesn't suffer from such a problem, but then you can't write as much data to EEPROM as you can to SPIFFS.

So that's really all there is to it. Neither is "better" than the other, but each is better suited to different ways of working or to different styles of data.
> 6 votes

# Answer
I will also add a few more things:

SPIFFS acts like a String or Serial object -- so you can do a println() or whatever else you want, and read/parse it back out. There's also a digital-level access that lets you read or write memory structures directly, too. It is wear-leveled and is wonderful for anything where you need multiple independent configs or lots of (searchable!) data.

You can also upload files (or download them) from a web server, and most things that support Strings to write to can use a File as well (YMMV).

EEPROM is not (unless you specifically downloaded a 3rd-party library to do so) wear-leveled on this system and uses one sector of flash. Writing to it too often will cause the sector to fail (~10,000-100,000 times, so it's a lot though). You are also limited by the size of the sector, so the maximum size of the data you can store is 4096 bytes.

Furthermore, EEPROM is written like an array. All your data ends up in this array, and you have to keep track of where each piece is and how large it was (potentially across multiple libraries, files, or functions). Worse, you can't tell if you changed the format since it was last saved (reuploaded your code or something), so you really *should* have a checksum or something.

---

TL;DR: SPIFFS is larger (storable capacity and in terms of code to access) and wear-leveled. It has a lot of convenience features, and lets you write or compose complex data.

EEPROM is tiny and has a limitation on how many times it can be committed before it fails (bad for datalogging and stuff). At best you can write memory blocks to it.

---

Edit: SPIFFS has now been deprecated due to lack of support by the devs, which is somewhat sad. It has been replaced by LittleFS, which (annoyingly to me) has more overhead AND does not do static wear-leveling (it only wear-levels to free space when a file is edited/moved, and does not reuse memory consumed by files that don't change (even if those have by far the least wear)). The interface (aside from changing all instances to "LittleFS" instead of SPIFFS, and some other minor things) is largely the same to the user otherwise, however, so this post still applies.
> 5 votes

---
Tags: esp8266, eeprom, memory
---


# Question
Title: HTTP parsing with authentication in Arduino + ethernet shield
i am trying to parse a page from the route by using Arduino + Ethernet shield. before Arduino testing. I tested my code via python as it shows below. from this code i can get the data as i wish where we need authenticate user name and pass word to access to the router, as you see, here ( admin , admin) in the same time i have to used output variable to get only the data required. Python code is does it.

**Python code:**

```
My_url = "http://192.168.8.1/update.cgi"
r = requests.post (My_url, auth=('admin', 'admin'),data = 'output=netdev' )
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.text)

```

**The output is:**

```
200
text/javascript
ISO-8859-1
netdev = {
 'WIRED':{rx:0x84154,tx:0x5a0cba}
,'BRIDGE':{rx:0x7e680,tx:0x59d98a}
,'WIRELESS0':{rx:0x0,tx:0x0}
,'WIRELESS1':{rx:0x0,tx:0x0}
}

```

Now i am trying to do that by using Arduino + Ethernet shield and i would like print the output on the serial port as it is showing below. Here the router is server and the Arduino is client.

**My problem** is the POST request with the authentication, How I can do it ( POST with authentication + 'output=netdev' like in python code ). Please any idea .. Many thanks in advanced

**Arduino code :**

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192,168,8,1);  // numeric IP for Google (no DNS)
//char server[] = "jsonplaceholder.typicode.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 8, 100);
IPAddress myDns(   8, 8, 8, 8);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  delay(1000);
  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:

    client.println("POST /update.cgi HTTP/1.0");
    client.println("Host: 192.168.8.1");
    client.println("Connection: close");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  //if (client.available()) {
  while (client.available()) {
    char c = client.read();
    Serial.print(c);

  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }

}

```

**Arduino output**

```
Initialize Ethernet with DHCP:
  DHCP assigned IP 192.168.8.107
connecting...
connected to 192.168.8.1
HTTP/1.0 401 Unauthorized
Server: httpd
Date: Sat, 01 Jan 2011 00:27:00 GMT
WWW-Authenticate: Basic realm="DR3800"
Content-Type: text/html
Connection: close

<HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
<BODY BGCOLOR="#cc9999"><H4>401 Unauthorized</H4>
Authorization required.
</BODY></HTML>

disconnecting.

```

---

Thank you Dougie for your anser. I used it , please you can see it in my code below where i used this library it gives no error for GET request , but when i use it ti POST request it gives same authentication problem as you see . where the POST request is important to get the data from .cgi page . Maybe i use that in wrong way .. any advice ? thanks

```
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.get("/"+contentType);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

```

## The output is ok

```
making GET request with HTTP basic authentication
Status code: 200
Response:
Wait five seconds

```

## But for POST as follows :

```
void loop() {
  Serial.println("making GET request with HTTP basic authentication");
  String contentType = "update.cgi";
  String postData = "output=netdev";

  client.beginRequest();
  client.post("/",contentType , postData);
  client.sendBasicAuth("admin", "admin"); // send the username and password for authentication
  client.endRequest();

   // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

```

## the output is :

```
making GET request with HTTP basic authentication
Status code: 401
Response: <HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
<BODY BGCOLOR="#cc9999"><H4>401 Unauthorized</H4>
Authorization required.
</BODY></HTML>

Wait five seconds

```

# Answer
> 0 votes
Rather than trying to send your own GET/POST request by hand coding it, use https://github.com/arduino-libraries/ArduinoHttpClient which does it all for you.

---
Tags: arduino-uno, shields, ethernet, ethernet-shield
---


# Question
Title: Serialize JSON as response to HTTP request
I'd like my ESP8266 to provide some JSON endpoints. I want to use ArduinoJson for serialisation. While this works in general if I serialize into a String and return this String afterwards, I was wondering if there is really no way to do this without wasting so much memory. Shouldn't it be possible to do something like this? Any hints?

```
ESP8266WebServer server;
StaticJsonDocument<768> response;
response["night"] = _playback.isNight();
response["shuffle"] = _playback.isShuffle();
server.send_P(200, "application/json", NULL);
serializeJson(response, server.client());

```

(this gives the following error:)

```
no instance of overloaded function "serializeJson" matches the argument list -- argument types are: (ArduinoJson6141_0000010::StaticJsonDocument<768U>, WiFiServer::ClientType)

```

# Answer
> 2 votes
`serializeJson()` accepts a `Print&`, i.e, a reference to a class that implements the `Print` interface.

`WiFiClient` does implement the `Print` interface, but `serializeJson()` cannot make a reference to it because `ESP8266WebServer::client()` returns a temporary. Indeed, C++ forbids references to temporary variables, only `const` reference to temporaries are allowed.

To fix this compilation error, you must extract a variable:

```
WiFiClient client = server.client();
serializeJson(doc, client);

```

The way I see it, `ESP8266WebServer::client()` should return a `WiFiClient&` instead of a `WiFiClient`, just as `HTTPClient::getStream()` does. I opened issue #7075 about that.

Anyway, even it this fixes the compilation, I'm not sure it will work as you intend because `ESP8266WebServer` may not allow writing directly to the `WiFiClient`.

---
Tags: esp8266, web-server, json
---


# Question
Title: ESP8266 reseted due to relay / AC plugged
My Wemos card is reseting for unknown reason. For example, the pump plugged on the relay works fine till 1am and then the pump stop. After a few research I figured out the ESP should reset because all internal parameters are reseted.

My hardware is simple Wemos card + relay + sensors (not here because not connected yet).

My program is quite complex. I can command/configure the wemos via webservice (ex relay on pin 5 with on 5min/off 10min). https://github.com/TittyPanda/ESP-commander/blob/master/ESP-COMMANDER

* OK if no AC device is connected on relay (no reset)
* OK if a light is connected on relay
* The issue occurs only when the water pump is connected

Maybe it's an electrical/electromagnetical thing because the pump has motor. What do you think ?

Thanks,

**EDIT** Power part are done with common wires from power extension cord

AC-DC converter 5 V 1A 1.5A 500mA

Pump 40W 3000L/H 220V 50Hz

# Answer
Try add some power filter like this:

Between the breadboard and ESP board.
> 2 votes

---
Tags: esp8266, relay, reset
---


# Question
Title: Circuit diagram for running bipolar stepper motor using LDR
I am new to Arduino, some how I have put this code together to run stepper motor using LDR(kind of solar tracker program) I searched on net and tried using servo motor circuit to run stepper motor, assuming just replacing servo motor with stepper motor would work. I guess that is not the case (because servo motor is not moving according to LRD inputs). Please help me with circuit diagram.

Here is the code I am using

```

const int dirPin  = 5;
const int stepPin = 4;
const int enPin   = 6;
const int SensorPin1 = A0;
const int SensorPin2 = A1;
int sensorValue1 = 0;
int sensorValue2 = 0;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);

  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);
  Serial.begin(9600);

}
void loop() {
  sensorValue1 = analogRead(SensorPin1);
  Serial.println(sensorValue1);
  sensorValue2 = analogRead(SensorPin2);
  Serial.println(sensorValue2);

  if(sensorValue1 < 40 && sensorValue2 < 400){
    Serial.print("No sun Detected");
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
  }
  else if(sensorValue1 > 400){

    digitalWrite(dirPin,HIGH);
    digitalWrite(stepPin,HIGH);

 }
else if(sensorValue2 > 400){
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,HIGH);
}
}

```

**Hardware Used:**

* Bipolar stepper motor- NEMA 23 20Kg torque
* Stepper driver: TB6600
* Power supply: SMPS 12V, 5amp
* LDR: 2
* Resistors: 2, 10K resistors
* 1 Arduino Uno
* Breadboard

# Answer
> 1 votes
If it helps, I tuned your code little.

```
const int dirPin  = 8;
const int stepPin = 7;
const int enPin   = 13;//with pin 13 You can monitor on-board LED, if its lit, "enable" is HIGH and stepper will turn.
const int rightSensorPin = A0;
const int leftSensorPin = A1;
int rightSensorRead = 0;
int leftSensorRead = 0;
int rightLightPct = 0;
int leftLightPct = 0;
int degreeChange = 1;

void setup() {
  Serial.begin(9600);
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  pinMode(A0, INPUT_PULLUP);//no need extra resistors. Just connect one LDR leg to A0 and another GND.
  pinMode(A1, INPUT_PULLUP);
}

void loop() {
  rightSensorRead = analogRead(rightSensorPin);
  leftSensorRead = analogRead(leftSensorPin);
  rightLightPct = map(rightSensorRead, 0, 1023, 0, 100);
  leftLightPct = map(leftSensorRead, 0, 1023, 0, 100);
  degreeChange = map(abs(rightLightPct-leftLightPct),0,100,2,10);
  Serial.print("right = ");
  Serial.print(rightSensorRead);
  Serial.print(" left = ");
  Serial.print(leftSensorRead);
  Serial.print(" Pct r/l = ");
  Serial.print(rightLightPct);
  Serial.print("/");
  Serial.println(leftLightPct);
  if(rightLightPct < 15 && leftLightPct < 15){
    Serial.println("Sun is detected");
    digitalWrite(enPin, LOW);
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
    delay(5000);//if somthing get in a way, program waits 5 sec. If nothing in that time, program will continue. That time may erase or add some more.
  }else if(rightLightPct > 50 && leftLightPct > 50){
    Serial.println("Sun is set!");
    digitalWrite(enPin, LOW);
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
  }else if(rightLightPct > 20 && leftLightPct > 20){
    Serial.println("Seeking sun!");
    digitalWrite(enPin, HIGH);
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
    delay(1);
    digitalWrite(stepPin,HIGH);
  }else if(rightLightPct > leftLightPct){
    Serial.println("Turning CW!");
    digitalWrite(enPin, HIGH);
    digitalWrite(dirPin,HIGH);
    digitalWrite(stepPin,LOW);
    delay(1);
    digitalWrite(stepPin,HIGH);
  }else{
    Serial.println("Turning CCW!");
    digitalWrite(enPin, HIGH);
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
    delay(1);
    digitalWrite(stepPin,HIGH);
  }
}

```

---
Tags: arduino-uno, stepper-motor
---


title: Why my 4WD Bluetooth car run so slow

text:
# Question
Title: Why my 4WD Bluetooth car run so slow
Code

```
/*Arduino Bluetooth Controlled Car
 *  * Created by Glen Tech
 * https://www.youtube.com/glentech
  */

#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    Stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(1000);//Define maximum velocity
  motor3.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(1000);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(1000); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(1000); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(FORWARD);  //rotate the motor clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void Stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the button
  motor2.setSpeed(0); //Define minimum velocity
  motor2.run(RELEASE); //rotate the motor clockwise
  motor3.setSpeed(0); //Define minimum velocity
  motor3.run(RELEASE); //stop the motor when release the button
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

```

# Answer
> 1 votes
I can't find issue in your code that I'm convinced is your problem. Without seeing your datasheet for the motor, I would bet your issue is one of two things:

1) A 9V battery is low-current relative to most batteries I've used for powering any decent DC motors. Do you have access to a better current source you could try?

2) Every motor has a trade-off in torque vs max-speed, dictated by the internal gear-ratio. Depending on the motor type, it may not have the torque to accelerate the vehicle to a significant speed.

---
Tags: bluetooth
---


# Question
Title: program evaluating if clause incorrectly
As the title says i'm having a problem with an if clause evaluating incorrectly in one particular function

```
uint16_t    getSleepTime()
{
    volatile uint8_t flag = EEPROM.read(3);

    uint8_t high    = EEPROM.read(0);
    uint8_t low     = EEPROM.read(1);

    if(flag != 0xaa);
    {
        Serial.println(flag);
        Serial.println("ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.");
        while(true)
        {
            digitalWrite(PIN_LED, true);
            delay(250);
            digitalWrite(PIN_LED, false);
            delay(250);
            wdt_reset();
        }
    }

    return word(high, low);
}

```

the result is that the if function evaluates as true always my first thought was, ok the eeprom wasn't written properly, hence i added the println, the returned value was 170 == 0xaa then i thought well maybe the flag variable is optimized out, hence the volatile and then, well maybe its a type comparison issue so i also defined a const uint8\_t flagv with value 0xaa same results in every case

```
13:21:00.991 -> 170
13:21:00.991 -> ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.
and the corresponding blink

```

the thing is that being such a trivial code i'm out of ideas right now, as anyone here experienced something like this?

# Answer
> 2 votes
Do not put a `;` after an if:

```
if(flag != 0xaa);

```

is the same as

```
if(flag != 0xaa)
{
}

```

Meaning that the code after the `if` statement is always executed.

---
Tags: error
---


# Question
Title: Substitute multiple potentiometers for push buttons and single potentiometers
this is my first post here. For some time I have been struggling with a problem and would like to know if anyone has a solution to share.

I am building a 4 tone sequencer, where I use 4 potentiometers to change the pitch of each tone beat. I want to add more beats to the sequencer so I would like to have an elegant solution instead of keep adding potentiometers. My idea was to use 1 potentiometer to control the pitch and use multiple push buttons with the single potentiometer for this process. All in all it goes like this: \- When switch1=HIGH, pitch1=analogRead(A0); \- When switch2=HIGH, pitch2=analogRead(A0); The problem is that when I change pitch1 and pitch2 the end up getting the same values as soon as I press their switch. My code looks like this:

```
   if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

```

I would really like to store that analog reading value when I press switch1 and keep it until switch1 goes HIGH again.

EDIT:

Let me try to explain the issue better: I have 2 push buttons and 1 potentiometer, all of them are inputs. The code I am aiming for is to do the following: 1 - While pressing push button1 I want to read the value of potentiometer and store it to a variable1. When the button1 is not pressed I want to keep that variable stored. 2 - While pressing push button2 I want to read the value of potentiometer and store it to a variable2. When the button2 is not pressed I want to keep that variable stored. I have successfully achieved this, however the problem comes when I press button1 again to adjust variable1, variable2 is also getting adjusted in the process, even when I am not pressing button2 Chris - The push buttons are correct since I can change the states of the digital pins when I press them ( and I measure the 5V when pressed). I do not need the buttons to be pressed at the same time. What I need is the buttons to trigger the event of storing potentiometer data only when either one of them is pressed accordingly. jsotola - Sorry for the bad explanation. I hope this one is better. Code:

```
#include "pitches.h"

int notes[]={

NOTE_B1,
NOTE_C2,
NOTE_CS2,
NOTE_D2,
NOTE_DS2,
NOTE_E2,
NOTE_F2,
NOTE_FS2,
NOTE_G2,
NOTE_GS2,
NOTE_A2,
NOTE_AS2,
NOTE_B2,
NOTE_C3,
NOTE_CS3,
NOTE_D3,
NOTE_DS3,
NOTE_E3,
NOTE_F3,
NOTE_FS3,
NOTE_G3,
NOTE_GS3,
NOTE_A3,
NOTE_AS3,
NOTE_B3,
NOTE_C4,
NOTE_CS4,
NOTE_D4,
NOTE_DS4,
NOTE_E4,
NOTE_F4,
NOTE_FS4,
NOTE_G4,
NOTE_GS4,
NOTE_A4,
NOTE_AS4,
NOTE_B4,
NOTE_C5,
NOTE_CS5,
NOTE_D5,
NOTE_DS5,
NOTE_E5,
NOTE_F5,
NOTE_FS5,
NOTE_G5,
NOTE_GS5,
NOTE_A5,
NOTE_AS5,
NOTE_B5,
NOTE_C6,
NOTE_CS6,
NOTE_D6,
NOTE_DS6,
NOTE_E6,
NOTE_F6,
NOTE_FS6,
NOTE_G6,
NOTE_GS6,
NOTE_A6,
NOTE_AS6,
NOTE_B6,
NOTE_C7,
NOTE_CS7,
NOTE_D7,
NOTE_DS7,
NOTE_E7,
NOTE_F7,
NOTE_FS7,
NOTE_G7,
NOTE_GS7,
NOTE_A7,
NOTE_AS7,
NOTE_B7,
NOTE_C8,
NOTE_CS8,
NOTE_D8,
NOTE_DS8
};

int Tone = 0;
int speakerPin = 3;

int switch1=6;
int switch2=7;
int switch3=8;
int switch4=9;
int switch5=10;
int switch6=11;
int switch7=12;
int switch8=13;

void setup() {

Serial.begin(9600);

pinMode(switch1, INPUT);
pinMode(switch2, INPUT);
pinMode(switch3, INPUT);
pinMode(switch4, INPUT);
pinMode(switch5, INPUT);
pinMode(switch6, INPUT);
pinMode(switch7, INPUT);
pinMode(switch8, INPUT);

}

void loop() {

 // get potentiometers inputs
//int TonePot = analogRead(A0); // 0 – 1023
//int DurationPot = analogRead(A1); // 0 – 1023
int TempoPot = analogRead(A2); // 0 – 1023

int Tone1Pot;
int Tone2Pot;
int Tone3Pot;
int Tone4Pot;
int Tone5Pot;
int Tone6Pot;
int Tone7Pot;
int Tone8Pot;

int Duration1Pot;
int Duration2Pot;
int Duration3Pot;
int Duration4Pot;
int Duration5Pot;
int Duration6Pot;
int Duration7Pot;
int Duration8Pot;

// calculate corresponding, divide by 13 as we have 77 pitches. 1023/77 ~ 13
int pitch1;
int pitch2;
int pitch3;
int pitch4;
int pitch5;
int pitch6;
int pitch7;
int pitch8;

int pitch1stored;
int pitch2stored;

int noteduration1 = Duration1Pot/8;
int noteduration2 = Duration2Pot/8;
int noteduration3 = Duration3Pot/8;
int noteduration4 = Duration4Pot/8;
int noteduration5 = Duration5Pot/8;
int noteduration6 = Duration6Pot/8;
int noteduration7 = Duration7Pot/8;
int noteduration8 = Duration8Pot/8;

int tempo = TempoPot;

//Get state of switches if HIGH or LOW
int switch1state=digitalRead(switch1);
int switch2state=digitalRead(switch2);
int switch3state=digitalRead(switch3);
int switch4state=digitalRead(switch4);
int switch5state=digitalRead(switch5);
int switch6state=digitalRead(switch6);
int switch7state=digitalRead(switch7);
int switch8state=digitalRead(switch8);

////////////////////////////////////////Sound generation code /////////////////////////////////

if(switch1state==HIGH)
  {
    Tone1Pot=analogRead(A0); // 0 – 1023
    pitch1=Tone1Pot/13;
  }

tone(speakerPin, notes[pitch1], 200);

//tone(speakerPin, 0, 200);}// make the tone mute

Serial.print("pitch1= ");
Serial.print(pitch1);
Serial.print("     ");
delay(tempo);

if(switch2state==HIGH)
  {
    Tone2Pot=analogRead(A0); // 0 – 1023
    pitch2=Tone2Pot/13;
  }

tone(speakerPin, notes[pitch2], 200);

Serial.print("pitch2= ");
Serial.print(pitch2);
Serial.print("     ");
delay(tempo);

if(switch3state==HIGH)
  {
    Tone3Pot=analogRead(A0); // 0 – 1023
    pitch3=Tone3Pot/13;
  }

tone(speakerPin, notes[pitch3], 200);

Serial.print("pitch3= ");
Serial.print(pitch3);
Serial.print("     ");
delay(tempo);
}

```

# Answer
I cannot see, how your code would show the described behavior (assuming that, you have connected the buttons correctly with a pulldown resistor). But your code can be greatly simplified, which would make it less error prone.

You have 8 buttons, which screams for the usage of arrays (IMO you should always use arrays, if you have more than 2 or 3 equal buttons). First put the button pins into an array:

```
#define N_BUTTONS 8
int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13};

```

Then define an array to hold the measured pitches (here initialized with 0):

```
int pitches[N_BUTTONS] = {0};

```

In your `setup()` function you can loop over the `button_pins` array to set them as input:

```
for(int pin : button_pins) pinMode(pin, INPUT);

```

In the `loop()` function you again loop over the button pins, but this time you check, if the current button is pressed. If yes, you measure the analog voltage, calculate the pitch and save it into the corresponding element of the `pitches` array:

```
for(int button=0;button < N_BUTTONS;button++){
    if(digitalRead(button_pins[button])){
        pitches[button] = analogRead(A0)/13;
    }
}

```

This always works for multiple pressed buttons at once.

Also you should avoid calls to `delay()` in your `loop()` function. That is just time, that the Arduino cannot do anything, including checking your buttons. If you want to do something timed, you should use a non-blocking coding style, like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Basically it uses the `millis()` function as a clock, checking regularily, if the needed time has passed and only doing something if it had passed; letting other code execute, if not. There are tons of tutorials about this on the web.

As you have seen above, I didn't include the `tone()` function in my answer. That is because you should decouple your input and output code. The code above is the input code. It saves the wanted pitches into the corresponding array. Then, after that code, you can write all the code you need for outputting the pitches as tones (however you actually want to output them). The only real logical connection between these 2 parts of code is the `pitches` array. That makes it easier to have more and different inputs (for example if you wanted to have a reset button, which sets all the pitches at onece to a predefined value). Also the function of the input code (which needs to very regularily check the buttons, to be responsive) is not disturbed by the output code.
> 1 votes

# Answer
So based on the information you provided I understand that the issue is that both the `if(switch1state==HIGH)` and the \`if(switch2state==HIGH)' statements evaluate to true if either switch is flipped. That means one of the following things is happening:

1) Somewhere in your code you're mixing their values and assigning ones value to the other

2) Your configuration of the digitalRead pins is wrong (either wrong pins or wrong pupdr config as I've seen incorrect pull-up and pull-down resistors propagate unexpected behavior across the ground)

3) your wires are crossed. If you're using a breadboard make sure you know how it's connected internally. Some swap between horizontal and vertical rows.
> 0 votes

---
Tags: arduino-uno, analogread, button, potentiometer
---


title: Thermocouple and multimeter

text:
# Question
Title: Thermocouple and multimeter
I've put together this script that should allow my Arduino Mega to be show thermocouple readings on the serial monitor, whilst also showing readings of voltage and ohms across a given component. I'd be grateful for any advice on how it can be improved/streamlined:

```
#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int raw = 0;
int Vin = 5;
float Vout = 0;
float R1 = 220;
float R2 = 0;
float buffer = 0;
float volt = 0;
int input = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);
  tempSensor.begin();

  if (tempSensor.isConnected()) {
    Serial.println("Device will acknowledge!");
  }
  else {
    Serial.println("Device did not acknowledge! Freezing.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Device ID is correct!");
  }
  else {
    Serial.println("Device ID is not correct! Freezing.");
    while (1);
  }

  pinMode(A4, INPUT);
}

void loop() {

  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }

  raw = analogRead(analogPin);
  if (raw)
  {
    buffer = raw * Vin;
    Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

```

# Answer
Your code is not very long, but I already see a few things that I would change.

```
int analogPin = 0;
[...]
pinMode(A4, INPUT);

```

These usages of pins are inconsistent. I personally prefer settings at the beginning of the file, so I'd expect

```
int analogPin = 0;
int whateverPin = A4;  // I don't have a good name yet

```

While you have

```
pinMode(A4, INPUT);

```

there's no

```
pinMode(analogPin, INPUT);

```

The main loop is doing 2 things: a) show temperature reading and b) show the component specs. This would be more obvious if written like this:

```
void loop() {
  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  showTemperatureReadings();
  showComponentReadings();
}

```

Now, that looks a bit strange, don't you think? What about the stuff before these two big `show...()` methods? These two lines clearly belong into `showComponentReadings()`.

Now, a lot of variables are declared outside of methods. This makes them global variables. It's possible to change them from anywhere in the code. When the project grows, side effects are evil. Let's remove as many of them as possible.

You can get rid of:

```
int input = 0;
float volt = 0;
float buffer = 0;
float R2 = 0;
float Vout = 0;
int raw = 0;

```

After this change, I think the `setup()` method could be more concise. A lot of stuff just deals with the temperature sensor. I would extract a method as well.

The error messages like

> Device did not acknowledge! Freezing.

could not mean very much to the user. A message like

> Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.

could give more meaningful instructions.

The final code with these suggestions applied:

```
#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int whateverPin = A4;
float R1 = 220;
int Vin = 5;

void setupTemperatureSensor() {
  tempSensor.begin();
  if (tempSensor.isConnected()) {
    Serial.println("Temperature sensor acknowledged.");
  }
  else {
    Serial.println("Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Temperature sensor ID is correct.");
  }
  else {
    Serial.println("The temperature sensor ID does not have the expected value. Do you use a different sensor type? Use a SparkFun MCP9600.");
    while (1);
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);

  setupTemperatureSensor();

  pinMode(whateverPin, INPUT);
  pinMode(analogPin, INPUT);
}

void showTemperatureReadings() {
    if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }
}

void showComponentReadings() {
  int input = analogRead(whateverPin); //analogRead function is used to receive analog data
  float volt = (input * 5.0) / 1024.0; //formula using for perform action
  int raw = analogRead(analogPin);
  if (raw)
  {
    float buffer = raw * Vin;
    float Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    float R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

void loop() {
  showTemperatureReadings();
  showComponentReadings();
}

```

With code folding active, I'd say it's now very simple to get an overview of what the code is doing and what can be configured:

---

Edit:

After you linked to the schematics, I would

* rename `whateverPin` to `voltageDividerPin`.
* change the calculation `float volt = (input * 5.0) / 1024.0;` to a mapping, because it maps the 1024 input values to 5V, so `float volt = map(voltageReading, 0, 1024, 0, Vin);`
* remove `analogPin` completely, because it's not used in the original code as well.

I also hope that read the article and you understood the consequences of using a 220 Ohm resistor.
> 1 votes

---
Tags: code-review, code-optimization, voltage, voltage-divider
---


title: Wiring parallel TFT with ESP32

text:
# Question
Title: Wiring parallel TFT with ESP32
I have this Parallel LCD TFT. I want to connect it with an ESP32 (NodeMCU). I am using the TFT\_eSPI library. In the TFT\_eSPI documentation, it says that the connection should be as following:

```
// The ESP32 and TFT the pins used for testing are:
//#define TFT_CS   33  // Chip select control pin (library pulls permanently low
//#define TFT_DC   15  // Data Command control pin - use a pin in the range 0-31
//#define TFT_RST  32  // Reset pin, toggles on startup

//#define TFT_WR    4  // Write strobe control pin - use a pin in the range 0-31
//#define TFT_RD    2  // Read strobe control pin  - use a pin in the range 0-31
//#define TFT_D0   12  // Must use pins in the range 0-31 for the data bus
//#define TFT_D1   13  // so a single register write sets/clears all bits.
//#define TFT_D2   26  // Pins can be randomly assigned, this does not affect
//#define TFT_D3   25  // TFT screen update performance.
//#define TFT_D4   17
//#define TFT_D5   16
//#define TFT_D6   27
//#define TFT_D7   14

```

P.S. My tft does not have DC PIN. So, I wired nothing to GPIO15

After I wired the TFT, the ESP32 stop responding to flash process. and obviously, it did not run anything(even if I flash it without the screen and then wiring it again)

My question is:

* What is the mistake did I do? How can I link this parallel LCD with ESP32

# Answer
> 1 votes
Sorry for the Late reply, I had the same issue. You cant have anything connected to pin 15 or 2 during flash

---
Tags: lcd, esp32, tft
---


# Question
Title: ESP8266, sporadically no write access to the file system
I have an ESP8266 project which reads my gas consumption. The hardware and the project run satisfactorily. Sporadically, the ESP8266 can no longer write to its file system and therefore cannot save any data. As soon as I upload the complete data and the sketch to the device again, it works for a few months. After that, the mistake occurred again and again. What could that be?

The ESP8266 then has an "Exception" error. Unfortunately, I have not yet been able to find the reason for the error, why it always happens.

Does anyone have a tip on how I can isolate the problem?

https://github.com/HomeAutoUser/ESP-Gaszaehler-GZ16/tree/pre-release\_v1.91

# Answer
I have faced the same issue with my water leak detector, based on esp8266. It was caused by memory leak in the ESP binaries, so, I've updated it to ver 2.6.3

So, you can try to log (print to serial) free memory amount:

```
extern "C"
{
    #include "user_interface.h"
}
uint32_t free = system_get_free_heap_size();

```
> 1 votes

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


# Question
Title: Parallel communication between multiple Arduino
Here's a post which explained the communication standard.

I need to establish communication between multiple Arduino nano board. I have used SPI bus on one of the Arduino board for wireless communication and I2C bus for another device. It appeared that both I2C bus and SPI bus support multiple device. However, since I have used both I2C and SPI for different purpose, establish parallel communication with RX TX pins seemed to be the preferable choice.

**Question 1:** This post provided a nice set up for I2C bus as master and slave. However, can one adjust the code in step 2 of master device with

```
 Wire.begin(n);

```

and change all the Arduino boards as master&slave devices, thus achieve parallel communication?

**Question 2:** I read this post where people mentioned RS 485. However, can one achieve parallel communication with RX and TX pin like the one used in Question 1, without using RS 485?

# Answer
parallel communication is possible using arduino you need to use the ports for example port A and then a rx tx pins.

```
#include <Wire.h>
#include <Arduino.h>

byte i = 0;
int intpin = 44;
int rcv_ready = 45;

void setup() {
  DDRA = B11111111; // Output
  DDRC = B11111111; // Output
  pinMode(intpin, OUTPUT);
  pinMode(rcv_ready, INPUT);
}

void loop() {
  transmit();
}

void transmit() {
  PORTA = i++
  PORTC = i;
  digitalWrite(intpin, HIGH);
  while (rcv_ready == LOW) {}
  digitalWrite(intpin, LOW);

  delay(299);
}

```

Here we set up the two ports DDRA and DDRC to be output ports by using the mask B11111111; We set the interrupt pin to port 44 and set it is an output and we set the receive pin to be 45 and an input. Then we call transmit in the loop. Where we then set port A and port C to equal i++ and i respectively. And then toggle the signal to say we have transmitted a new message. This will get picked up by the Slave-input.

Slave input

```
#include <Arduino.h>

byte x = 0;
byte y = 0;
int rcv_ready = 45;

void setup() {
  DDRA = B00000000; // Input
  DDRC = B00000000; // Input
  Serial.begin(19200);
  attachInterrupt(5, blink, RISING);
  pinMode(rcv_ready, OUTPUT);
  digitalWrite(rcv_ready, LOW);
}

void loop() {}

void blink() {
  x = PINA;
  y = PINC;
  delay(100);
  digitalWrite(rcv_ready, HIGH);
  delay(100);
  digitalWrite(rcv_ready, LOW);
  Serial.print(x);
  Serial.print(" , ");
  Serial.println(y);
}

```

Here we set up the two ports DDRA and DDRC to be input ports by using the mask B00000000; We then set the baud rate as 19200 which matches the rate set by the master

Here we set the interrupt to be 5 which is pin 18 and tell it to call blink on an interrupt. We then read the values from PORTA and PORTC and then we output it to the serial monitor screen. We also send back the acknowledgement of receipt to the master using pin 45
> -1 votes

---
Tags: serial, i2c, communication, rx-pin
---


title: Extra `eecfbba=.@aa` file in sd card

text:
# Question
Title: Extra `eecfbba=.@aa` file in sd card
I am doing a project, and I need an SD card. Everything worked well, but after a while when I read the SD card from my PC(Windows 10 64 bit, Intel Core), I found a file called `eecfbba=.@aa`. It's so big that it almost ate up one GB storage of my SD card. But when I tried to open it with notepad, notepad tells me that there is actually no such file, and asks me if I want to create it. I tried to delete it, but file explorer also told me there is no such file. What is it?

This is my code:

```
#include <ArduinoJson.h>

// Version 0.20.1.19.3.7:
// 2020/01/19, 16:10, button record test, 7th version.

#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <Wire.h>
#include "RTClib.h"
//#include <string.h>

RTC_DS1307 rtc;
String strdoc;
char daysOfTheWeek[7][2] = {"su", "mo", "tu", "we", "th", "fr", "sa"};
#define SD_ChipSelectPin 10  // 如果使用 arduino nano 328 可使用Pin4

TMRpcm audio;
void setup() {
  audio.speakerPin = 8;
  Serial.begin(9600);
  pinMode(25, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  else
  {
    Serial.println("rtc started");
  }

  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD Fail");
    return;
  } else {
    Serial.println("SD OK");
  }

  audio.setVolume(6);
  audio.CSPin = SD_ChipSelectPin;

  StaticJsonDocument<200> doc;
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;
  JsonArray data = doc.createNestedArray("data");
  data.add(48.756080);
  data.add(2.302038);
  serializeJson(doc, strdoc);
}
bool isrecording = false;
bool recordButtonPressed()
{
  return (digitalRead(25) == LOW);
}
bool playButtonPressed()
{
  return (digitalRead(7) == LOW);
}
void loop() {
  delay(200);
  // Below is the formatted datetime.
  DateTime now = rtc.now();
  // Below is the serialized datetime.
  String filename = (String)(now.unixtime() % 10000000) + ".j";
  //  Serial.println(filename);
  if (recordButtonPressed())
    if (!isrecording)
    {
      isrecording = true;
      audio.startRecording("test.wav", 16000, A0);
      Serial.println("stt");
    }
    else
    {
      isrecording = false;
      Serial.println("stp");
      audio.stopRecording("test.wav");
    }
  Serial.println("sdsad991===`=`");
  if (playButtonPressed())
  {
    audio.play("test.wav");
    Serial.println("ply");
  }
  String dataString = strdoc;
  if (!isrecording)
  {
    File dataFile = SD.open(filename, FILE_WRITE);

    if (!dataFile) {
      Serial.println(F("Failed to create file"));
    }
    else
    {
      dataFile.println(dataString);
      Serial.println("Wrote string.");
      dataFile.close();
      Serial.println("Closed file.");
    }
  }
  /* Please ignore this line */
  //  //    audio.play("test.wav"); break;audio.volume(1); break;audio.volume(0); break;audio.stopPlayback(); break;
}

```

P.S. I'm using Mega 2560, so MISO, MOSI, SCK and CS pins are different.(Which is 50,51,52,10).

Edit 2020/1/25, 14:15(Beijing Time) At 1/20 I have bigger problems. There are more and more big files. All of them are the same situation. For details, take a look at this photo(ignore selected files): Imgur or 咱们中国人上不去imgur，用这个：File-up（直接下载）

# Answer
> 0 votes
Thanks to @Juraj, I fixed the problem. Deleted those files by manually formatting the SD card.

***This is not really the answer, you can see the answer in this comment under the question.***

---
Tags: arduino-mega, spi, sd-card, sd.h
---


# Question
Title: Running a robot with 2 front-facing sensors, but it's stuttering
Here's the run down: I have a small robot with four continuous servo motors and two ultrasonic sensors. It's run by and UNO board with a Sensor Shield V5 on top. My goal is to program the front right and front left sensors to both be returning distances in inches, and have the robot turn in the direction with the most room when one of the sensors returns a distance less than some minimum. I am very confident that the motors and sensors aren't the issue, as testing them by themselves shows no issues. However, when I run the below code the robot stutters, mainly just going backwards but stuttering forwards and occasionally turning for a second or two. Any ideas what's going on?

```
#include <Servo.h>

Servo FL;
Servo FR;
Servo BL;
Servo BR;

const int FRecho = 11;
const int FRtrig = 10;
const int FLecho = 9;
const int FLtrig = 8;

long durationFL;
long durationFR;
int distanceInchR = 24;
int distanceCmR;
int distanceInchL = 24;
int distanceCmL;

const int minDistanceInch = 18;
const int minDistanceCm;

enum movementStates {
 STILL,
 FORWARD,
 BACK,
 TURNFR,
 TURNFL,
 NOTHING
};

enum movementStates movement;

void setup() {

  FL.attach(4);
  FR.attach(5);
  BL.attach(6);
  BR.attach(7);

  pinMode(FRtrig, OUTPUT);
  pinMode(FRecho, INPUT);
 pinMode(FLtrig, OUTPUT);
  pinMode(FLecho, INPUT);

  movement = NOTHING;

  forward();

}

void loop() {

updateDistanceFL();
updateDistanceFR();

updateDirection();

}

void forward () {
  FL.write(180);
  FR.write(0);
  BL.write(180);
  BR.write(0);
  movement = FORWARD;
}

void turnFR () {
  FL.write(180);
  FR.write(180);
  BL.write(180);
  BR.write(180);
  movement = TURNFR;
}

void turnFL () {
  FL.write(0);
  FR.write(0);
  BL.write(0);
  BR.write(0);
  movement = TURNFL;
}

void backUp () {
  FL.write(0);
  FR.write(180);
  BL.write(0);
  BR.write(180);
  movement = BACK;
}

void still () {
  FL.write(90);
  FR.write(90);
  BL.write(90);
  BR.write(90);
  movement = STILL;
}

void updateDirection() {

  if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
    if (movement != BACK) {
      backUp();
    }
    else if (distanceInchR < minDistanceInch) {
     if (movement != TURNFL) {
      turnFL();
     }
    }
    else if (distanceInchL < minDistanceInch) {
     if (movement != TURNFR) {
      turnFR();
     }
    }
    else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
    if (movement != FORWARD) {
      forward();
    }
  }
    else {
      if (movement != STILL) {
        still();
      }
    }
}

void updateDistanceFR(){
digitalWrite(FRtrig, LOW);
delayMicroseconds(2);
digitalWrite(FRtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FRtrig, LOW);
durationFR = pulseIn(FRecho, HIGH);
distanceCmR= durationFR*0.034/2;
distanceInchR = durationFR*0.0133/2;
  }

void updateDistanceFL(){
digitalWrite(FLtrig, LOW);
delayMicroseconds(2);
digitalWrite(FLtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FLtrig, LOW);
durationFL = pulseIn(FLecho, HIGH);
distanceCmL= durationFL*0.034/2;
distanceInchL = durationFL*0.0133/2;
  }

```

# Answer
> 2 votes
your `updateDirection` logic doesn't quite work the way you think it does.

after a bit of code formatting and comments it looks like this:

```
void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        } else if (distanceInchR < minDistanceInch) {
            //always entered if movement == BACK
            if (movement != TURNFL) {
                turnFL();
            }
        } else if (distanceInchL < minDistanceInch) {
            //never entered
            if (movement != TURNFR) {
                turnFR();
            }
        } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
            //never entered
            if (movement != FORWARD) {
                forward();
            }
        //endif distanceInchR < minDistanceInch && distanceInchL < minDistanceInch
    } else {
        // entered when distanceInchR > minDistanceInch || distanceInchL > minDistanceInch
        if (movement != STILL) {
            still();
        }
    }
}

```

it looks like you had a missing closing brace around the first condition. Causing the only movement functions that get called to be `backUp`, `turnFL` and `still`.

If we add the missing braces then it looks much better:

```
void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        }
    } else if (distanceInchR < minDistanceInch) {
        if (movement != TURNFL) {
            turnFL();
        }
    } else if (distanceInchL < minDistanceInch) {
        if (movement != TURNFR) {
            turnFR();
        }
    } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch) {
        if (movement != FORWARD) {
            forward();
        }
    } else {
        if (movement != STILL) {
            still();
        }
    }
}

```

---
Tags: arduino-uno, sensors, servo, robotics
---


# Question
Title: Components required to control the Speed of Wilo Para AC Synchronous Motor
I want to control the speed of the AC motor based on the temperature set on the Nextion HMI. Right now I have my ESP32 Microcontroller and Solid-state relays which supply the maximum output power of 10 amperes. My Wilo Motor requires the power of 0.03 to 0.66Amps. I am in a state of confusion about what component is required in the middle to connect my ESP32 Controller to send the analog PWM control signals of 0 to 10V to my Wilo Para Motor for the speed control. I searched in Google and I got few data like H-Bridge, PWM Speed control manual module. I'm stuck in this work and I'm looking for help.

Below I have attached the link of the datasheet. On page number 34 is my WILO Para Motor and the model name is Wilo Para 25-180/9-87/IPWM1 in the table

https://wilo.cdn.mediamid.com/cdndoc/wilo164576/1544113/wilo164576.pdf

Thanks in Advance.

# Answer
You do not want a "0-10V PWM signal". There is no such thing.

There are generally 2 methods of controlling motors like these:

* Through a variable analog voltage between 0V and 10V, where the voltage given is proportional to the speed, and
* Using a digital PWM signal where the duty cycle is proportional to the speed.

You are getting confused and combining the two together (and to be honest that datasheet, which is really little more than a sales brochure, doesn't help matters).

Typically a PWM input on a motor uses a standard TTL signalling method. This specific motor, as detailed in this document uses a slight modification on the standard. It requires a minimum of 3.6V for a HIGH, and the ESP32 gives 3.3V maximum.

Because of that you will need to amplify, or "boost" the signal to a slightly higher voltage. The simplest way to do that is with an off-the-shelf logic level translator (3.3V to 5V). There are cheap MOSFET based ones on eBay etc that will do the job.

If you want to create your own the circuit is quite simple, and requires one N-channel MOSFET and two resistors. I use the BSS138:

simulate this circuit – Schematic created using CircuitLab
> 1 votes

# Answer
Page 6 of this doc explains, what is iPWM and its electrical characteristics.

So, you need some low-power PNP transistor and the resistor (about 5-10k).
> 1 votes

---
Tags: esp32
---


# Question
Title: Neopixel code not working on Adafruit Feather board
I have connected a single neopixel to my Adafruit Feather board, running Arduino software.

The power pin is connected to 3V on the Feather. The data-in pin is connected to pin 15 on the Feather.

As soon as power is connected, the light shows blue. But uploading any program has no effect whatsoever. The Neopixel won't respond to anything.

How can I use a Neopixel on the Adafruit Feather?

```
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif

#define PIN 15
#define NUMPIXELS 1

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

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

void loop() {
  Serial.println("RED");
  pixels.setPixelColor(PIN, pixels.Color(255, 0, 0));
  pixels.show();
  delay(1000);
  Serial.println("GREEN");
  pixels.setPixelColor(PIN, pixels.Color(0, 255, 0));
  pixels.show();
  delay(1000);
}

```

The neopixel and the Feather board

# Answer
> 1 votes
Pin 15 is the serial RX pin which connects to the USB port so you should not use it. From the Feather pinouts page about pins 15,16 : "These are connected through to the CP2104 USB-to-Serial converter so they should not be connected to or used unless you're super sure you want to because you will also be getting the USB traffic on these!"

So try another pin and it should work.

---
Tags: arduino-ide, adafruit, neopixel, feather
---


# Question
Title: Trying to flash ESP8266 with Arduino UNO
This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.

I am the point where I plug it into my computer via USB, open the Arduino IDE \> Tools \> Serial Monitor.

I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.

Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

Any advice with regards to anything you see here would be great, I am new to the world of circuits.

Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

# Answer
> 3 votes
You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.

And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).

When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.

One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.

# Answer
> 0 votes
What I have done was connecting ESP8266 and UNO as the schematic described.

But instead of using the default program in ESP8266, I programmed ESP8266 via UNO using the ESP8266 Library on Arduino IDE

If your way still did not work you can maybe try this method.

# Answer
> 0 votes
I think I may be able to help clarify things a bit here:

You are not trying to "flash" the ESP01 (the kind you have) board, but you are trying to talk to the AT command firmware it came installed with.

Also, there's a sort of pingback sketch (I forget the name and can't find it, but it basically uses a SoftwareSerial and copies characters from one to the other and vice versa) that is used to configure the ESP01 that's *normally* used, but you don't seem to be using it here (it may not be worth the effort, either, since it's tricky to get working sometimes).

In this case, it seems that you are trying to do one of two things:

If you are trying to talk to the ESP01 module **from the computer** connect the TX to the TX pin and the RX to the RX pin. This is because the Arduino board's serial adapter is *already* connected in the mirrored direction, and you are using that to talk to the ESP01. Do note that you should, **before** connecting the ESP01, upload the Blink sketch or similar to the Arduino so that it's not trying to use the Serial connection too. See http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/ for more information on that use case.

On the other hand, if you are trying to talk to the device from the Arduino itself (as in, the Arduino has a program that needs WiFi access), you'd want to connect it RX to TX and TX to RX. Of course, when doing this, the Arduino should already have its program uploaded since the ESP01 would cause issues uploading firmware via Serial afterward (they both talk at once).

Lastly, these things are REALLY finicky, so make sure you set the baud rate and use NLCR end-of-line signaling.

---
Tags: arduino-uno, serial, esp8266, voltage-level, flash
---


title: ESP32 - NTP inaccuracy after deep sleep

text:
# Question
Title: ESP32 - NTP inaccuracy after deep sleep
I'm trying to create a sensor sampling project using ESP32 ( battery, solar panel and temperature affects are not part of test right now to reduce external effects that may cause/ increase such behaviour ).

In current phase, I'm only testing the sleep & waking up process.

A short description: System wakes up after deep sleep cycle, connects to Wifi, MQTT, NTP - and checks if wake up time ( wake up value is stored in ׳RTC\_DATA\_ATTR long calc\_waketime׳ variable from previous cycle ), posting IFTTT, goes to deep sleep for another 10 min. cycle.

The phenomena I wish to share is: The longer deep sleep is the **NTP has few seconds drift which gets longer (again - NTP sync has a drift and not RTC clock)**.

I'm aware that wake time/ RTC drifts during deep sleep ( especially in ESP8266 chips that wake up can be not accurate in terms of minute - I'm using ESP32). Since ESP32 uses RTC, waking up is very accurate ( matter of seconds ). In order to wake up in exact time ( 18:00, 18:10, 18:20... every hour ) code connects to Wifi& NTP, and verify that wake time was as intended (comparing the epoch value that was stored during the end of previous cycle and current epoch time ) if it woke up earlier, it will got to sleep for that missing time.

But - What puzzles me is why updated NTP time ( which is not related what so ever to RTC drifts ), is drifted the longer to sleep is ( for comparison : when less than a minute - almost no drift, when sleeping for 10 minutes, 3 seconds drift, 20 minutes get up to 5 seconds drifts ).

Please see **NOTE(1)** to witness the drift in 10 min sleep.

Posting terminal output: some explantions: NOTE (1) displays the 3 seconds drift , NOTE(2) calculated time that was stored at previous wake cycle, NOTE (3) shows that that **drift get synced** during the code run - 594 sec for next wake 18:50:00.

```
18:39:58.032 -> 09B⸮⸮L⸮1U1V(⸮⸮⸮1m1m1F⸮Connecting to Xiaomi_D6C8 .... // WAKING UP
18:39:58.595 -> 192.168.3.186
18:39:59.013 -> now is: 1580575203               **// NOTE (1)**
18:39:59.013 -> sleep time was: 1580574611
18:39:59.048 -> expected wake time: 1580575200   // NOTE (2)
18:39:59.085 -> total time delta: 3
18:39:59.122 -> OK - WOKE UP after due time:
18:39:59.419 -> Attempting MQTT connection...connected
18:40:04.544 -> Connecting to maker.ifttt.com
18:40:04.855 -> Request resource: /trigger/send_reading/with/key/cFLymB4JT9tlODsKLFn9TA
18:40:05.376 -> HTTP/1.1 200 OK
18:40:05.376 -> Date: Sat, 01 Feb 2020 16:40:05 GMT
18:40:05.414 -> Content-Type: text/html; charset=utf-8
18:40:05.447 -> Content-Length: 52
18:40:05.480 -> Connection: close
18:40:05.515 -> X-Top-SecreTTT: VG9vIGVhc3k/IElmIHlvdSBjYW4gcmVhZCB0aGlzLCBFbWFpbCB1cyBhdCBqb2JzK3NlY3JldEBpZnR0dC5jb20uIFdlIHdhbnQgTWFrZXJzLg==
18:40:05.619 -> Server: web_server
18:40:05.619 ->
18:40:05.619 -> Congratulations! You've fired the send_reading event
18:40:05.689 -> closing connection
18:40:07.007 -> Last Sleep: 1580574611
18:40:07.007 -> Time left: 594                 // NOTE (3)
18:40:07.041 -> Going to DeepSleep for [594] sec

```

Relevant code:

```
void sleepNOW(int sec2sleep = 2700)
{
  char tmsg[30];
  sprintf(tmsg, "Going to DeepSleep for [%d] sec", sec2sleep);
  Serial.println(tmsg);
  // mqtt_pubmsg(tmsg);
  Serial.flush();
  esp_sleep_enable_timer_wakeup(sec2sleep * uS_TO_S_FACTOR);
  esp_deep_sleep_start();
}
bool getTime()
{
  delay(200);
  if (getLocalTime(&timeinfo))
  {
    time(&now1);
    delay(200);
    return 1;
  }
  else
  {
    return 0;
  }
}

bool check_awake_ontime()
{
  getTime();
  if (timeinfo.tm_year >= 120) // year 2020
  {
    if (lastsleeptime != 0)
    { // not first boot
      long current_boottime = now1;
      int t_delta = now1 - calc_waketime;
      // int t_delta1 = TIME_TO_SLEEP * 60 - (t_delta + TIME_AWAKE);
      Serial.print("now is: ");
      Serial.println(now1);
      Serial.print("sleep time was: ");
      Serial.println(lastsleeptime);
      Serial.print("expected wake time: ");
      Serial.println(calc_waketime);

      Serial.print("total time delta: ");
      Serial.println(t_delta);
      if (t_delta >= 0)
      {
        Serial.println("OK - WOKE UP after due time: ");
        return 1;
      }
      else
      {
        Serial.println("FAIL- woke up before time: ");
        sleepNOW(-1 * t_delta);
        return 0;
      }
    }
    else
    {
      return 1;
    }
  }
  else
  {
    return 0;
  }
}

```

inside `setup()`

```
#if USE_WIFI
  if (startWifi())
  {
    mqttConnect();
    startNTP();
#if USE_SLEEP
    check_awake_ontime();   // PLEASE PAY ATTN ONLY THIS LINE
#endif
  }

```

inside `loop()`

```
#if USE_SLEEP
  if (millis() >= TIME_AWAKE * 1000)
  {
    getTime();

    Serial.print("Last Sleep: ");
    Serial.println(lastsleeptime);

    long clockCount = TIME_TO_SLEEP * 60 - (timeinfo.tm_min * 60 + timeinfo.tm_sec) % (TIME_TO_SLEEP * 60);
    // Serial.print(timeinfo.tm_hour);
    // Serial.print(":");
    // Serial.print(timeinfo.tm_min);
    // Serial.print(":");
    // Serial.print(timeinfo.tm_sec);
    // Serial.println("");
    Serial.print("Time left: ");
    Serial.println(clockCount);

    lastsleeptime = now1;
    calc_waketime = now1 + clockCount;

    sleepNOW(clockCount);
  }

```

I'm not posting entire code, but only relevant parts. Appreciate any help,

# Answer
As Juraj commented, a 2.5 \[sec\] delay, solved it, and NTP update was correct.
> 0 votes

---
Tags: esp32, sleep
---