body:
I've been trying to upload sketch to Arduino Nano clone (CH340G RS232 to USB converter). I have ArchLinux. My port is detected as /dev/ttyUSB0 (Official Arduino Uno is /dev/ttyACM0). After trying to upload a sketch avrdude responds with

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

or

    avrdude: stk500_getsync(): can't communicate with device: resp=0x88

After using verbose output it seems like it does not read from the arduino back to PC. I have all my permissions correct and everything was working to this date. I also used many arduinos which I also burned bootloader on using my Arduino Uno. Everything also works on seconds PC with Windows. Any ideas?

Linux log:

    /usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/jakub/.arduino15/packages -tools /usr/share/arduino/tools-builder -tools /home/jakub/.arduino15/packages -libraries /home/jakub/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path /tmp/arduino_build_539099 -warnings=all -build-cache /tmp/arduino_cache_182117 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avrdude.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /usr/share/arduino/examples/01.Basics/Blink/Blink.ino
    /usr/share/arduino/arduino-builder -compile -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/jakub/.arduino15/packages -tools /usr/share/arduino/tools-builder -tools /home/jakub/.arduino15/packages -libraries /home/jakub/Arduino/libraries -fqbn=arduino:avr:nano:cpu=atmega328 -vid-pid=1A86_7523 -ide-version=10809 -build-path /tmp/arduino_build_539099 -warnings=all -build-cache /tmp/arduino_cache_182117 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.arduinoOTA.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/home/jakub/.arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avrdude.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /usr/share/arduino/examples/01.Basics/Blink/Blink.ino
    Using board 'nano' from platform in folder: /home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2
    Using core 'arduino' from platform in folder: /home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2
    Detecting libraries used...
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /dev/null
    Generating function prototypes...
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /tmp/arduino_build_539099/preproc/ctags_target_for_gcc_minus_e.cpp
    /usr/bin/arduino-ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_539099/preproc/ctags_target_for_gcc_minus_e.cpp
    Kompilujem projekt...
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/cores/arduino -I/home/jakub/.arduino15/packages/arduino/hardware/avr/1.8.2/variants/eightanaloginputs /tmp/arduino_build_539099/sketch/Blink.ino.cpp -o /tmp/arduino_build_539099/sketch/Blink.ino.cpp.o
    Compiling libraries...
    Compiling core...
    Using precompiled core: /tmp/arduino_cache_182117/core/core_arduino_avr_nano_cpu_atmega328_6ffe6e1951fbeab8145453327f70df2d.a
    Linking everything together...
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-gcc -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/sketch/Blink.ino.cpp.o /tmp/arduino_build_539099/../arduino_cache_182117/core/core_arduino_avr_nano_cpu_atmega328_6ffe6e1951fbeab8145453327f70df2d.a -L/tmp/arduino_build_539099 -lm
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/Blink.ino.eep
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -R .eeprom /tmp/arduino_build_539099/Blink.ino.elf /tmp/arduino_build_539099/Blink.ino.hex
    /home/jakub/.arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-size -A /tmp/arduino_build_539099/Blink.ino.elf
    Projekt zaberá 924 bytov (3%) pamäte pre program. Maximum je 30720 bytov.
    Globálne premenné zaberajú 9 bytov (0%)  dynamickej pamäti, 2039 bytov zostáva pre lokálne premenné. Maximum je 2048 bytov.
    /home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b115200 -D -Uflash:w:/tmp/arduino_build_539099/Blink.ino.hex:i

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

         System wide configuration file is "/home/jakub/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/home/jakub/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

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

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

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
             Hardware Version: 4238814
             Firmware Version: 21984432.4
             Topcard         : Unknown

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

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

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

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
             Vtarget         : 0.0 V
             Varef           : 1992555.2 V
             Oscillator      : Off
             SCK period      : 0.1 us

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

    avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xfc
    avrdude: AVR device initialized and ready to accept instructions

    Reading |
    avrdude: arduino_read_sig_bytes(): (a) protocol error, expect=0x10, resp=0xfc
    avrdude: error reading signature data for part "ATmega328P", rc=-3
    avrdude: error reading signature data, rc=-3

    avrdude done.  Thank you.

Windows log:

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Adamko\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -ide-version=10807 -build-path C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804 -warnings=all -build-cache C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Adamko\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328 -ide-version=10807 -build-path C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804 -warnings=all -build-cache C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Program Files (x86)\Arduino\examples\01.Basics\Blink\Blink.ino
    Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    "C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    Kompilujem projekt...
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp" -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core: C:\Users\Adamko\AppData\Local\Temp\arduino_cache_611368\core\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a
    Linking everything together...
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804\\sketch\\Blink.ino.cpp.o" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/..\\arduino_cache_611368\\core\\core_arduino_avr_nano_cpu_atmega328_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804" -lm
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.eep"
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf" "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.hex"
    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\Adamko\\AppData\\Local\\Temp\\arduino_build_858804/Blink.ino.elf"
    Projekt zaberá 930 bytov (3%) pamäte pre program. Maximum je 30720 bytov.
    Globálne premenné zaberajú 9 bytov (0%)  dynamickej pamäti, 2039 bytov zostáva pre lokálne premenné. Maximum je 2048 bytov.
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:i

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

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

             Using Port                    : COM3
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 3
             Firmware Version: 4.4
             Vtarget         : 0.3 V
             Varef           : 0.3 V
             Oscillator      : 28.800 kHz
             SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: reading input file "C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex"
    avrdude: writing flash (930 bytes):

    Writing | ################################################## | 100% 0.16s

    avrdude: 930 bytes of flash written
    avrdude: verifying flash memory against C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:
    avrdude: load data flash data from input file C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex:
    avrdude: input file C:\Users\Adamko\AppData\Local\Temp\arduino_build_858804/Blink.ino.hex contains 930 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.12s

    avrdude: verifying ...
    avrdude: 930 bytes of flash verified

    avrdude done.  Thank you.

**UPDATE** Added the avrdude logs and command line.

title: Arduino Nano clone doesn't upload Linux

Answers: 2

body: I think you should try disconnecting any VCC port you have and see if it uploads if it does, after uploading the code reconnect the VCC ports again.

body:
The problem is in kernel ch341 driver. Using 5.3.3 on Archlinux and 5.6 rc1.

https://github.com/torvalds/linux/blob/e33eab9ded328ccc14308afa51b5be7cbe78d30b/drivers/usb/serial/ch341.c

This driver version compiled using this Makefile

    obj-m += ch341-m.o

    all:
      make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

    clean:
      make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

    reload: all
      sudo rmmod ch341-m ||true
      sudo insmod ./ch341-m.ko

Made it upload again. Hope it will be solved in kernel soon. I think the problem is addressed here

https://github.com/torvalds/linux/commit/35714565089e5e8b091c1155517b67e29118f09d#commitcomment-37154772

But the guy said it was solved in 5.6 rc1 which was not in my case.


body:
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?

title: program evaluating if clause incorrectly

Answers: 1

body:
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.


body:
can Arduino IDE point to a file in another directory? If yes how?
With my code

    ../../main.h

the compile fails.

Error:

    In file included from D:\Eigene Dateien\Entwicklung\SIGNALDuino_MR\src\arduino-ide\SIGNALDuino\SIGNALDuino.ino:1:0:

    main.h:1:1: error: expected unqualified-id before '.' token

     ../../main.h

     ^

    exit status 1
    expected unqualified-id before '.' token

--------------- structure ------------------

    TEST
      |--main.h
      |-----Ordner 1
                 |-----Ordner 3
                           |--files.h
      |-----Ordner 2
                 |-----Ordner 4

title: can Arduino IDE link to other libs / files in other directories?

Answers: 0


body:
So I am making a football playing robot which consists of 3 servo motors. Currently,i am only checking only a single servo(myservoKicker)which is operated via button in the blynk app and trying to read x and y values from joysticks in blynk. I am using wifi communication. I have seen that wifi.begin never properly starts as the serial.print("Blynk Connected") after it does not run, plus on my blynk app the project constantly connects and disconnects.
Note: The code for steering other servo's is not implemented yet and is just a stub.
Board: DoIt ESP32 Devkit V1 30 GPIO
Blynk: 0.6.1
myservoKicker connected to pin 13

    #include <ESP32Servo.h>
    #include <SPI.h>
    #include <Ethernet.h>
    #include <ETH.h>
    #include <WiFi.h>
    #include <WiFiAP.h>
    #include <WiFiClient.h>
    #include <WiFiGeneric.h>
    #include <WiFiMulti.h>
    #include <WiFiScan.h>
    #include <WiFiServer.h>
    #include <WiFiSTA.h>
    #include <WiFiType.h>
    #include <WiFiUdp.h>
    #include <BlynkSimpleEsp32.h>

    Servo myservoKICKER;
    Servo myservoLEFTWHEEL;
    Servo myservoRIGHTWHEEL;
    int pos;

    char auth[] = "9Itekdu3vf_B_3YmNxxHu9G3Bs_1IWs9";
    char ssid[] = "RO IMRAN RO";
    char pass[] = "xxxxxxxxxxx";
    char localserver[16]= "192.168.1.1";
    BLYNK_WRITE(V1)
    {
        int xAxis = param[0].asInt();
        int yAxis = param[1].asInt();

        // Do something with x and y
        Serial.print("X = ");
        Serial.print(xAxis);
        Serial.print("; Y = ");
        Serial.println(yAxis);

    }
    BLYNK_WRITE(V4){                                        //WHEEL CALIBRATION
        int WheelCalibration=param.asInt();
        if(WheelCalibration == 1)
        {
            myservoLEFTWHEEL.attach(26);
            myservoRIGHTWHEEL.attach(27);
            delay(100);
            myservoLEFTWHEEL.write (90);
            myservoRIGHTWHEEL.write (90);
            delay(30000);

        }
    }
    BLYNK_WRITE(V5){                                        //KICKER 90 DEGREE CALIBRATION
        int KickerCalibration= param.asInt();
        if(KickerCalibration == 1)
        {
            myservoKICKER.attach(13);
            delay(100);
            myservoKICKER.write (90);
            delay(200);

        }
    }

    void setup(){
        // Attach servos to pins
        myservoLEFTWHEEL.attach(26);                        //1
        myservoRIGHTWHEEL.attach(27);                       //2
        myservoKICKER.attach(13);                           //3

        // detach servos to avoid jitter on power up
        myservoLEFTWHEEL.detach();
        myservoRIGHTWHEEL.detach();
        myservoKICKER.detach();

        Serial.begin(115200);
        delay(10);
        Serial.print("Connecting to ");
        Serial.println(ssid);
        WiFi.begin(ssid,pass);
        int wifi_ctr = 0;
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }
        Serial.println("WiFi connected");
        Blynk.begin("9Itekdu3vf_B_3YmNxxHu9G3Bs_1IWs9",ssid,pass);
        Serial.println("Blynk connected");
    }

    void loop()
    {
        Blynk.run();
    }

title: Esp32(Arduino Core) + Blynk Wifi Connection Problems

Answers: 0


body:
I am using the DS3231 RTC connected to an Arduino UNO R3 for a project. I won’t go into detail, but I need to save power, therefore I am using the DS3231 Alarm Interrupt to wake the Arduino from sleep. The Alarm Interrupt works fine when the Arduino is sleeping and connected to the 5V and GND pins of the Arduino, however it turns out that the DS3231 won’t fire a square wave interrupt when on battery power. **In order to turn it on, I need to set bit 7 of the Control Register (0Eh) to logic 1, and bit 6 to logic one.** I can’t find any documentation on how to do this, except for a few forums talking about it. What is the specific code to do this, and where would I place the code?

DS3231 Data Sheet (Control Register on p.13)

``` c++
#include <Wire.h>
#include <RTClibExtended.h>
#include <LowPower.h>

#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ledPin 13    //use arduino on-board led for indicating sleep or wakeup status

RTC_DS3231 RTC;      //we are using the DS3231 RTC

byte AlarmFlag = 0;
byte ledStatus = 1;

//-------------------------------------------------

void wakeUp()        // here the interrupt is handled after wakeup
{
}

//------------------------------------------------------------

void setup() {
  //digitalWrite(wakePin,HIGH);
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);

  //switch-on the on-board led for 1 second for indicating that the sketch is ok and running
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  delay(1000);

  //Initialize communication with the clock
  Wire.begin();
  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));   //set RTC date and time to COMPILE time

  //clear any pending alarms
  RTC.armAlarm(1, false);
  RTC.clearAlarm(1);
  RTC.alarmInterrupt(1, false);
  RTC.armAlarm(2, false);
  RTC.clearAlarm(2);
  RTC.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to Arduino D2 pin for wake-up
  RTC.writeSqwPinMode(DS3231_OFF);

  //Set alarm1 every day at 18:33
  RTC.setAlarm(ALM1_MATCH_HOURS, 16, 19, 0);   //set your wake-up time here
  RTC.alarmInterrupt(1, true);
}

//------------------------------------------------------------

void loop() {

  //On first loop we enter the sleep mode
  if (AlarmFlag == 0) {
    attachInterrupt(0, wakeUp, LOW);                       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    digitalWrite(ledPin, LOW);                             //switch-off the led for indicating that we enter the sleep mode
    ledStatus = 0;                                         //set the led status accordingly
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up

    //When exiting the sleep mode we clear the alarm
    RTC.armAlarm(1, false);
    RTC.clearAlarm(1);
    RTC.alarmInterrupt(1, false);
    AlarmFlag++;
  }

  //cycles the led to indicate that we are no more in sleep mode
  if (ledStatus == 0) {
    ledStatus = 1;
    digitalWrite(ledPin, HIGH);
  }
  else {
    ledStatus = 0;
    digitalWrite(ledPin, LOW);
  }

  delay(500);
}

```
Also, how would I set it to go to sleep after the alarm?

Thanks!

P.s sorry about that Thomas, I'm a bit new here.

title: How to Set the Control Register on the DS3231 RTC module for Arduino UNO R3?

Answers: 1

body:
I took a look at the [FabioCuomo-DS3231 library][RTClibExtended], as I
guess that is what you are using, and I saw nothing related to setting
those two bits. However, you can take inspiration from the code in the
library to implement the functionality yourself.

I would try this:

```c++
void enableAlarmInLowPower(void) {
    // Read the control register.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.endTransmission();
    Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1);
    uint8_t value = Wire.read();
    Wire.endTransmission();

    // Update it.
    value |= bit(6) | bit(7);  // set bits 6 and 7

    // Write it back.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.write(value);
    Wire.endTransmission();
}
```

Warning: not tested.

[RTClibExtended]: https://github.com/FabioCuomo/FabioCuomo-DS3231


body:
i am completely new to hardware programming and micro controllers and i am unable to figure out what search-engine search-term to use to find the answer i am looking for.

# the project
i am working on a project that will use an arduino to control the opening and closing of a window; in a shed. the project i am trying to achieve is further described [here](https://robotics.stackexchange.com/questions/20046/28byj-48-gear-cog-attachment-guidance?noredirect=1#comment33027_20046).

# the question
i want to know what are the limitations of wire length in an arduino project and what do i need to have to be able to extend that wire length capacity?

i currently have those "common" 20cm wires you get off ebay... which i dont think will be long enough.

title: Arduino Connect Long Wires/Cables

Answers: 2

body:
The stepper motor 28byj-48 seems to be a 5V motor ([datasheet](https://components101.com/sites/default/files/component_datasheet/28byj48-step-motor-datasheet.pdf)). I've seen it being used with a [A3967 driver](https://www.sparkfun.com/datasheets/Robotics/A3967.pdf), which means that it does not draw more than 750 mA of current.

I'll go with the length you mentioned in the comments:

> for this example lets say 3m

The rest is Physics: the resistance of a wire is

    R = p * l/A

where l is the length of the wire and A is the area (dependent on the diameter).

A [voltage drop calculator](https://www.calculator.net/voltage-drop-calculator.html?material=copper&wiresize=1079&voltage=5&phase=dc&noofconductor=1&distance=3&distanceunit=meters&amperes=0.75&x=50&y=22) can now tell you how much voltage is left at the end of the wire.

I would have estimated a 0.75 mm² (AWG 18), but you might even be fine with 0.5mm² (AWG 20) according to the calculator. But: better safe than sorry.

----

Also from the comments:

> i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements)

A stepper motor needs a totally different setup than a servo. The servo is connected with simple 4 pins, the stepper needs a motor driver (H-bridge). Connecting the stepper motor directly to the Arduino may destroy your board.

body: Wire length is hard to define. It depends if it is in your case powering a motor or has control signals connected directly to the Arduino. Take a good look at the answer provided by Thomas Weller, by sizing the wire appropriately you can get extremely long lines for motors and other types of loads, you have some voltage to work with. The wires connected to the Arduino are also antennas and can pick up a lot of nasties in a very short run, especially around motors. These antennas on the inputs are high impedance making them more sensitive to noise. Regardless of which wires you are looking at they need to be properly conditioned for your environment and application.


body:
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:
<!-- language-all: lang-cpp -->

    #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);
      }
    }

title: Thermocouple and multimeter

Answers: 1

body:
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:

[![Code folded][1]][1]

____

Edit:

After you linked to [the schematics](http://www.circuitbasics.com/arduino-ohm-meter/), 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]: https://i.stack.imgur.com/JTLCD.png


body:
I have two Arduinos: one is transferring on its output pin to other Arduino's input_pullup low or high signal depend on servo action (rotating/stop).

I need an action on slave Arduino with dfmini player: actually I need a code with which mp3 sample is triggered on slave Arduino.

servo rotates -output pin goes low = sample is played just once until servo reaches desired position

servo stopped -output pin goes high = sample stops

solving this issue will be really helpful for my project.

here is example code

tnx.

    ***************************************************
      DFPlayer - A Mini MP3 Player For Arduino
      <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

     ***************************************************
      This example shows the basic function of library for DFPlayer.

      Created 2016-12-07
      By [Angelo qiao](Angelo.qiao@dfrobot.com)

      GNU Lesser General Public License.
      See <http://www.gnu.org/licenses/> for details.
      All above must be included in any redistribution
     ****************************************************/

    /***********Notice and Trouble shooting***************
      1.Connection and Diagram can be found here
      <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
      2.This code is tested on Arduino Uno, Leonardo, Mega boards.
     ****************************************************/

    #include "Arduino.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"
    #define pin 2 // connect to master digital output "pin"

    SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);

    void setup()
    {
     mySoftwareSerial.begin(9600);
     Serial.begin(115200);
     pinMode(2,INPUT_PULLUP);

     Serial.println();
     Serial.println(F("DFRobot DFPlayer Mini Demo"));
     Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

     if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
       Serial.println(F("Unable to begin:"));
       Serial.println(F("1.Please recheck the connection!"));
       Serial.println(F("2.Please insert the SD card!"));
       while (true);
     }
     Serial.println(F("DFPlayer Mini online."));

     myDFPlayer.volume(15);  //Set volume value. From 0 to 30
    }

    void loop(){
      if (digitalRead(2)==LOW) myDFPlayer.play(1); // 5 sec mp3 sample, turn on , then debounce or return ?

    }

    }

wiring scheme
[![enter image description here][1]][1]

[![enter image description here][2]][2]

output cobmination on master arduino
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/leBJz.jpg
  [2]: https://i.stack.imgur.com/YZDr9.png
  [3]: https://i.stack.imgur.com/O1UDy.jpg

title: mp3 trigger, output to antoher input, no switch

Answers: 0


body:
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

title: ESP8266, sporadically no write access to the file system

Answers: 1

body:
I have faced the same issue with my [water leak detector][1], based on esp8266. It was caused by [memory leak][2] 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]: https://github.com/BG4444/waterLeakDetector
  [2]: https://github.com/esp8266/Arduino/issues/4497


body:
i am using ModbusRtu.h library for modbus protocol. it works for sending data from master to  slave but it can not send data from slave to master.

master code:

    #include <ModbusRtu.h>
      #define SERIAL_BUFFER_SIZE 64
    // data array for modbus network sharing
    uint16_t au16data[26];
    uint8_t u8state;

    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  port : serial port
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus master(0,Serial1,8); // this is master and RS-232 or USB-FTDI

    /**
     * This is an structe which contains a query to an slave device
     */
    modbus_t telegram;

    unsigned long u32wait;

    void setup() {
      Serial1.begin( 19200 ); // baud-rate at 19200
      Serial.begin( 19200 ); // baud-rate at 19200
    //  master.start();
     master.begin();
      master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
      u32wait = millis() + 1000;
      u8state = 0;
    }

    void loop() {

        telegram.u8id = 2; // slave address
        telegram.u8fct = 3 ; // function code (this one is registers read)3
        telegram.u16RegAdd = 0; // start address in slave 1     slave array index 0 dhora
        telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read 4  //master array er koyta(not start from 0) value show korba
        telegram.au16reg = au16data; // pointer to a memory array in the Arduino
        int x = master.poll(); // check incoming messages
        Serial.print("x: ");
        Serial.println(x);
                    if (master.getState() == COM_IDLE)
                    {
                       master.query( telegram ); // send query (only once)

                    }
    Serial.print("Recieve: ");
          for (int i = 0; i < 5; i += 1)
          {
            Serial.print(au16data[i]);
            Serial.print(",");
          }
          Serial.println("");
    }

slave code:

    #include <ModbusRtu.h>
    #define SERIAL_BUFFER_SIZE 64
    // data array for modbus network sharing
    //uint16_t au16data[26] = {
    //  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };
    uint16_t au16data[26] = {4,17,89};
    int led = 13;
    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  port : serial port
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus slave(2,Serial1,8); // this is slave @1 and RS-232 or USB-FTDI

    void setup() {
      Serial1.begin( 19200 ); // baud-rate at 19200
      Serial.begin( 19200 ); // baud-rate at 19200
      pinMode(led, OUTPUT);
      slave.begin();
      //slave.start();
    }

    void loop() {

      slave.poll( au16data, 26 );

       Serial.print("Recieve: ");
          for (int i = 0; i < 5; i += 1)
          {
            Serial.print(au16data[i]);
            Serial.print(",");
            if(au16data[3] == 1)
            {
              digitalWrite(led, HIGH);
             // Serial.println("in");
            }
             if(au16data[3] == 2)
            {
               digitalWrite(led, LOW);
               //Serial.println("else");
            }
          }
             Serial.println("");

           memset(au16data, 0, 26 * sizeof(uint16_t)); // recieveLargeArray = {}
    }

title: can ModbusRtu.h library send data from slave to master using modbus(RS485) module?

Answers: 0


body:
I've created a simple transmitter with an **HC-12** and an *Arduino Nano* (clone), where I send the values of *DHT11* and *LM35* sensors to a receiver unit made only of a *Wemos D1* and another **HC-12**.

Setup is really simple and worked fine for a couple of days (transmitter in the cellar 2 floors down, receiver in my living room, it was POSTing data to my own server correctly), then I unplugged the receiver and modified the transmitter to add a JSON library; when I plugged them back again the receiver is not getting anything anymore.
Transmitter seems to be working fine, at least it prints the number of bytes written in the Serial Monitor.

I tried:

 * reverting back to the working version (no JSON), but still the same
 * tested each of the HC12 modules with a simple test code and AT commands, they all responds and are all set to factory configuration, like it was before actually (AT+DEFAULT)
 * made another receiver with an Arduino Uno and a lcd screen - a setup that I was successfully using before changing to the Wemos. Strangely, now this setup doesn't work too...
 * Switched the modules and what I got? The transmitter still transmits, the receiver doesn't receive, nothing changed.
* Tried sending a simple string "Test", still no results.

Relevant code:

Transmitter:
```
#include <ArduinoJson.h>
#include <DHT_U.h>            // just Adafruit Library
#include <DHT.h>
#include <SoftwareSerial.h>
#define DHTTYPE DHT11   // DHT 11
SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin
int DHTPIN = 4;
int LMPIN = 5;
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<80> doc;

void setup() {
  analogReference(INTERNAL);
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  dht.begin();
}

void loop() {
  delay(5000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int reading = analogRead(LMPIN);
  float lmt = reading/9.31;
  doc["dht_h"] = h;
  doc["dht_t"] = t;
  doc["ds_t"] = lmt;
  char result[50];
  serializeJson(doc, result);
  Serial.println(result);
  int written = HC12.print(result);
  Serial.println(written);    // it's 39 chars
}
```
Receiver (all wifi sections are removed):

```
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#define STASSID "....."
#define STAPSK  "....."
SoftwareSerial HC12(D13, D15); // HC-12 TX Pin, HC-12 RX Pin

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "...........";
const uint16_t port = 3000;

void setup() {
  Serial.begin(9600);
  HC12.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500); Serial.print(".");
  }
}

void loop() {

  String content = HC12.readString();
  Serial.println(content);
  if(content.length()) {
    // This will send a string to the server
    Serial.println("sending data to server");
    if (client.connected()) {
      //....
    }
  }
  delay(1000);
}
```

I'm pretty stumped by the fact that it stopped working, and that both the HC-12 modules seem to be working fine (at least they respond to all the AT commands).
I even tried purging arduino from the system and reinstalling (I now have the very latest IDE release) but nothing....

Am I missing something obvious? (I've a weak electronic background, I'm a web developer by trade).
Is there a way to check if data is actually sent?
How can I debug these modules?

title: HC-12 modules stopped receiving, cannot understand why

Answers: 1

body:
For what it's worth, I manage to make them working again by playing a bit with the settings of both modules.

Using a simple test sketch I issued some AT commands to both modules; I had already tried setting them to the DEFAULT setup with AT+DEFAULT, but that was fruitless. I decided to left the mode as is (FU3), same for the serial rate (B9600), but I tried switching channel so I set both modules with AT+C002.

That did the trick, maybe was some sort of external interference, or a lack of precision in the channel settings - I just know that's a week now they've been communicating just fine and that's what matters.

So, if they fail to communicate, first try to adjust their settings, don't assume the DEFAULT ones are surely working.


body:
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;
      }

title: Running a robot with 2 front-facing sensors, but it's stuttering

Answers: 1

body:
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();
            }
        }
    }


body:
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.

title: Components required to control the Speed of Wilo Para AC Synchronous Motor

Answers: 2

body:
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](https://2-improve.com/wp-content/uploads/2016/02/Datasheet-Yonos-PARA-ST-7-0-iPWM2_August-2015.pdf) 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:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/u67aE.png)

<!-- End schematic -->

body:
Page 6 of this [doc][1] explains, what is iPWM and its electrical characteristics.

[![Manual page][2]][2]

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

  [1]: https://2-improve.com/wp-content/uploads/2016/02/Datasheet-Yonos-PARA-ST-7-0-iPWM2_August-2015.pdf
  [2]: https://i.stack.imgur.com/eAAPM.png


body:
I am having an issue with the a 4×4 keypad. It usually works fine but sometimes the keypad stops reacting or no key is pressed but it still shows a random keypress on the LCD. The only solution is to unplug and plug again. I thought it may be the length of the wires for the keypad. I uses 3 ft wires from the keypad to the Arduino. Has anyone faced similar issues?
[![Diagram][1]][1]
[![Picture1][2]][2]
[![Keypad][3]][3]

  [1]: https://i.stack.imgur.com/i9S60.jpg
  [2]: https://i.stack.imgur.com/rKvtV.jpg
  [3]: https://i.stack.imgur.com/X4jzN.jpg

title: 4x4 keypad stops reacting

Answers: 0


body:
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][1] and the [Feather board][2]

  [1]: https://www.adafruit.com/product/1734
  [2]: https://learn.adafruit.com/adafruit-feather-huzzah-esp8266

title: Neopixel code not working on Adafruit Feather board

Answers: 1

body:
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.


body:
i'm trying to create a system that arduino and esp-1 send an GET request each 2 secs to a server and depend on server reply turns a LED on or off . system works good for 6-7 hours but stops after one day . actually i  checked server logs after one day and i realized no request is sending to serve .
my hardware :
Arduino Uno
ESP-1
LED or Relay

and my arduino codes : ( in know my host is not working now . i turned it off )

    #include <ArduinoJson.h>
    #include <WiFiEsp.h>
    #include <WiFiEspClient.h>
    #include <SoftwareSerial.h>

    SoftwareSerial Serial1(10,11);

    char ssid[] = "AZaz";            // your network SSID (name)
    char pass[] = "Az8833394";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status
    int Relay = 13;

    char server[] = "azimi.ir";
    unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 1000L; // delay between updates, in milliseconds
    WiFiEspClient client;

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

      pinMode(Relay, OUTPUT);
      Serial.begin(115200);
      Serial1.begin(9600);
      WiFi.init(&Serial1);
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println(F("WiFi shield not present"));
        // don't continue
        while (true);
      }

      while ( status != WL_CONNECTED) {
        Serial.print(F("Attempting to connect to WPA SSID: "));
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println(F("You're connected to the network"));
    //  printWifiStatus();
    }

    void loop() {
      while (client.available()) {
      char c = client.read();
      char endOfHeaders[] = "\r\n\r\n";
      if (!client.find(endOfHeaders)) {
        Serial.println(F("Invalid response"));
        return;
      }
      const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 80;
      DynamicJsonDocument doc(capacity);
      DeserializationError error = deserializeJson(doc, client);
      if (error) {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.c_str());
        return;
      }
          int count = doc["counts"];
          if(count == 1){
            int relay = doc["message"];
            int cmd = doc["val"];
            digitalWrite(relay , cmd);
          }

      }
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();

      }
    }

    void httpRequest()
    {

      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        client.println(F("GET /check/ HTTP/1.1"));
        client.println(F("Host: azimi.ir"));
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection
        Serial.println(F("Connection failed"));
      }
    }

now i have some questions :

1- why system stops working after more hours ? what is the problem ? my codes or my hardware ?

2- if problem is my hardware , what kind of wifi module or arduino you think will work ?

3- i want this project to make someone else's home . it will be a long term project so i want my system works for one or two years at least . is arduino suitable for this kind of projects ?! if its not , what hardware is ?

title: arduino and esp-1 stop workign after 1 day running

Answers: 0


body:
Coming from JS, I find it very difficult to program Arduino in C++ *(not even knowing which version or what features are supported)*, being bound to the `loop` and `delay`, not being able to (easily) use anonymous functions in parameters or async code.

I know JS isn't natively supported by Arduino, but I know languages can be transpiled.

I have seen many solutions, so just to pick few:
[JohnnyFive J5][1], which runs via cable on a host PC,
[NectarJS][2] with their `arduino-uno` target,
or [andrei-markeev/ts2c][3] which converts ES3 to C89.

Each of them come with their own limitations and it's very difficult to find the right without prior experience with IoT. Did anyone walk this path already and found a viable solution?

  [1]: http://johnny-five.io
  [2]: https://github.com/NectarJS/nectarjs
  [3]: https://github.com/andrei-markeev/ts2c

title: Is it possible to program Arduino in transpiled JavaScript?

Answers: 3

body:
Even if such a transpiler exists (which I don‘t know) you will still have to deal with the `loop` structure and the fact that you should avoid using `delay`s. On a microcontroller you have to forget about things like multithreading and even dynamic memory allocation should be used carefully.
Most of those things that make a programmer‘s life easy on bigger systems are usually paid with ram or cpu power, but on a microcontroller with some kB RAM there are only few resources to pay with.

So my recommendation is to learn C++ instead of looking for ways to convert code from another language, which will probably introduce its own problems. You‘ll soon find yourself one layer below and there are exciting things that higher languages hide from you.

body:
Why don't you just start with a microcontroller that supports Javascript?

I find the Adafruit Circuit Playground Express quite fun to work with. You can still connect sensors and other hardware, the same as you can do with Arduino. It also has a bunch of sensors built-in.

You can try it out right now without owning a hardware board at adafruit.makecode.com. Click the Javascript tab on the top of the page.

Using a JS>Arduino transpiler will probably cause a lot of headache, since it often won't do what you expect it to do.

body:
andrei-markeev/ts2c JavaScript/TypeScript to C transpiler looks promising.

I'll probably give it a go tonight.

### According to the github page:

Produces readable C89 code from JS/TS code.

For example, this JavaScript:
```
console.log("Hello world!");
```

transpiles to the following C code:
```
#include <stdio.h>

int main() {
    printf("Hello world!\n");
    return 0;
}
```

src: https://github.com/andrei-markeev/ts2c


body:
    DC motor: 3-6v
    Servo sg90: 3-7.2v
    Esp 8266 01: 3.3v

I have 2 Arduino Uno both has their own ac-dc power adapter.
Lets say, 1st Arduino is `Ard1` and 2nd is `Ard2`.

The `Ard1` communicates to a web server (BLYNK) with Esp 01.

Using I2C, `Ard1` sends command to `Ard2` to power/move the DC motor/Servo.

So far, **it has no problem operating with Servo**. But,

Whenever the `Ard1` commands the `Ard2` to power the DC motor.

Right when the DC motor runs(using `digitalWrite(motor,HIGH)`) the Esp 01 resets.

- - -

 - Tried using `analogWrite(motor, 102)` though it won't reset instantly, prolong usage randomly resets it anytime.

 - I also tried to test operating Servo and DC motor simultaneously in `Ard2` using Serial commands, without I2C/Esp01. There was no problem at all, both works flawlessly.

Below is the diagram of the wiring.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/h4a8c.png

title: ESP8266-01 Resetting when DC motor runs

Answers: 1

body: Can you clear one thing that you are giving power to dc motor from 5v pin given on Arduino board or from your ac to dc power supply. If you are giving power to the motor from 5v pin of Arduino Uno then there is a high possibility that the motor is not getting sufficient current because 5v supply on Arduino comes from onboard lm1117 5v voltage regulator and cheap clon Arduino has a cheap regulator with less than 1amp capacity.


body:
I thought of the idea of using the WS2312B LED strip to drive a custom 7-Segment display. The project will require a large number of these displays, and driving them with a single Arduino (I'm thinking of an Arduino MEGA). For driving the LEDs I am using the FastLED library.

[![(2 different 7-Segment displays; and that is the letter E)][1]][1]

I wrote some code that drives a single display, It works, but I think It's possible to make it simpler, the code I wrote stores the digits in arrays, and uses these arrays in functions customized to each digit. here is an example:

    //Digit Arrays:
    byte digit0[]     = {0,1,2,3,4,5};
    byte digit1[]     = {1,2};
    byte digit2[]     = {0,1,3,4,6};
    byte digit3[]     = {0,1,2,3,6};
    byte digit4[]     = {1,2,5,6};
    byte digit5[]     = {0,2,3,5,6};
    byte digit6[]     = {0,2,3,4,5,6};
    byte digit7[]     = {0,1,2};
    byte digit8[]     = {0,1,2,3,4,5,6};
    byte digit9[]     = {0,1,2,3,5,6};

The functions are something like this:

    void AllOff(){
    //Switch off All the LEDs in the segment. Should be off for 1 second
      for(int i=0; i<7; i++){
        leds[i] = CRGB::Black;
        FastLED.show();
      }
      //delay(1000);
    }
    void AllOn(CRGB myColor){
      //Switch on All the LEDs in the segment (should display 8)
      //The color of choice is #1E78A0
      for(int i=0; i<7; i++){
        leds[i] = CRGB (30,120,160);
        FastLED.show();
      }
      delay(1000);
    }
    void Print0(CRGB myColor){
      //Prints the digit 0:
      AllOff();
      ArraySize = sizeof(digit0);     //get the size of the array
      for(int i=0; i<ArraySize; i++){
        LED_Number  = digit0[i];      //get the LED number from the array
        leds[LED_Number]    = CRGB (myColor);  //Switch the LED on
        FastLED.show();
      }
    }

When I call it in the code, I simply do something like this:

    Print0(CRGB::Purple);
    delay(500);

I have tried for the best part of the past two days to find a better way to go about this, but I couldn't. What I'm thinking is perhaps to create a function that would store all the digits instead of storing every one as an array, and then call it maybe within a for loop? something like

    for(int i=0; i<10; i++){
        displaydigit[i];
        FastLED.show();
      }

Do you know of any library that has something similar, or perhaps any idea on how to achieve this?

Your assistance, as always, is greatly appreciated.

Thank You.

  [1]: https://i.stack.imgur.com/KKpi0.png

title: 7-Segment Display with WS2312B and FastLED

Answers: 2

body:
First, for all the digits I'd use an 7 value array, indicating for every segment if it's ON or OFF. So for `0` your get `byte digit0[] = {1,1,1,1,1,1,0}`, where `1` indicates the segment is ON, and `0` indicates it's OFF. Your code then becomes:

    void Print0(CRGB myColor){
      //Prints the digit 0:
      for(int i=0; i<7; i++){
        if( digit0[i] )
          leds[i] = CRGB (myColor);  //Switch the LED on
        else
          leds[i] = CRGB::Black; // Switch the LED off
      }
      FastLED.show();
    }

The next step would be to create a two dimensional array containing which segments are on for which digits.

    byte digits[10][7] = {
         {1,1,1,1,1,1,0} //0
        ,{0,1,1,0,0,0,0} //1
        ,{1,1,0,1,1,0,1} //2
        ,{1,1,1,1,0,0,1} //3
        ,{0,1,1,0,0,1,1} //4
        ,{1,0,1,1,0,1,1} //5
        ,{1,0,1,1,1,1,1} //6
        ,{1,1,1,0,0,0,0} //7
        ,{1,1,1,1,1,1,1} //8
        ,{1,1,1,1,0,1,1} //9
       }

Now you can generalize you Print0 function to accept any number:

    void PrintNumber(byte number, CRGB myColor){
      if( number>9 )
        return;
      for(int i=0; i<7; i++){
        if( digit[number][i] )
          leds[i] = CRGB (myColor);  //Switch the LED on
        else
          leds[i] = CRGB::Black; // Switch the LED off
      }
      FastLED.show();
    }

Call the new function in your `loop`; for example `PrintNumber(3, CRGB:White);`

If you want to put multiple 7-segment displays in series, you could add and `offset` argument to the PrintNumber function, and use `leds[i+offset]` instead. Then call the PrintNumber with offset 0 for the first digit/display, 7 for the second, 14 for the third, and so on.

body:
In general, in many engineering efforts, a definition of the feature(s) and constraints need to be considered.  The feature you are creating is a large-7-segment-display.  Now decide what constraints you are working under.  Normally, in embedded programming, this means limited memory, limited power and interacting with people.

Because of limited memory, consider storing 7-segment patterns in a condensed form.  Also consider creating the simplest code possible.  Usually the more data is compressed, the more complex the code needs to be.  If there is a large amount of data (for example, an [mp3 compressed][1] sound track) the cost of high compression and complex code can be justified.  But storing 7-segment patters is comparatively simple.  So, consider expanding the array to include all 7 segments for each of the 10 digits.  Store if each segment is on or off.  Then, remove the "all on" and "all off" loops in your code leaving only one loop to read the array and turn off or on each segment.

Adapting the project to facilitate interacting with people can be confusing and difficult.  Possibly the most common problem with displays are delays and flicker.  For this project choosing the WS* line of LEDs should mitigate flicker problems (at the very least it takes it out of your hands) as the [PWM][2] feature is the responsibility of each WS* chip. People have been putting up with (expect) small delays when viewing large displays.  And it is expected this approach could update perhaps 10 digits in less than hundreds of milliseconds.

  [1]: https://en.wikipedia.org/wiki/MP3
  [2]: https://en.wikipedia.org/wiki/Pulse-width_modulation


body:
I'm trying to create a deepSleep class for my ESP32 project, but I get this error : `section attribute not allowed for 'clock_beforeSleep'` The only place it compiles, is outside the class.

How should I declare it ?

**EDIT1**: Add Code

    #include "EEPROM.h"
    #include "time.h"
    #include "WiFi.h"

    RTC_DATA_ATTR long clock_expectedWake = 0;
    RTC_DATA_ATTR int bootCounter = 0;
    RTC_DATA_ATTR int driftRTC = 0;
    RTC_DATA_ATTR long clock_beforeSleep = 0;

    class esp32Sleep
    {
    #define EEPROM_SIZE 16
    #define DEV_NAME "ESP32lite"
    #define uS_TO_S_FACTOR 1000000ULL /* Conversion micro seconds to seconds */

    private:
      char sleepstr[250];
      // RTC_DATA_ATTR long clock_expectedWake = 0;
    .
    .
    .

title: Can't create a RTC_DATA_ATTR var inside a class

Answers: 2

body:
You can't put an `RTC_DATA_ATTR` qualified variable inside a class because the class is stored in normal RAM. The `RTC_DATA_ATTR` qualified variable is, by definition, stored in RTC RAM.

The definition of `RTC_DATA_ATTR` includes a `section` attribute (`__attribute__((section(".rtc.data")))`) that tells the compiler where abouts in memory the variable should be stored (in this case the 8kiB of "slow" RTC memory). That is mutually exclusive with where the compiler decides to store the class.

It's like you have a diamond necklace which the has to be kept in a safe at all times, but you want to wear it around your neck *whilst at the same time storing it in the safe*. You can't do it.

body:
I think some explanation about the different allocation schemes could be
useful:

* Global variables, as well as static locals and static class members,
  are allocated at build time, by the linker, typically in the .data or
  .bss section of the program.
* Local variables are allocated at run time in the stack. Typically the
  compiler issues some instructions to adjust the stack pointer in order
  to make room for the variable. As an optimization, the most used
  locals can be stored directly in CPU registers, but this optimization
  is disabled if you use the address of the variable.
* Variables created with `new` and `malloc()` are allocated at run time
  in the heap. This allocation is handled by a support library.

Note that objects are variables and are allocated in one piece, just
like a C `struct`. Static class members are not part of the class
instances.

Now, some build chains have extensions that allow you to store
statically allocated variables elsewhere than the RAM. One example is
the `PROGMEM` storage on AVR. `RTC_DATA_ATTR` sounds like a similar
extension. You may be able to store a regular class member this way if:

1. The object is global and stored as `RTC_DATA_ATTR` as a whole.
2. It doesn't need a constructor.


body:
I was hoping anyone could help me with my problem.

I am trying to play a sequence of tones without using delay. So I am relying on millis(). However I have not been successful yet and after reading multiple tutorials about using millis(), I could not find one that covers sequencies of events.
What I am trying to do is the following:

- Play a tone1 for 1 s
- After 1 second (duration which tone 1 is played) play tone 2
- After 1 second (duration which tone 2 is played) play tone 3
- After 1 second (duration which tone 3 is played) play tone 4

With the current code I have, everything seems to be played at the same time and not really considering my IF statements.

Code:
<!-- language-all: lang-cpp -->

    #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 speakerPin = 3;

     #define N_BUTTONS 8

    int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13}; // Putting button_pins into an array

    int Pitches[N_BUTTONS] = {0}; // Define array to hold the pitch. Setting it to 0.

    long Durations[N_BUTTONS]; // Define array to hold the duration of the note. Setting it to 500.

    unsigned long startMillis;
    unsigned long startMillis_2;
    unsigned long startMillis_3;
    unsigned long startMillis_4;
    unsigned long currentMillis;
    unsigned long period = 1000;

    void setup() {

    Serial.begin(9600);

    for(int pin : button_pins) pinMode(pin, INPUT); // Define the input pins for button_pins

    startMillis = millis();

    }

    void loop() {

    for (int button=0; button<N_BUTTONS ; button++){
      if(digitalRead(button_pins[button])){
        Pitches[button] = analogRead(A0)/13;   // As we have 77 pitches we divide the max Potentiometer value by 77. This equals 13.
        Durations[button] = analogRead(A1)*4;
       }
      }
    ////////////////////OUTPUT CODE////////////////////Sound generation code /////////////////////////////////

    unsigned long currentMillis = millis(); // Gets the current time

    if (currentMillis - startMillis >= period)  // Start event after 1 second
      {
      tone(speakerPin, notes[Pitches[0]], period);
      Serial.print("pitch1= ");
      Serial.println(Pitches[0]);
      Serial.print("duration1= ");
      Serial.println(period);
      Serial.print("millis = ");
      Serial.println(currentMillis);
      startMillis_2 = currentMillis;   // Saves the current time into the variable
      Serial.print("startMillis_2 = ");
      Serial.println(startMillis_2);
      }

    if (currentMillis - startMillis_2 >= period)
      {
      tone(speakerPin, notes[Pitches[1]], period);
      Serial.print("pitch2= ");
      Serial.println(Pitches[1]);
      Serial.print("duration2= ");
      Serial.println(period);
      startMillis_3 = currentMillis;
      Serial.print("millis = ");
      Serial.println(currentMillis);
      Serial.print("startMillis_3 = ");
      Serial.println(startMillis_3);
      }

    if (currentMillis - startMillis_3>= period)
      {
      tone(speakerPin, notes[Pitches[2]], period);
      Serial.print("pitch3= ");
      Serial.println(Pitches[2]);
      Serial.print("duration3= ");
      Serial.println(period);
      startMillis_4 = currentMillis;
      Serial.print("millis = ");
      Serial.println(currentMillis);
      Serial.print("startMillis_4 = ");
      Serial.println(startMillis_4);
      }

    unsigned long startMillis_4;

    if (currentMillis - startMillis_4 >= period)
      {
      tone(speakerPin, notes[Pitches[3]], period);
      Serial.print("pitch4= ");
      Serial.println(Pitches[3]);
      Serial.print("duration4= ");
      Serial.println(period);
      startMillis = currentMillis;
      Serial.print("millis = ");
      Serial.println(currentMillis);
      Serial.print("startMillis = ");
      Serial.println(startMillis);
      }

    }

---

I have managed to get my code running on delay. It is working but I am very limited on what I can accomplish if I want more.
I have read through all answers and comments but was still unable to get a millis() solution since my main problem was how to get tone 2 started and so on. I can get the first tone to play on a loop and correct intervals, but I am not understanding how to trigger the start of tone 2.
Here is my code with delay. If anyone has can guide me to use millis() specially to trigger the start the tone 2, it would be very helpful.

EDIT. New Code:

    #include "pitches.h"

    int notes[]={
    0,
    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 speakerPin = 3;

    #define N_BUTTONS 8

    // Input variables definitions

    int button_pins[N_BUTTONS] = {6, 7, 8, 9, 10, 11, 12, 13}; // Putting button_pins into an array

    int Pitches[N_BUTTONS] = {0}; // Define array to hold the pitch. Setting it to 0.

    long Durations[N_BUTTONS]; // Define array to hold the duration of the note. Setting it to 500.

    void setup() {

    Serial.begin(9600);

    for(int pin : button_pins) pinMode(pin, INPUT); // Define the input pins for button_pins

    }

    void loop() {
    int tempo = analogRead(A2);
    for (int button=0; button<N_BUTTONS ; button++){
      if(digitalRead(button_pins[button])){
        Pitches[button] = analogRead(A0)/13;   // As we have 78 pitches we divide the max Potentiometer value by 77. This equals 13.
        Durations[button] = (analogRead(A1)*4) + tempo;
       }
      }
    ////////////////////OUTPUT CODE////////////////////Sound generation code /////////////////////////////////
      for (int button=0; button <N_BUTTONS ; button++){
      tone(speakerPin, notes[Pitches[button]], Durations[button]);
      delay(tempo);
      Serial.print("Pitch");
      Serial.print(button);
      Serial.print(" = ");
      Serial.println(Pitches[button]);
      Serial.print("Duration");
      Serial.print(button);
      Serial.print(" = ");
      Serial.println(Durations[button]);
      Serial.println(tempo);
      }
    }

title: Using millis() to create a timed sequence of events

Answers: 2

body:
Your code falls through (skips over) the first “if” statement in the output code because its time period has not yet passed.

It then starts to use startMillis_2, which is not yet initialized (and may be any value), in the next “if”.

Initialization of startMillis_2 only happens inside the first “if” statement but that code has not yet been executed.

The same goes for startMillis_3 and 4.

But I think there’s something more fundamentally wrong with your code. You execute all “if” statements inside of a loop that is continuously repeated. There is no sequence. You have to make sure that tone 2 can only be started after tone 1, etcetera.

body:
You are overcomplicating the program. There is no point in remembering
when each of the notes started. You just have to remember:

* what note is currently playing
* when you started playing this note

Then the logic of `loop()` becomes simply: “if we are done with the
current note, then start playing the next one.” In code:

**Edit**: Changed the code to include your button-scanning loop.

```c++
int current_button;
uint32_t note_started;

void loop() {
    // Adjust the notes on button presses.
    for (int button = 0; button < N_BUTTONS; button++) {
        if (digitalRead(button_pins[button])) {
            // As we have 78 pitches we divide the max Potentiometer
            // value by 77. This equals 13.
            Pitches[button] = analogRead(A0)/13;
            Durations[button] = analogRead(A1)*4;
        }
    }

    // Are we done with the current note?
    uint32_t now = millis();
    int tempo = analogRead(A2);
    if (now - note_started >= Durations[current_button] + tempo) {

        // Then move to the next note.
        ++current_button;

        // Finished the tune?
        if (current_button == N_BUTTONS) {
            current_button = 0;  // then restart from the beginning
        }

        // Play the note.
        tone(speakerPin,
                Pitches[current_button], Durations[current_button]);

        // Take note of when this started.
        note_started = now;
    }
}
```