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

What's a Wilo Motor? Links to datasheets please.

@Majenko As far from my knowledge Wilo is a smart AC Synchronous Motor. https://wilo.cdn.mediamid.com/cdndoc/wilo164576/1544113/wilo164576.pdf

This is the link of the datasheet and on page number 34 is my WILO Para Motor and the model name is Wilo Para 25-180/9-87/IPWM1 in the table

Pretty useless datasheet that. It doesn't contain any real information. I hate when companies do that. But one thing I did glean: the phrase used in the datasheet is "0-10V or PWM". The PWM is probably a TTL compatible input, so LOW is 0V and HIGH is >2V. The 0-10V is something completely different.

@Majenko Yes this was the datasheet I  got from the WILO heat pump website. Now I need a component to send the control signal from ESP32 to the Motor.

If it is just a TTL input then you don't need a "component" - the ESP32 can just drive it direct.

@Majenko But I don't think it is TTL input. I just want to send the analog PWM input signal based on the temperature set on the Nextion HMI. For example, If I am setting the room temperature as 25 degrees in Nextion HMI then the control signal should be passed to Motor to run at a particular speed to pump the water to the heater to obtain a room temperature set point.

There is no such thing as an "analog PWM" signal. PWM is digital, not analog.

@AbhishekhAaron, where did you get the current draw specification of 3 A to 87 A ?

@jsotola I am sorry guys the maximum output power required is 0.66 Ampere

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

I will try and I will let you know.

Sorry, but you are wrong. Wilo explains about their iPWM signal in doc. Lowest voltage is 3.6 volt, not 2, it's greather, than ESP32 VCC.

@gbg Can you reference a page number? I scoured that document looking for that information but it's such a terrible document I failed.

https://2-improve.com/wp-content/uploads/2016/02/Datasheet-Yonos-PARA-ST-7-0-iPWM2_August-2015.pdf
page 6
See my answer

No wonder I couldn't find the info - that's a completely different document.

@gbg Thanks for that info. I have updated my answer accordingly.

@AbhishekhAaron Note: important update in my answer now new information has come to light.

@Majenko I saw it and thanks for your help.

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).

Thanks for the information

Lowest voltage for iPWM is 3.6 volt, so, you need the voltage amplifier.

Yes, the lowest voltage for iPWM required is 3.6 Volt. But the problem is I am not getting the exact information of my motor model Wilo Para 25-180/9-87/IPWM1

You don't need this. Wilo refers to its standard, the iPWM. So, any Wilo device, that use iPWM, will use the same electrical characteristics for it.

Thank you so much


text:
Arduino Nano clone doesn't upload Linux
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.

Comments are not for extended discussion; this conversation has been moved to chat.

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.

I get make[2]: *** No rule to make target '/home/jrs/Builds/ch341-driver/ch341-m.o', needed by '__build'.  Stop. How does that Makefile work, what prerequisites do you have to have in place?

Makefile is a build configuration file. If you download the link I provided (the first one) and save it with a name "ch341-m" which is said in the mamefile, to the same directory you can use "make" and "make reload" you should have ch341 driver installed. For more questions move to chat in the question comment. Thank you.

Got it working now by downloading the whole kernel source, copying the file you linked to into drivers/usb/serial and following https://wiki.archlinux.org/index.php/Compile_kernel_module. Thank you for the quick answer!

Happy to help :)

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.

Comments are not for extended discussion; this conversation has been moved to chat.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Which board to select in PlatformIO for ESP Wroom 32?
I'm quite new in this microcontroller topic and my next step is to make use of a wlan module, which is a ESP WROOM 32.
As IDE I'm using Visual Studio + PlatformIO and I can't figure out how to access the module. Atm I use these parameters:
[env:esp12e]
platform = espressif8266
board = esp12e
framework = arduino
monitor_speed = 74880

but I receive:
(...)
CURRENT: upload_protocol = esptool
Looking for upload port...
Auto-detected: /dev/ttyUSB0
Uploading .pio/build/esp12e/firmware.bin
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting......
Chip is ESP8266EX
Features: WiFi
WARNING: Detected crystal freq 20.45MHz is quite different to normalized freq 26MHz. Unsupported crystal in use?
Crystal is 26MHz
MAC: 00:08:ff:00:00:00
Uploading stub...
Running stub...

A fatal error occurred: Invalid head of packet (0x46)
*** [upload] Error 2
============================================================================= [FAILED] Took 3.27 seconds =============================================================================
The terminal process "platformio 'run', '--target', 'upload'" terminated with exit code: 1.

edit:
The ESP WROOM 32 is a NodeMCU 32 and the board config now is:
[env:espwroom32]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200

and to check if everything works:
void setup() {
  pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(2, HIGH);
  delay(1000);
  digitalWrite(2, LOW);
  delay(1000);
}

I also had problems that I received Failed to connect to ESP32: Timed out waiting for packet header nevertheless but here is a nicely explained workaround for that. Solution is, either you hold the BOOT button pressed while uploading the code or you sold a capacitor to specific pins on the board.
I just tried to hold the boot button and it's blinking now. Finally :)
I'm sure, a lot of further issues are only waiting on the way ^

The ESP WROOM32 is an ESP32, not an ESP8266. You have PlatformIO configured for an ESP8266, specifically the ESP12e, and there's no way that's going to work.
You'll want something more along these lines:
[env:espwroom32]
platform = espressif32

To choose the board - if you're using a breakout board, you'll need to be more specific about it - what model is it? ESP WROOM32 is just the name of the CPU module; PlatformIO needs to know the size of the flash storage in order to upload properly. Your link is to the entire Espressif ESP32 site. Otherwise, look through PlatformIO's list of ESP32 boards and find one that matches the amount of flash storage your board has.
You might want to read PlatformIO's ESP32 documentation.

Thanks a lot! I knew it was wrong..  after some hours :) I'm not using a breakout board. How can I figure out the board I have? I can only see what's written on it: fcc id 2ac72 esp wroom 32. Does that reveal something?

Just from the look I'd say it is a Node MCU. In platformio it is given as "NodeMCU-32S" but when I want to use it, it says it is an unknown board. ESP32 is apparently also an unknown board..

it is definitely this one: https://www.reichelt.de/nodemcu-esp32-wifi-und-bluetooth-modul-debo-jt-esp32-p219897.html

Looks like you got it!

Yeah, that was quite an effort just to get started.. :) But it is almost always the same, doesn't matter which electronics or programming..

btw, is there a certain site for all microcontroller related questions? I wonder that there is arduino and raspberry pie, but what about all the electronics around it and other microcontrollers like a stm32 and so on?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?
I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.
So I’m using DS1302 for the clock, and FastLED for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.
But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).
Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output
#include <FastLED.h>
#include <DS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

// Init the DS1302 - stops LEDs working
DS1302 rtc(2, 3, 4);

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  for (int i=0; i<NUM_LEDS;i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();
  delay(100);
}

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?
I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.
Edit: inserted sketch which demonstrates the issue

Don’t have access to actual code at the moment, the above hopefully is a minimum working example to demo the issue, also the light sequence is fairly complex and arbitrary, so at this stage just want to find any way of getting both rtc and leds operating at same time

Do you ever try to switch pin 3 to 9?

That DS1302 library you point to is very old. Did you try using a more recent library like the one from Richard C. Miller that can be installed from the Arduino IDE?

There are more precise RTC modules (DS3231) using I2C, which is supported by hardware: won't affect FastLED timing.

I installed a library from within the IDE as StarCat suggested.
https://github.com/Makuna/Rtc
#include <FastLED.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

ThreeWire myWire(3,4,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

CRGB leds[NUM_LEDS];

void setup() {
   FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
   Rtc.Begin();
}

void loop() {
   RtcDateTime dt = Rtc.GetDateTime();

   for (int i=0; i<NUM_LEDS;i++) {
     leds[i] = CRGB::Red;
   }

FastLED.show();
delay(100);
}

I am able to get and use the time, and the LED output works.


text:
How to use AT+CFTRANTX command in SIM7100
I am working on a project using pro mini 8MHz/3.3v and SIM7100, I want to know how can I used AT+CFTRANTX command. I am try to read file from EFS and write to SD card via Serial port. I have get some data in SD but is junk.
My board is Arduino Pro Mini (ATMega 328) 8MHz/3.3 V datasheet (DEV-11114) and Modem is home-made board with SIM7100 module, already test board and module work with all functions without any problem. I’ve added a schematic of the board to the question.
Here is SIM7100 Schematic

Here is SD Module, Pro Mini and SIM7100 pin layout

c:\data2.txt is: A1 to F0
A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6B7B8B9B0C1C2C3C4C5C6C7C8C9C0D1D2D3D4D5D6D7D8D9D0E1E2E3E4E5E6E7E8E9E0F1F2F3F4F5F6F7F8F9F0
Any help would be appropriated.
The code that I am using, I tried it with every possible baud rate:
#include <SPI.h>
#include <SD.h>
#include <SoftwareSerial.h>
SoftwareSerial simSerial(7, 6);
File myFile;

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

  simSerial.begin(9600);
  Serial.print("\nInitializing SD card...");

  if (!SD.begin(10)) {
    Serial.println("\nInitialization failed!");
    while (1);
  }
  Serial.println("\nInitialization done.");
  delay(8000); //For booting SIM7100
  if (SD.exists("1.TXT")) SD.remove("1.TXT");

  myFile = SD.open("1.txt", FILE_WRITE);
  if (myFile) {
    simSerial.println("AT+CFTRANTX=\"c:/data.txt\"");
    while (simSerial.available() > 0) {
      byte voc = simSerial.read();
      myFile.write(voc);
    }
    myFile.close();
    // Serial.println("\nClose done.");
  } else {
    // Serial.println("Error opening 1.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("1.txt");
  if (myFile) {
    Serial.println("1.txt:");
    while (myFile.available()) {
      Serial.print(myFile.read());
    }
    myFile.close();
    Serial.println("\nReading SD Card done.");
  } else {
    Serial.println("Error opening 1.txt");
  }

}

void loop() {

}

Here is test sketch for software & hardware serial.
SoftwareSerial mySerial(7,6); // RX, TX

void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Hardware Serial port!");
  mySerial.begin(9600);
  mySerial.println("AT+CFTRANTX=\"c:/data.txt\"");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Please attach a description/diagram what is attached where. And is the SD-card-reader part of a Sim7100 shield or extra. If shield which make and type. if extra partswhich parts. And how do you want to write to C:/data.txt on the PC? Make a problem statement what you want to do in logical steps

The "data.txt" coming to EFS via ftp from server, and i want to send this file to SD-card.

The Manual v1.02 of Sim7100 with all the commands can be downloaded here
Here is code to test it compiled for UNO without warnings and errors: Please test it and give feedback (read the comments to get the flow of code) Test with  the RX/TX of the Sim7100 to pins 4/5 (Software Serial and the Sim7100 to baud rate 9600):
#include <SPI.h>
#include <SD.h>

#include <SoftwareSerial.h>

#define SD_ChipSelectPin 10

SoftwareSerial simSerial(5, 6); // RX, TX to TX RX of the SIM7100 module
//#define simSerial Serial
char receiveArray[256] = {'\0'};
void readSerialPort(uint8_t);
uint8_t counter = 0;

void setup() {
   Serial.begin(57600);
    while (!Serial) {
     ;
    }
  simSerial.begin(9600); // using HW Serial on a Pro Mini
  while (!simSerial) {
    ;
  }

  simSerial.println("AT+IPR=9600"); // set sim7100 to same serial speed
  delay(1000);
  simSerial.flush();   // Flush buffer

  SD.begin(SD_ChipSelectPin);
  if (!SD.begin(SD_ChipSelectPin)) {
    //Serial.println("Error opening SD-card");
    return;
  }
  delay(1000);
  if (SD.exists("1.TXT")) SD.remove("1.TXT");
  delay(1000);
}

void loop() {

  if (counter < 3) {
    File saveFile = SD.open("1.TXT", FILE_WRITE);
    if (saveFile) {
      // This has to be the Serial the SIM7100 is attached to
      simSerial.println("AT+CFTRANTX=\"c:/data.txt\"\r");
      while (!simSerial.available()) {} // wait for data to arrive

        readSerialPort(0);

      saveFile.close();

      // Serial.println("Success creating file");
    } else {
      // Serial.println("Error creating file");
    }
    counter++;
  }
}

/* For a first test we print everything to 1.txt -
  there will be "garbagge" as the AT response in it -
  we can "clean" in a later  by using the intermediate array or the counter */
void readSerialPort(uint8_t startIndex = 0) {
  uint16_t i = 0;   // counter and we want later to filter the first X chars
  while (simSerial.available() > 0) {
    char inChar = simSerial.read();
    if (i >= startIndex) { // if we want to filter the first 16 chars it would be i>=16 (as it starts with 0)
      if (inChar == '\n') {
        receiveArray[i] = '\0'; // terminate the array
        return;
      }
      if (inChar != '\r') {
        receiveArray[i] = inChar;
        i++;
      }
    }
  }
}

The code waits now for the modem to respond

Tried the code is return blank SD Card.

I have rewiring my board and change my data file as above and test the way @ TisteAndii  guide me in code above, I got right data in Serial  with AT+CFTRANTX="c:/data.txt, but get junk like 000000000062480198616224 on SD Card. My hardware setup and wiring okay now, maybe i help again get he right format on SD Card.

Can you post the last working code in your question? Of course I'll help you

I already update codes and sample data2.txt, i have change from 1 to 100, to A1A2 up to F9F0, I was looking at how change my data format on SD, I have test with char and byte nothing change much. but I am sure wiring and SoftwareSerial (7, 6) working correct now.

use my function readSerialPort() from my answer and the according changes to the program (define char array, change loop)

I done as you said, but nothing change and my SD Crad is shows empty 1.txt.

When having trouble in getting started with a modem, it's usually best to connect to the modem in "interactive mode", to verify that you're sending the right commands and getting the right responses.
Have you made sure that your modem/module's UART is at the right logic level to interface directly with your Pro Mini? How about the supply voltage? (Post a link to the product). If you're done with all that, then connect only the modem to the Pro Mini:
5V/3.3V -> Vcc (depending on the module's supply voltage)
D6 -> Modem TX
D7 -> Modem RX
Gnd -> Gnd

Then, upload the following to your Pro Mini:
#include <SoftwareSerial.h>

SoftwareSerial fserial(6, 7);

void setup(void)
{
    Serial.begin(57600);
    // I assume this is the default for your modem
    fserial.begin(115200);
    Serial.println("Starting.");
}

void loop(void)
{
    while (fserial.available())
        Serial.write(fserial.read());
    while (Serial.available())
        fserial.write(Serial.read());
}

This should basically transfer everything you send from your Serial Monitor to the modem, and in the reverse, transfer everything the modem sends to your Serial Monitor.
After uploading the sketch, in the Serial Monitor, set the Line Ending at the bottom to Carriage Return. Then you can first send the simple AT and should receive OK from the modem, to confirm that your setup works. Then to test your file reading code, send your command AT+CFTRANTX="c:/data.txt" and see what you get.
If you can confirm this works, writing code to do this automatically should then be much clearer. Or at the very least, you'll have ruled out a whole bunch of possible problems.
(Note: the Arduino may not work reliably with 115200 baud on Software Serial. So you may want to change the modem's baud rate quickly with AT+IPREX=9600. And then modify your sketch accordingly and re-upload.)

@AliMorawej What baud rate do you see when you enter AT+IPR?? Does your command AT+CFTRANTX work from the serial monitor?

@AliMorawej What did you modify exactly? The baud rate?

@AliMorawej So you can now read the data.txt using this test sketch to send the command?

Yes, read on SIM7100 the AT command without any problem, but when I write it to SD is missed up the data, write data A1A2A3...F9F0, and get on SD something like 000000000062480198616224 change data type char and byte nothing get better ...


text:
How to write & read from SPIFFS file as object data on ESP8266
I am trying write four digit number to SPIFFS file, and read that four digit from SPIFFS file and display on seven segment.
The code, I am writing as below, I got "0" on each segment, but if manually make number = 4567; then seven segment show proper number on every segment.
Please help me to learn more about how to read & write and convert to object data.
Here is my code;
#include <FS.h>

const char* filename = "/InputInt.txt";
int digit_1 = 0;
int digit_2 = 0;
int digit_3 = 0;
int digit_4 = 0;

int Anode_1 = 16;
int Anode_2 = 14;
int Anode_3 = 5;
int Anode_4 = 4;
int count = 0;
int digits[4] ;
int AnodePins[4] = {4, 5, 14, 16};

int clockPin = 12;
int latchPin = 13;
int dataPin = 15;

int number = 0; //declear the variables

byte numbers[10] {B00000011, B10011111, B00100101, B00001101, B10011001, B01001001, B01000001, B00011111, B00000001, B00001001};

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

  bool success = SPIFFS.begin();

  if (!success) {
    Serial.println("Error mounting the file system");
    return;
  }
  SPIFFS.format();
  File fw = SPIFFS.open(filename, "w");

  if (!fw) {
    Serial.println("Error opening file for writing");
    return;
  }
  char Written = fw.print("1234");

  if (Written == 0) {
    Serial.println("File write failed");
    return;
  }
  fw.close();

  pinMode(Anode_1, OUTPUT);
  pinMode(Anode_2, OUTPUT);
  pinMode(Anode_3, OUTPUT);
  pinMode(Anode_4, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

} //End of setup

void loop() {
  int i;
  File fr = SPIFFS.open(filename, "r");

  if (!fr) {
    Serial.println("Failed to open file for reading");
    return;
  }

  for (i = 0; i < 4; i++) {
    byte number = (Serial.write(fr.read()));
  }
  fr.close();
  break_number(number);
  display_number();
  delay(3000);
} // End of loop

// seperate the input number into 4 single digits
void break_number(int num) {
  Serial.println("");
  digit_1 = num / 1000;
  digits[0] = digit_1;
  Serial.print(" Digit_1: ");
  Serial.println(digit_1);
  int dig_1_remove = num - (digit_1 * 1000);

  digit_2 = dig_1_remove / 100;
  digits[1] = digit_2;
  Serial.print(" Digit_2: ");
  Serial.println(digit_2);
  int dig_2_remove = dig_1_remove - (digit_2 * 100);

  digit_3 = dig_2_remove / 10;
  digits[2] = digit_3;
  Serial.print(" Digit_3: ");
  Serial.println(digit_3);
  digit_4 = dig_2_remove - (digit_3 * 10);

  digits[3] = digit_4;
  Serial.print(" Digit_4: ");
  Serial.println(digit_4);
}

void display_number() {                                             //scanning
  digitalWrite(AnodePins[count], HIGH);                            //turn on the relevent digit
  digitalWrite(latchPin, LOW);                                      //put the shift register to read
  shiftOut(dataPin, clockPin, LSBFIRST, numbers[digits[count]]);    //send the data
  digitalWrite(latchPin, HIGH);                                     //put the shift register to write mode
  delay(0);
  digitalWrite(AnodePins[count], LOW);                            //turn on the relevent digit
  count++;                                                          //count up the digit
  if (count == 4) {                                                 // keep the count between 0-3
    count = 0;
  }
}

Here is the result;
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0
1234
 Digit_1: 0
 Digit_2: 0
 Digit_3: 0
 Digit_4: 0

Thanks,

I directly see 3 problems with your code:

Serial.write() will not return the written data, but the number of send bytes. This means that in your for loop you are only assigning the written number of bytes to the variable, not the data. But I guess you want to display the actual data, which was read from the file. You should assign the return value of fr.read() to a variable. Then you can send it via Serial.write() and still use that variable for other things later (like displaying).

You need to look into variable scope. You have a global variable number. But in the for loop you are defining a local variable with the same name via
 byte number = ...

This variable is only valid in that specific for loop iteration. When the iteration ends, the variable is thrown away and redeclared in the next iteration. It will not be there anymore, when you leave the for loop. So currently you are saving your data in a variable local to the for loop. It does NOT touch the global variable. Thus the other functions only see the value zero, with which the global variable number was initialized. You can remove the type byte before the variable in the for loop. That makes it an assignment instead of a definition. Thus then you really write the data into the global variable.

Data encoding: Clearly you have your number in the file as ASCII encoded text. But you seem to handle it as binary data. That cannot work. For example: When you read the first character of 1234 (which is written in the file), then you get '1' (the character, not the number). When looking at an ASCII table you can see, that this character corresponds to a decimal number of 49 (or 0x31 in hex). You can convert an ASCII encoded digit to a real number by subtracting the value of the character '0':
 int number = fr.read() - '0';

or
 int number = fr.read() - 48;

(both are equivalent).
Also you are currently just saving the read character into a single variable. That means, that after the for loop only the last character is left. Since this is a composite number, you should do something to compose it. Like this:
 number = 0;
 int factor = 1000;
 for(int i = 0; i<4; i++){
     number += (fr.read() - '0') * factor;
     factor /= 10;
 }

Note: This is untested, it is not the best way, but the easiest at this point, and it only works for numbers between 1000 and 9999 (4 digit numbers). You can implement this more versatile.
First we are resetting the number variable, so that old values are not getting in our way. We are using a variable holding the current factor (starting with 1000, since that is the figure in which the first digit lies). Then we go through the 4 characters, reading them. We subtract the character '0' (as described above) and then multiply by the factor. That resulting number is added to the variable number. Then we divide the factor by 10 (getting from 1000 to 100, then to 10 and finally to 1). At the end we can use number like any other integer variable.

Alternative implementation of reading the number, which is suitable for different numbers of digits:
number = 0;
// Prepare character buffer to read the number in
char buffer[10] = ""; // space for maximum 9 digits
int pos = 0; // position variable in the buffer
while(fr.available() && pos < 9){ // loop while there is data left to read in the file or we have no pace left in buffer (leaving one character for the terminating null character
    char c = fr.read(); // read character into variable
    if(isDigit(c)){
        buffer[pos] = c; // save digit in buffer
        pos++; // increment position for the next character
    } else {
       break; // break out of loop, if read character is not a digit (we don't want to read further when a non-digit character comes up)
    }
}
buffer[pos] = 0; // terminate buffer with null character
number = atoi(buffer); // use standard function to convert to integer number

Note:

This code is not tested, though it compiles without errors
You see, that it is not smaller, than the other one, but can handle different number of digits.
You can still use the first version with smaller numbers, if you always pad them with zeros. So instead 991 you would write 0991 to the file. That will make the first version work.

Thanks Chrisl, I have edit the way you mention, it'sworking well now, you are absolutely right.

Please let me know, how to keep number as four digit (OCT), number is 1000 and minute 4 should display 0996, but display 9911.

Sorry, I don't quite understand. Please explain more clearly

Ok, write number 1008 into file, then read it correct in display, I add some code in loop the final number = number -4; and display number again, start correct from 1008, 1004, 1000, and go to 9911 instead of 0996.

You almost certainly don't pad the number with zeros to 4 digits, when writing it to the file. As I wrote, that will break the code snippet. I added another way of reading the number, which also supports other digit numbers.


text:
Print 2 numbers stored in 24-bits in decimal format
An implementation function from the nice little Wiegand library YetAnotherArduinoWiegandLibrary prints a hexadecimal representation of a facility # & card # (8-bit facility #, 16-bit card #) — 24 bits of a 26-bit stream that comes across the wire.
Example encoded 24-bit number: 7111097 (decimal). Hex equivalent: 6C81B9. The 6C portion is the facility # (decimal: 108). 81B9 is card # (decimal 33209).
This function from the library's example usage serial prints the hexadecimal format of the number:
void receivedData(uint8_t* data, uint8_t bits, const char* message) {
    Serial.print(message);
    Serial.print(bits);
    Serial.print("bits / ");
    //Print value in HEX
    uint8_t bytes = (bits+7)/8;
    for (int i=0; i<bytes; i++) {
        Serial.print(data[i] >> 4, 16);  //1st, 3rd, 5th hex digit
        Serial.print(data[i] & 0xF, 16); //2nd, 4th, 6th hex digit
    }
    Serial.println();
}

What I've tried to do unsuccessfully so far is to loop over the bits to also serial print the two decimal formatted numbers (facility:card) in the final output form:  108:33209

why do you need to loop over bits? ... the for loop already manipulates bytes of data

@jsotola With or without a for loop how do you output the two separate logical numbers in decimal format?

how do you convert 3 bytes to a single number? .... think about this ... what mathematical process do you follow to convert 4 hundreds , 6 tens and 8 units to 468?

I wonder why that sample code prints each nibble of a byte separately? Doesn't Serial.print(255, 16); output FF? So couldn't the inside of the for loop just read Serial.print(data[i], 16);

Your code loops from the high order byte to the low order byte, printing each byte as 2 hex digits.
If you want instead to print the first byte as a decimal value, and then the remaining bytes as another decimal value, then do this:
Print byte 0 in base 10:
    Serial.print(data[0]);  //first byte
    Serial.print(":");

Then loop through the remaining bytes, building a result as a decimal value, and print that:
unsigned long total = 0;
for (int i=1; i<bytes; i++) //Skip the first byte
{
    total = total << 8;  //Shift the previous total by 8 bits.
                         //(The same as multiplying by 256, but faster)
    total += data[i];    //Add in the new value
}
Serial.println(total);

The sample code you posted is written to handle a variable number of bytes. The code above does the same thing with decimal results. It's much simpler if you know you will always have 3 bytes or 4 bytes:
For 3 bytes:
    Serial.print(data[0]);  //first byte
    Serial.print(":");
    long total = long(data[1])*256 + data[2]);
    Serial.println(long(total);

I wrote the second version of the code using long ints, since I started out with printing an 8-bit value followed by a 24 bit value. If the second value is only 2 bytes (16 bits) you could change the data type to unsigned int

This is great and makes sense of it for me, thank you.


text:
serial problem with python to arduino
when i execute the python script, the arduino response but the code between the if(Serial.available()) not responding.
python script
 import  time, serial
 arduino = serial.Serial('COM7', 9600)
 time.sleep(2)
 while True:
    arduino.write(str(input("1")))                  # write position to serial port
    # and the pysthon script cant read the code below this line
    reachedPos = str(arduino.readline())            # read serial port for arduino echo
    data.append(reachedPos)
    arduino.close()

arduino script
 #include <Servo.h>
 Servo servo;
 int angle = 0;
 String in;
 int pos = 1;

void setup() {
 servo.attach(7);
 Serial.begin(9600);
 servo.write(0);

}

void loop() {
if(Serial.available())  // if data available in serial port
{
in = Serial.readStringUntil('\n');
Serial.print(in);
pos = in.toInt();
  if(pos == 1){
if(angle == 0){
  servo.write(180);
  delay(10);
  angle = 180;
  delay(1000);
}

if(angle == 180){
  servo.write(0);
  delay(10);
  angle = 0;
  delay(1000);
}}
}
}

What is the problem?
Te arduino code works fine

You're reading up until a \n, but you're never sending a \n - so you end up receiving until a timeout. That consumes everything in the buffer. 2. You then look to see if there's something available. There isn't. You've consumed it all.

i have the same problem when i use Serial.read()

You mean you read everything, and then you look to see if something is available? Of course that will never work. You need to rethink your whole strategy.


text:
Sending MIDI CC to multiple midi Channel
Hi so i would like to send CC messages to different MIDI Channel (volume control). The CC messages are coming from one knob.
The solution i found kind of work but i'm pretty sure is not ideal and seems to introduce drift or lag: the volume isn't getting the same value from one channel to another.
My question is: is there a better way to do it than what i have done.
I use and tweak the following exemple provided in the Teensy Exemple library "USB MIDI AnalogControlChange Example"
The exemple was using this line of code to send CC (controlChange) to a specific channel:
MIDI.sendControlChange(controlNumber, controlValue, channel);
As i wanted to have multiple target channels for the third parameter i tried things like this:
MIDI.sendControlChange(controlNumber, controlValue, 1-2-3);
or
MIDI.sendControlChange(controlNumber, controlValue, (1,2,3));
or
MIDI.sendControlChange(controlNumber, controlValue, 1+2+3);
But it didn't worked. I didn't find in the documentation if this parameter could accept more than one number.
What worked is to multiply analog read of the same knob and multiply the sent message. It's not elegant (i'm new to programing of course) but also i noticed i strange latency or drift if you will: the volume of the channel did went from 0 to full volume but the one on channel 2 didn't go to zero, so the purpose failed. The idea here is to have all the midi channels (1 to 8) but the 11 to be affected by the volume knob.
Hope you can help, in advance, thanks
    /* USB MIDI AnalogControlChange Example

   You must select MIDI from the "Tools > USB Type" menu
   http://www.pjrc.com/teensy/td_midi.html

   This example code is in the public domain.
*/

#include <Bounce.h>

// the MIDI channel number to send messages
const int channel = 11;

// the MIDI continuous controller for each analog input
const int controllerA9 = 1; // param 1
const int controllerA8 = 2; // param 2
const int controllerA7 = 3; // cutoff
const int controllerA6 = 4; // reso
const int controllerA5 = 16; // volume (for channel 11)
const int controllerA4 = 16; // volume (for other channels exept 11

void setup() {

}

// store previously sent values, to detect changes
int previousA9 = -1;
int previousA8 = -1;
int previousA7 = -1;
int previousA6 = -1;
int previousA5 = -1;
int previousA4 = -1;

elapsedMillis msec = 0;

void loop() {
  // only check the analog inputs 50 times per second,
  // to prevent a flood of MIDI messages
  if (msec >= 20) {
    msec = 0;
    int n0 = analogRead(A9) / 8;
    int n1 = analogRead(A8) / 8;
    int n2 = analogRead(A7) / 8;
    int n3 = analogRead(A6) / 8;
    int n4 = analogRead(A5) / 8;
    int n5 = analogRead(A4) / 8;
    int n6 = analogRead(A4) / 8; //i duplicated this to be able to have a different channel target
    // only transmit MIDI messages if analog input changed
    if (n0 != previousA9) {
      usbMIDI.sendControlChange(controllerA9, n0, channel);
      previousA9 = n0;
    }
    if (n1 != previousA8) {
      usbMIDI.sendControlChange(controllerA8, n1, channel);
      previousA8 = n1;
    }
    if (n2 != previousA7) {
      usbMIDI.sendControlChange(controllerA7, n2, channel);
      previousA7 = n2;
    }
    if (n3 != previousA6) {
      usbMIDI.sendControlChange(controllerA6, n3, channel);
      previousA6 = n3;
    }
    if (n4 != previousA5) {
      usbMIDI.sendControlChange(controllerA5, n4, channel);
      previousA5 = n4;
    }

    if (n5 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n5, 1);
      previousA4 = n5;
    } // 1 here is the channel who's different from the int channel = 11

     if (n6 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n6, 2);
      previousA4 = n6;
    } // 2 here is the channel who's different from the int channel = 11

  }

  // MIDI Controllers should discard incoming MIDI messages.
  // http://forum.pjrc.com/threads/24179-Teensy-3-Ableton-Analog-CC-causes-midi-crash
  while (usbMIDI.read()) {
    // ignore incoming messages
  }
}

A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:
usbMIDI.sendControlChange(controllerAx, nx, 0);
usbMIDI.sendControlChange(controllerAx, nx, 1);
usbMIDI.sendControlChange(controllerAx, nx, 2);
usbMIDI.sendControlChange(controllerAx, nx, 3);
...

And this should of course be done in a loop:
for (int c = 0; c < 16; c++)
    if (c != 10)
        usbMIDI.sendControlChange(controllerAx, nx, c);

Thanks a lot for your answer.
I'll try both of your solution.
On your loop exemple C is getting all the channel between 0 to 16 except the channel 10 right ?

Thanks again, it behave as expected like that:
  `if (n5 != previousA4) {
          for (int c = 1; c < 8; c++){
              usbMIDI.sendControlChange(controllerA4, n5, c);
            }
          previousA4 = n5;
        }`


text:
Arduino GPIO automatically turns high
I've been trying to turn on 21W bulb with Protected MOSFETS.
But somehow the bulbs are getting high automatically from arduino.
I've tried all the hardware related things like pull down with different resistors, but no luck.
Is it possible due to separate ground of controller and Switch?
Because Switch and bulbs are powered through SMPS of 12V 10A while Arduino through Laptop USB cable.
Used this protected mosfet, circuit as given on page no 50 of datasheet.
Following is the code I used.
#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 5;
int OUT4 = 7;
int OUT5 = 6;
int count = 0;

void setup() {
 pinMode(IN0, INPUT);
 pinMode(IN1, INPUT);
 pinMode(OUT1, OUTPUT);
 pinMode(OUT2, OUTPUT);
 pinMode(OUT3, OUTPUT);
 pinMode(OUT4, OUTPUT);
 pinMode(LED, OUTPUT);
 digitalWrite(OUT3, LOW);
 Timer1.initialize(1000000);
 Serial.begin(9600);

}

//void flash_R()
//{
//  digitalWrite(LED, !digitalRead(LED));
//  digitalWrite(OUT3, !digitalRead(OUT3));
//  //digitalWrite(OUT4, !digitalRead(OUT4));
//
//  if(digitalRead(LED)){
//    Serial.println("ON");
//  }
////  Serial.print("Count Value: ");
////  Serial.println(count++);
//}

void flash_L()
{
  //digitalWrite(OUT3, LOW);
  digitalWrite(LED, !digitalRead(LED));
  digitalWrite(OUT3, !digitalRead(OUT3));
  //digitalWrite(OUT4, !digitalRead(OUT4));

  if(digitalRead(OUT3)){
    Serial.println("hello");
    //Serial.print("Count Value: ");
    //Serial.println(count++);
  }
}

void loop() {
    Timer1.attachInterrupt(flash_L);
  }

  [1]: https://i.sstatic.net/64yyQ.jpg

I'm very interested in your schematics. To answer your question: Unless there is some kind of (optical) isolation, both parts of the circuit need the same ground to act as a reference. This may very well be the cause of your problem and you should correct it as soon as possible. Separate grounds could cause large currents to flow between different parts of your circuit and be really dangerous to your Arduino as well as your laptop.

@StarCat for schematic, circuit is same as given in datasheet application cicuit and datasheet link I've shared. For input, simple zener based active high circuit used for 12v to 5v and given to controller. For arduino power supply what if I used same power source as of SMPS which is used to power up bulb and switch. So that Ground of switch and arduino will be same.

You don't have to use the same power supply as long as the grounds are connected. However, you could use the 12V 10A supply for powering the Arduino as long as it's connected to the external power connector (via a barrel plug). What resistor value did you use in the input circuit in combination with the Zener?

First resistor of 4K7(series), then a 4V7 zener, Pull Down resistor of 4K7, 0.1UF cap (all 3 other terminal to ground) then again a series resistor of 47K other end connected to controller pin. I wish to upload whole image of ckt but somehow its not getting uploaded due to some error.

@StarCat Thank you soo much. Your help really solved my problem. Just one more question, After programming arduino, completely disconnected it from laptop. So, to perform any operations like UART arduino needs to be connected to laptop. So, how advisable it is to connect arduino to both laptop and to SMPS via barrel plug?

It's no problem to have the Arduino Uno connected to both the (external) power supply and USB. The external supply will override the USB power.


text:
What are the units of output of soil moisture sensor?
I want to use a soil moisture sensor using arduino uno R3. I am using the analog output. The values are in the range of 100 to 1300 as in the readings mention in this question.
May I know what exactly these numbers mean? I read in a website that:

Most soil moisture sensors are designed to estimate soil volumetric water content based on the dielectric constant (soil bulk permittivity) of the soil.

So what are the units? Basically I want to base an estimate for the normal amount of soil moisture for typical loamy soil and I don't understand how to base this threshold based on the readings given by the sensor. It would be greater help if someone actually knows what an appropriate soil moisture threshold is for loamy soil.
I searched on the internet but the closest i could come to answers was this table and this particular entry:

Table 1.1. Typical field capacity and wilting point values (m^3
   m^(–3)) for different soil textures
Soil texture| Field capacity| Wilting point| Available water
Loam    |0.27| 0.12| 0.15|

I am so sorry if I seem confused but I am very new to the whole of sensors and electronics
This is the sensor that I am making use of

They measure units of moistosity. That is from dry to wet. The numbers themselves have no intrinsic meaning. At least not without more details about the "soil moisture sensor" that you're using.

@Majenko I have added the senor details that I have used in case it gives something more to work with :)

That device has no units. It doesn't measure anything absolute. It only gives you a voltage that is in proportion to the resistance of the soil compared to some other resistance that isn't specified. So it's just a number from dry to wet. Or maybe wet to dry. Even that isn't clear.

Also that kind of soil moisture sensor is the worst kind of moisture sensing you can possibly do. Fine short term for a pot plant I suppose, but it will corrode in no time unless you take special measures, and the results are, as you see, pretty meaningless. A proper soil moisture sensor costs a lot more and looks like this: https://www.davisinstruments.com/product/soil-moisture-sensor-vantage-pro-and-vantage-pro2/

Oh. Makes sense. But this was for the sake of experimentation. So.

Such cheap sensors are fine for learning and playing around with.

@Majenko: actually the Watermark sensors are soil water potential sensors, not soil water content sensors. Seems even people selling them don't always understand the difference.

Those sensors have no units. If you can find a schematic you could possibly relate the value to the resistance of the soil, but you'd need to know the resistance that the soil is paired with to form the resistive divider.
All you can say from the numbers is "This is wet" or "This is dry". Normally you would use trial and error to determine what the values roughly relate to, and say that "Anything under X should trigger watering. Anything over Y should stop watering."

So what exactly are the outputs obtained in the question I had linked? Were they resistances?

They are the ADC values that equate to the voltage that is read from the sensor which is related to the resistance of the soil and the resistance of the (unknown) resistor in the sensor circuit.

You could calibrate the sensors by measuring the output value in soil of known moisture but it probably wouldn't be worth it because those sensors corrode. There are some very inexpensive capacitance sensors available which would be better


text:
How to pause the analog value according to input signal applied to a particular digital pin?
I'm working with a digital blood pressure meter using arduino nano. I need to display the pressure reading during inflation and deflation of the cuff instantly. And when an input signal applied to a particular pin during deflation, I need to print the pressure value at that time of input signal, to a display. How to code for this logic. I made the code for showing pressure value during inflation and deflation. But need to pause the value and display constantly the pressure value at the time of input applied to the arduino pin. How this pausing of value can be done?.
Finally I need to print both the systolic and diastolic pressure value constantly as: 120/80 mmHg (systolic/diastolic mmHg)
In this project, the systolic pressure is noted when there is an input at digital pin.
In the case of diastolic pressure, it is noted according to input pulse duration. That is, If the duration of pulse is greater than 50 milli-seconds, print the diastolic pressure as current pressure minus the pressure when pulse duration equal to 50 milli-seconds.
Below is the code I have written for printing the systolic and diastolic pressure instantly.
#include <LiquidCrystal.h>//Don't forget to enter this library

LiquidCrystal lcd(12, 11,  10, 9, 8, 7);

int analogInPin = A1;     // Analog input pin that the pressure sensor output is attached to

int pressure = 0;
int sensorValue = 0;        // value read from the pressure sensor via the amplifier stage

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

void loop() {
lcd.clear();
sensorValue = analogRead(analogInPin);

pressure = sensorValue*(0.9226)-267.7; //Pressure value according to sensor value
  lcd.setCursor(0,1);
  lcd.print("mmHg: ");
  lcd.print(pressure);
  delay(100);

}

I'm using a different method to note systolic as well as diastolic pressure values, like the stethoscope doing the job in conventional measurement method. The dual microphone arrangement will capture the sounds( korotkoff ) of blood flow. This sounds are processed (independent to arduino) by the external analog circuitry which outputs a 5VDC at every noticeable instant of pulse(during blood flow). This signal is then fed to a digital pin of arduino. Here, when the 5V signal reaches at the digial pin first, we note the systolic pressure as the pressure at the instant when the 5V signal is generated first. In the case of diastolic pressure, the generated 5V signal from the circuit is compared with an externally given unit step 5V using comparator. This compared signal output is fed to another digital pin of arduino, where the diastolic pressure is noted according to the input 5V pulse signal duration( Eg: If the duration is greater than  50ms ), the diastolic pressure is the pressure at which the pulse duration which is equal to 50ms).
I'm totally frustrated with remaining parts of code as mentioned.
Thank you in Advance..!!

the answer to your question is in your own code, right after delay(5000);

I need to print the two pressure values as Systolic/Diastolic with respect to the input signal to particular digital pins. And these values should displayed constantly as it is the final measurement value. Like: "Your Blood Pressure is: 120/80 mmHg"

The Systolic/Diastolic pressure is the two pressure levels noted at instant when the signals are reached by externally to any two digital pins at two different time

so, what is giving you the problem? .... you already have code for displaying data depending on pin input

your code is poorly formatted ... that makes it more difficult to see program flow and more difficult to determine where to insert additional code for expanded functionality

I just optimized the code for better understanding (I hope). Yes, I already have code for displaying data depending on pin input. That's working nice. But, I need to print the two pressure values among these broad pressure values, depending on an external signal  as input to a digital pin. This is what I need to print constantly as Systolic pressure during the measuring of pressure.

ok, now i know that i do not understand what you are trying to do ... my apologies ... maybe someone else can understand what you are asking

In my project, The pressure is given to the sensor externally and it is represented as inflation here and after a pressure value of (say: 180 mmHg), the deflation valve is activated to decrease the pressure inside the cuff gradually. at this time of deflation, at a particular time of deflation, an input from external microphone is reached at a digital pin (say: pin4). Here, I need to pause or print the pressure value at the time of input signal given.

Can I hope someone will solve my problem?. Anyway, thanks for follow up @jsotola

i think that the problem may be with your thinking that the displaying of data is somehow related to acquiring data .... the two functions are totally separate .... what you do with data, is totally irrelevant to the "read data function" ... how you obtained the data is totally irrelevant to the "display data function"

What is your overall hardware setup? Do you have the pulse detection circuit connect to the Arduino? My understanding of systolic pressure change is caused by the oscillation and therefore it can't just detected by reading the pressure. The amplitude of the pulse change when the pressure changed. The maximum amplitude represents the mean arterial pressure, and both systolic and diastolic can then be calculated based on the obtained mean arterial pressure. To obtain the pulse amplitude, you need a sensor (e.g. microphone) and a high-pass filter to filter out the pulse and the amplitude.

Sir, I'm using a different method to note both the systolic as well as diastolic pressure. I just added the description of my hardware part in above main question. Please find it at the bottom of my code part.

Still your code has nothing about the digital signal you mentioned. You need to read the change of the signal and record the pressure as diastolic. If you are using the cuffless technique, I would suggest you read the pulsein()   function that might be useful for your application.


text:
Arduino sends bad data ONLY when not connected at the launch my application
I'm trying to write a little sensor reading application with a light sensor attached to an Arduino, which writes the information from the sensor over serial. I have written a python program to read the data from the serial port. The good news, is that my program is working completely fine... only if I make sure that the Arduino USB is connected to my laptop before I launch my Python program.
I have myself forgotten to connect the Arduino before running the program before, which can leave it hanging... until you realise and plug the Arduino back in. It would be nice to have a window helping users if they ever make the same mistake.
Here is the Arduino sketch I have running on my Arduino.
int photoTran = A1;
  int reading = 0;

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

void loop() {
  // We just read the value on the analogPin
  reading = analogRead(photoTran);
  Serial.println(reading);
  delay(100);

}

Here is the little catcher part of the Python script which checks whether the Arduino is connected before I get into the main part of my application. When I plug in the Arduino before running the Python script, it can still sometimes take a few attempts before connecting. (Just FYI: the window(), button, values, variables are from the PySimpleGUI framework that I'm using.)
connected = False
while connected == False:
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break
    try:
        print("Attempting to connect")
        SER = serial.Serial(serial_port, baud_rate, timeout=0.1)
        connected = True
        ser.append(SER)
    except:
        time.sleep(0.1)
        attempts += 1
        window.FindElement('attempts').Update(attempts)
window.close()

# User exited from the GUI connection window
if not connected:
    sys.exit(0)

Later on in my Python code, I want to read the sensor data coming to us from the Arduino. ReadArduino, and CleanThe are the functions that I use to read data from the Arduino.
def ReadArduino( serialCon ):
""" Try to read in a value from the Arduino. Sometimes we might read a value from the serial
    port before the arduino has sent anything. In such cases we will wait a small time, and read again.
    Until we pick up our first non empty integer value."""
while True:
    val = serialCon.readline()
    print(val)
    val = cleanThe(str(val))
    if val != '':
        return val

def cleanThe( lineVal ):
""" The Arduino returns non-clean data back to us.
    We need to remove all the non-integer values to get
    a nice plottable integer value. Will accept '.' unconditionally for now,
    we may have to add conditions later. """
S = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}
clean = ''
for char in lineVal:
    if char in S:
        clean += char
return clean

Now the confusing part. When I run the application without the Arduino connected to my computer. It gets stuck in the while connected == False: while loop above. This is exactly what I want. Then when I plug it in, the serial port sets up and we break out of the loop. I even have a serial port object that I read from.
However, when I read from the serial port, I get back garbage hex values, without any sign of any useful integer values that I would expect.
Here are some sample raw val values that get read back when the python script is run with the Arduino connected before running:
b'336\r\n'
b'349\r\n'
b'343\r\n'
b'322\r\n'
Then here is the output I receive when the Arduino was not connected to my computer before running the Python script.
b'\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\x00\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00'

b'\x00\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0'

I have noticed, that when I am running my script with the Arduino plugged in from the start (i.e. the working case). The first value I read back from the Arduino is the same type of garbage hex:
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

It seems like in the working case, the hex is all sent on one line. Where as in the non-working case, these hex values, seem to be sent intermittently in smaller chuncks. Perhaps I could add a check to the Arduino code, to only write values back to serial if they are good? I do realise this may be more of a python serial issue than an Arduino issue, let me know if this is the case and I will move the post.
Has anyone experience some kind of problem like this before?

Depending on the bootloader you might receive its tries to connect to its counterpart on your PC. Did you check how the "garbage" maps with the bootloader's protocol? -- Another thought: The xe0 and x00 bytes might indicated an unmatched baudrate.

I know I'm a month late to this question, but just out of curiosity, did you solve it? Have you tried with a Serial.flush() after the Serial.println in the Arduino code?

No I haven't managed to find a working solution so far. I would be very keen to find a fix thought. Will give this a go, thank you for the suggestion.

Okay so after having a tinker around I have found a fairly reasonable solution to the problem.Previously my app would instantly enter a infinitely repeating while loop trying to connect to the arduino over serial port as soon as it started, waiting for a successful connection to indicate that the device was connect.

Instead of this automatic repeated connection attempts, I've programmed a 'Connect' button into my apps GUI with a window saying to connect the device before attempting to connect. I think the automatic attempts to connect to the arduino, immediately after launch the app meant that the successful serial connection would happen while the arduino was in some kind of set up phase. By letting the user click connect, there is always some reasonable delay between plugging the arduino into my laptop, and the first attempt at a serial connection being made.

Just to explicitly show what I changed to my python code I thought I would answer my own question. The solution I found ended up being in the Python, but the other suggestions were useful for cleaning up the output of my Arduino.
Here is the old auto connecting solution.
connected = False
window = sg.Window('Arduino Connection').Layout(layout)
attempts = 0
while connected == False:
    print("In connection while loop")
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break

    try:
        print("Attempting to connect")
        SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
        print(SER)
        connected = True
        ser.append(SER)
    except:
        time.sleep(0.1)
        attempts += 1
        window.FindElement('attempts').Update(attempts)

Here is the working solution where I ask the user to press a connect button.
    connected = False
window = sg.Window('Arduino Connection').Layout(layout)
attempts = 0
while connected == False:
    print("In connection while loop")
    button, values = window.Read(timeout=300)
    if button in (None, 'Exit'):
        break
    if button == 'Ok':
        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
            print(SER)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)

On the Arduino side make your code non blocking:
 unsigned long timeStamp = 0;
 unsigned long timerDelay = 1000; // 1 second

 setup(){....}

void loop() {
// We just read the value on the analogPin
 if (millis() - timestamp > timerDelay ) {
     reading = analogRead(photoTran);
     Serial.print(reading); // instead of println which sends additional \r\n
     timeStamp =millis();  // reset timer instead of delay(100);
 }
}

On the Phyton side try to implement a routine waiting for the first char and then start reading from the next message on. The 1 second between sends on Arduino should suffice to ensure its working. The garbagge chars could be an init sequence from the port driver - this can not come from your code,

Hey, thanks for the reply! I gave this a go on the Arduino side, but I'm still running into the same kind of problems. One thing I did try was closing the serial connection in python after it is first established. Then re-opening it later when I actually want to start reading data from the Arduino. This change produced a different kind of error. When I try to re-open the serial communication for the second time, I get an error message in my Python console saying: [Errno 16] could not open port /dev/ttyACM0: [Errno 16] Device or resource busy: '/dev/ttyACM0'


text:
Trying to do hello world app for Nokia 5110 LCD with arduino yun and johnny five
I have a Nokia 5110 LCD which is using this display PCD8544, I am using a arduino yun and johnny five I have hooked up the following pins. So far with my node app all that happens is the lcd lights up. I am not sure if maybe the lcd is not supported with johnny five, if I have a pin wrong. I followed this site for the pin setup https://lastminuteengineers.com/nokia-5110-lcd-arduino-tutorial/ Any help would be greatly appreciated. This is my first attempt with Johnny five and second attempt at hooking anything up to a bread board. Hope we can get this working. Thanks
Here is my code
const five = require('johnny-five');
const board = new five.Board();

board.on("ready", function() {

    lcd = new five.LCD({
      controller: "PCF8574"
    });

    lcd.print("Hello");
  });

Here is my configuration
blue         =  pin 7          sclk     (serial clock(CLK)) 10 om
white        =  pin 6          DN(MOSI) (Serial data in) 10om
grey         =  pin 5          D/C      (Mode select) 10om
orange       =  pin 4          RST      (Reset) 10om
yellow/red   =  pin 3          SCE      (Chip select) 10om
yellow-short =  power strip +  LED      (backlight supply) 1kom
green/black  =  gnd / strip -
blue/power   =  3.4v power + 330om

Here is are some images of the setup

Update so my configuration looks more like this now
blue         =  pin 7          sclk     (serial clock(CLK)) 10k
white        =  pin 6          DN(MOSI) (Serial data in) 10k
grey         =  pin 5          D/C      (Mode select) 10k
orange       =  pin 4          RST      (Reset) 10k
yellow/red   =  pin 3          SCE      (Chip select) direct
yellow-short =  power strip +  LED      (backlight supply) 330
green/black  =  gnd / strip -
blue/power   =  3.4v power powerstrip direct

does the code compile without errors?

I don't see any errors, I can console log the board, and the repl just starts with johnny five

Follow the instructions on your page: use 10k (not 10 ohms) on the signal lines. Get rid of the 330-ohm connected to the display's VCC, there should no resistance there at all. Use that 330-ohm for the BL pin instead.

that's a mistake on my part I was using 10k, but the 330 I guess was in the wrong spot, so I moved it to the backlight pin, now It doesn't light up. Have to figure this out now.

I added my new config above still no luck

Arduino Yun is a ATMega32U4-based board, like other ATMega32U4-based Arduino boards, such as Arduino Leonardo, Micro, the SPI is only available on the ICSP header:
MOSI - Yun has it on ICSP Pin 4
MISO - Yun has it on ICSP Pin 1
SCK - Yun has it on ICSP pin 3
SS - Yun has no dedicated pin, use any digital data pin

You can find out the ICSP header pin assignment at Arduino SPI reference page. So here is the connection between Arduino Yun and LCD5110
Yun               LCD 5110
ICSP pin3         CLK(SCK)
ICSP pin 4        DN(MOSI)
any GPIO pin      D/C (see note 1)
RST               RST
any GPIO pin      SCE(SS) (see note 1)
any GPIO pin      Backlight (via a 330 ohm resistor) (see note 2)
GND               GND
3v3               VCC

Note 1: Although you could use any GPIO for D/C and SCE, you should consult the library that you are using to see what pin the library used for the data/command line and SS line.
Note 2: Connecting to a GPIO pin allows you to turn on and off the LED backlight, you could ignore the connection if you don't want the backlight, or you could connect it directly to 3v3 via a resistor if you want backlight on permanently

If you still have problem in using the LCD5110, please update your question with complete code and the library that you are using.

Im still working on this, I tried the new arrangment and still no led, or any text to screen. When you say library are you refering to this http://johnny-five.io/api/lcd/ that's the API I am using. The only other thing I can think of is I am using Firmata to connect Johnny Five To the Board. I'll look over my config again and see if I am missing something, but still quite stuck.

I took a look at the library that you are using, I don't think it supports SPI to begin with. The Nokia 5110 is a display with SPI interface and the library seems to be a wrong one.

Oh ok well I will just try and get some leds going, I just wanted to get that libary working period. Down the road want to do some soil testing. Ok I'll select your answer thanks for all the help

Maybe update your answer saying I am using the wrong library, in case someone else needs to know

You can easily find Arduino LCD library for LCD5110 if you are using c++(i.e. Arduino), I wrote my own library a few years ago as part of my learning. Maybe you could port it JS.


text:
Data in two 8 bit shift registers won't change
I'm trying to output 16 bits of data to two 8 bit shift registers (74HC595), which drive a 8x8 led matrix. There is a problem with the way the code outputs data to the registers, its like no data is even shifted onto them. The first 8 bits handle the rows and the last 8 bits handle the columns.
I have already written this code in Arduino, but I am trying to re-write in it C (we have to learn AVR programming in C for college). The Arduino version works fine, so I know the circuit is correct. I'm using Atmel Studio.
For example, I replaced all the digitalWrite(clockPin, HIGH)'s with PORTD = PORTD | (1<<clockPin).
But I can't get anything to output with my code.
For refreshing the led display the variable refreshFlag is used. For updating the game state (which hasn't been implemented yet) the variable updateFlag is used.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>

//portd 2(latch), 4(clock), 7(data). Same as pins on arduino board
#define latchPin 2
#define clockPin 4
#define dataPin 7

//functions
void init_ports(void);
void init_USART(void);
void init_timer0(void);
void sendmsg (char *s);
void drawData(uint8_t myData[]);
void shiftOut(uint8_t myDataOut);

unsigned char qcntr = 0,sndcntr = 0;   /*indexes into the queue*/
unsigned char queue[100];       /*character queue*/

int updateTimeCount;
int updateDelay;
int updateFlag; // Flag for updating game state
int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();
    clearData();
    newBlock();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

void drawData(uint8_t myData[]) { //takes data and outputs it
  for (uint8_t j = 0; j <= 7; j++) {

    //ground latchPin and hold low for as long as you are transmitting
    PORTD = PORTD & ~(1<<latchPin); //latch pin low

    //shift data into regs

    shiftOut(~(1<<j)); //grounds row. For example 10111111 means 6th row is on

    shiftOut(myData[j]);  //outputs column data.

    //return the latch pin high to signal chip that it
    //no longer needs to listen for information
    PORTD = PORTD | (1<<latchPin); //latch pin high
  }
}

void shiftOut(uint8_t myDataOut) { //shifts 8 bits out to register

  // This shifts 8 bits out LSB first,
  //on the rising edge of the clock,
  //clock idles low

//internal function setup
  uint8_t i=0;
  int pinState;

//prepare shift register for bit shifting
  PORTD = PORTD & ~((1<<dataPin) | (1<<clockPin)); //clock & data pin low

  //for each bit in the myDataOut
  for (i=0; i<=7; i++)  {

    PORTD = PORTD & ~(1<<clockPin); //clock low

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1<<i) ) {
      pinState= 1;
    }
    else {
      pinState= 0;
    }

    //Sets the pin to HIGH or LOW depending on pinState
    PORTD = PORTD | (pinState<<dataPin);

    //register shifts bits on upstroke of clock pin
    PORTD = PORTD | (1<<clockPin);

    //zero the data pin after shift to prevent bleed through
    PORTD = PORTD & ~(1<<dataPin);
  }

  //stop shifting
  PORTD = PORTD & ~(1<<clockPin);
}

void sendmsg (char *s) { //create serial message
    qcntr = 0;    /*preset indices*/
    sndcntr = 1;  /*set to one because first character already sent*/

    queue[qcntr++] = 0x0d;   /*put CRLF into the queue first*/
    queue[qcntr++] = 0x0a;
    while (*s)
    queue[qcntr++] = *s++;   /*put characters into queue*/

    UDR0 = queue[0];  /*send first character to start process*/
}

/*this interrupt occurs whenever the */
/*USART has completed sending a character*/

ISR(USART_TX_vect) {
    /*send next character and increment index*/
    if (qcntr != sndcntr)
        UDR0 = queue[sndcntr++];
}

ISR(TIMER0_OVF_vect) { //overflow every 16ms
    TCNT0 = 6; // 256-250 = 6
    ++updateTimeCount;
    if(updateTimeCount >= updateDelay) { //after 208ms, update game state
        updateFlag = 1; // Call for updating game
        updateTimeCount = 0;

    }

    refreshFlag = 1; // Call for updating screen
}

void init_ports() {
    DDRD = (1<<latchPin) | (1<<clockPin) | (1<<dataPin); //enable pins
    PORTD = 0; //set all pins low
    DDRB = (1<<5); //enable the built-in led for debugging
    PORTB = 0; //set all pins low
}
void init_USART() {
    UCSR0B = (1<<TXEN0) | (1<<TXCIE0); //enable transmitter and tx interrupt
    UBRR0 = 103; //baud 9600
}
void init_timer0() {
    TCCR0A = 0;
    TIMSK0 = (1<<TOIE0);    // enable interrupt
    TCCR0B = (5<<CS00); // prescalar 1024. 16Mhz/1024 = 15625Hz = 0.064ms
    // For refresh rate of 62.5Hz, 16ms /0.064ms = 250
    TCNT0 = 6; // 256-250 = 6
}

I really can't tell what the problem is and I don't what to look up either. I think the problem is in the functions drawData and shiftOut, because that's where all the data is shifted out. I tested the timer0 interrupt by flipping the built-in led and that seems to be working fine.
Are the ports flipping too fast for the shift regs to receive the data? Is there a semantic error somewhere? Can you see any problems. Thanks for any help!

Re “I think the problem is”: better be sure. Break down the problem into smaller chunks and test them one by one. Writing the full program before you start testing is a bad idea.

@EdgarBonet I did some testing with LED's and the refreshFlag isn't getting set to one when the timer0 overflows. Which means drawData() is never called. But I have tested the updateFlag, and it does work. So I tried calling the drawData() when the updateFlag is one but still nothing. So I'm not really sure where the problem is.

this may help ...... https://electronics.stackexchange.com/questions/183299/atmega-16-timer0-with-interrupt ...... http://www.avr-asm-tutorial.net/avr_en/micro_beginner/6_Led_Int/6_Led_Int.html

As Edgar Bonet said: start with code that's as simple as possible for testing / debugging basic functionality. First get that to work before moving on to more complex code. See if your problem can be reproduced with (much) simpler code.

why do you use direct register access and not digitalWrite and the Arduino shiftOut function?

@juraj I'm using C not Arduino code

You might want to add some delays in you shiftout function. You set the data-pin to the correct value, set the clock pin to high, and then set the data-pin back to LOW. All right after each other. I'd start adding some leds to the data and clock pins, just to see if there is any data being transmitted. With these high speed signals I connect the 5V to see if the signal is ever LOW, or connect the other way around to GND to see if the signal is ever HIGH. With current high brightness led, ever a very short signal is still  visible, though might only appear as a sight glow.

Start with volatile modifier for variables accessed in both ISR and main program.

@KIIV Yes, thank you! That solved the problem with the refreshFlag. I guess the compiler interpreted it as if(0) . However there is still no output on the display, so I'm still trying to debug that.

@Gerben So there is a slight glow on the data and clock pins without any added delay, so there is definitely data being transmitted. However I just as I'm writing this I think I have found the problem.

@KIIV @Gerben @Edgar_Bonet @StarCat @jsotola @Juraj There was no data being sent because a function clearData() was called before the while loop. I feel so stupid! However there was a problem with the refreshFlag which @KIIV noticed! Thanks for your help!

Thanks to everyone who commented on my question, I was able to solve the problem with your help!
The first issue was that the compiler interpreted the if(refreshFlag) {...} as if(0) {...} so the data would have never been outputted to the display.
This happens is because the compiler doesn't see that the refreshFlag can be set to 1 in the timer0 interrupt service routine. From its perspective I have written an if statement that never runs.
As @KIIV pointed out, if the volatile keyword is used when declaring refreshFlag, this tells the compiler that this variable can change at any time.
The second and more embarrassing issue was that I forgot to remove a call to clearData() function which clears the data array. So I was just outputting nothing to the registers!
This is what the fixed variables and main should look like:
int updateTimeCount;
int updateDelay;
volatile int updateFlag; // Flag for updating game state
volatile int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

It's OK to accept your own answer as the solution to the problem. You'll have to wait 48 hours before you can accept it.