body:
# Update:
**The arduino works only when I connect 3.3v to reset pin. And I successfully uploaded a sketch but it stops when I disconnect 3.3v and reset.**
# Update 2:
**-- Removed --**
# Update 3:
**Its working perfectly and running smoothly for like 5+ min but the problem starts again**

----------

I bought a new arduino nano V3 clone. Till now, I have been facing very strange problems with it:

 - The pre-uploaded blinking sketch works for a few seconds (like 5 sec and only works when powered after a break) and then it starts to glitch
 - The L led stays on or off after that
 - Reset button does nothing (No led blinks or anything)
 - Can't upload any sketch
 - Programmer is not responding
 - RX led blinks during uploading (3 times only)
 - USB not recognized when connected

Here is what I tried to solve:

 - Loopback test > Successful
 - Changed ports
 - Changed proccessor
 - Tried uploading with parallel programming
 - Sketch worked with another arduino nano clone
 - Manual reset
 - Tried with Old bootloader
 - Tried uploading sketch with older version of Arduino IDE.

Here is the exact image of one I have:

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

Here is the error message:

    Arduino: 1.8.10 Hourly Build 2019/07/23 10:33 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\arduino-builder -dump-prefs -logger=machine -hardware C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\tools-builder -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -built-in-libraries C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\libraries -libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810 -build-path C:\Users\MN\AppData\Local\Temp\arduino_build_778230 -warnings=none -build-cache C:\Users\MN\AppData\Local\Temp\arduino_cache_273206 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -verbose C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\examples\01.Basics\Blink\Blink.ino
    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\arduino-builder -compile -logger=machine -hardware C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\tools-builder -tools C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -built-in-libraries C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\libraries -libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810 -build-path C:\Users\MN\AppData\Local\Temp\arduino_build_778230 -warnings=none -build-cache C:\Users\MN\AppData\Local\Temp\arduino_cache_273206 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr -verbose C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\examples\01.Basics\Blink\Blink.ino
    Using board 'nano' from platform in folder: C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\arduino\avr
    Detecting libraries used...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\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=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\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=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\preproc\\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\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 -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\arduino\\avr\\variants\\eightanaloginputs" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp" -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core: C:\Users\MN\AppData\Local\Temp\arduino_cache_273206\core\core_arduino_avr_nano_cpu_atmega328old_96bc3f74325b2724b539066aa6a6e44d.a
    Linking everything together...
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230\\sketch\\Blink.ino.cpp.o" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/..\\arduino_cache_273206\\core\\core_arduino_avr_nano_cpu_atmega328old_96bc3f74325b2724b539066aa6a6e44d.a" "-LC:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230" -lm
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\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\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.eep"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf" "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.hex"
    "C:\\Users\\MN\\Downloads\\Compressed\\arduino-nightly-windows\\arduino-nightly\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\MN\\AppData\\Local\\Temp\\arduino_build_778230/Blink.ino.elf"
    Sketch uses 924 bytes (3%) of program storage space. Maximum is 30720 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/bin/avrdude -CC:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:C:\Users\MN\AppData\Local\Temp\arduino_build_778230/Blink.ino.hex:i
    An error occurred while uploading the sketch

    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 "C:\Users\MN\Downloads\Compressed\arduino-nightly-windows\arduino-nightly\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM6
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x85

    avrdude done.  Thank you.

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

What is wrong with my arduino?

Note: I was uploading the blink (Example) code, tried with others too...

  [1]: https://i.stack.imgur.com/WjFwR.jpg

title: Arduino Nano - Strange problems

Answers: 3

body: Sounds like it is missing the 10K reset pullup resistor.  Try adding one from the RST pin to VCC, which is pin 2 of the 6-pin header.

body:
The compiler log said:

`-libraries C:\Users\MN\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10810`

It seems your AVR is not updated, try to update your `Arduino Avr Bords` on the boards manager. also make sure your `avrdude.conf` file might to be :

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

Dont forget to wire RX to GND or connected RX to TX directly.

Hope this helps.

body: When soldering the pin headers, I used too much flux. So this caused contact between the GND and RST on the ICSP causing the arduino to stay in the reset position. I removed the ICSP pin headers and there was a lot of flux. I removed it and now my arduino is working perfectly. Thanks to @Juraj for figuring it out that there must be a contact between GND and RST


body:
I'm trying to read from the EEPROM and combine the information and send it out over SoftwareSerial using write() function but i'm getting the following error

    error: invalid operands of types 'const char [3]' and 'const char*' to binary 'operator+'

----------

    void loop()
    {
      const char* eTest1 = EEPROM.read(1);
      const char* eTest2 = EEPROM.read(2);
      const char* eTest3 = EEPROM.read(3);

      char combinedVal[] = eTest1+":"+eTest2+":"+eTest3;
      bluetooth.write(combinedVal);
    }

title: Reading from EEPROM and combining

Answers: 1

body:
You cannot use the + operator for that.

However, since EEPROM.read only returns one byte and not a string, you can do a much easier implementation:

    void loop()
    {
      char result[] = "1:2:3";
      for (int item = 0; item < 3; item++)
      {
        result[item * 2] = EEPROM.read(1 + item);
      }
    }

This first create a string "1:2:3", where the digits are overwritten in the for loop by that item. Note that the digits in the string do not matter, it's just some free 'comment', it also should work when using "x:x:x".


body:
I am using an Arduino (Elegoo) Mega with Motor shield to drive a digital train set. The Motor shield is powered from a 12v 1.1 amp dc power supply and I have the Arduino plugged into my laptop via USB. I have an app which sends commands via serial to the mega which are then turned into commands for the train set and sent down the line.

When using this all of a sudden the main chip on my Arduino blew up and my Laptop seemed to blow a re-settable fuse shutting off instantly (It was dead for about 10-20 minutes then worked again).

**Would this be because something caused power to get back through the Arduino to my laptop?**

The railway will short from time to time if a locomotive derails for example.

I know there is a trace on the Motor Shield which prevents the shield powering the Arduino. I have now cut this although it says you only need to cut it if using over 12v.

title: Arduino powered from motor shield and USB issue

Answers: 2

body:
Looking at pictures of the Elegoo Mega 2560 they use a "hash fill" for the pour on the tab of the regulator, not a solid fill, and zero vias to another dissipation layer on the reverse. While this may look more funky it provides only a fraction of the heat dissipation of a solid double-layer fill, meaning the regulator is more likely to overheat. Also because this is a Chinese clone the component quality will be lower (cheaper) meaning the regulator probably doesn't have proper thermal overload protection.

So it gets too hot too easily, and **pop** your Arduino is dead as the regulator fails "short" and 12V gets pumped directly into the rest of your Arduino.

Byebye Arduino, and byebye computer (fortunately temporarily in the case of your computer).

body: Be careful dissing Chinese components as 'poor quality' Your TV, Phone, computer and practically any other electronic item you own has chines built components in it. Most of these items are assembled in China anyway. I agree the board design may be poor but component quality from China is fast becoming a thing of the past.


body:
I am  trying to program an ATMega32u4 microcontroller through arduino IDE. I have added external oscillator(16Mhz) and capacitors and few other connections according to the Schematic. I had put a sparkfun bootloader onto it(caterina) using Avr Pocket Programmer. A usb 2.0 is connected to the microcontroller. Arduino IDE recognizes microcontroller as Arduino Leonardo with the help of this usb. [Bootloader file](https://github.com/sparkfun/SF32u4_boards/tree/master/sparkfun/avr/bootloaders/caterina).

I was able to upload codes into the microcontroller but the issue is, I have to put the reset pin to ground momentarily each time when the IDE goes to uploading stage.
If i do not reset it, the COM Port for leonardo disappears but it never comes back until I reset it manually and therefore the uploading bar just gets stuck. I have also added the circuit connected to the Reset Pin according to the schematic but even if i remove all of it and just connect a switch, no difference can be observed. No power on reset is working.

Since one can upload codes without having to manually reset each time in Arduino Leonardo, I was wondering what could be the issue here.

Is there a way to auto reset this? Or perhaps fix the auto reset issue in this case? [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/EHMCs.jpg

title: How to enable auto reset in Arduino Leonardo?

Answers: 0


body:
 I want to make a strip led application(Fade In/Fade Out).Each strip has 48 pixels.One of the strips should be red and the other should be blue.Using the for loop, I managed to fade in-fade out a small number of strips (eg 10).But when I fade in / fade out all of the 48 leds, the code behaves as if there is a "delay".I guess that's because there's a lot of data in the for loop.Is there a way to do fade in / fade out without using a for loop?

    #include "FastLED.h"
    #define NUM_LEDS_PER_STRIP 48
    CRGB redLeds[NUM_LEDS_PER_STRIP];
    CRGB blueLeds[NUM_LEDS_PER_STRIP];
    void setup() {
    FastLED.addLeds<NEOPIXEL, 6>(redLeds, NUM_LEDS_PER_STRIP);
    FastLED.addLeds<NEOPIXEL, 7>(blueLeds, NUM_LEDS_PER_STRIP);
    FastLED.setBrightness(0);
    }

    void loop() {
    //fade in
    for(int i=0;i<256;i=i+5) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i);
    redLeds[j] = CRGB(255,0,0);
    blueLeds[j] = CRGB(0,0,255);
    FastLED.show();
    }}
    //fade out
    for(int i=255;i>=0;i=i-5) {
    for(int j=0;j<NUM_LEDS_PER_STRIP;j++) {
    FastLED.setBrightness(i);
    redLeds[j] = CRGB(255,0,0);
    blueLeds[j] = CRGB(0,0,255);
    FastLED.show();
    }}
    }

title: Fade In/Fade Out with multiple LED strips

Answers: 2

body:
Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.

Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.

body:
CrossRoads already gave a likely reason for the delay (so upvoted).

One way to solve it is using one microcontroller (slave) per LED string and split the load, and using one microcontroller as master:

- Use a fast communication protocol between your current MCU (master) and the slaves (preferably small/cheap ones like Arduino Mini/Micro's), e.g. SPI which is easy to use for communication.
- To make sure they all start at the same time, you can first send all data (SPI), and at the end after all data is sent to all slaves, set on the master a GPIO high where all slaves listen to, knowing they have to start sending.
- SPI is very fast, but if you want to save communication time, you can make some smart commands (e.g. like sending a command to reset a group of bytes, or change a group of bytes by a certain value etc). Depending on what commands you want, it might be needed to store the data of all led strips on your Arduino, which can cost quite some money (see CrossRoads answer).


body:
I am SOMETIMES getting `exception 28` when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):

 Decoding stack results
 0x40213b8c: dns_gethostbyname at core/dns.c line 1472
 0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
 0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
 0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
 0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
 0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
 0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
 0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
 0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
 0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
 0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
 0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

My code at line 360 is

    if (client.connect(serverName,80)) {

My current strategy is to keep the wifi connection open all the time.  Should I test for connection before attempting to connect to the server?

title: NodeMCU Exception 28 - intermitent problem

Answers: 1

body:
Exception 28 is, according to the [exception list document](https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf):

> Access to invalid address

The most common cause is trying to read or write from/to a NULL pointer.

It *could* be because you have debugging turned on, and that debugging is trying to print something that didn't get returned properly from another function call (the call failed) - most likely looking up a host name (`hostByName()`) due to your intermittent internet connection.

This may sound counter intuitive, but try turning off debugging to see if that helps reduce the number of crashes.


body:
I am working with Arduino which activates a box which is similar to a [Skinner Box][1]. Some of the output sound stimuli are sine waves with duration of less then 5 milliseconds. I output the sounds using the MP3 module [DFR0299][3].

However there are too much problems using this module: it seems like the module has a wakening delay of around 100 ms, so it is not working well with this duration and below (the response time of the module is important).

So, I was thinking of buying a better module. However, I am far from being an expert in these things..

I can look for other modules in the internet, but, just from looking at the datasheets, I cant tell if the quality of the module is what I need.

I would be grateful if any of you could give me names of modules that might feet my requirements (or even advice me at what to look in the datasheets)

Thanks!

  [1]: https://en.wikipedia.org/wiki/Operant_conditioning_chamber
  [2]: https://www.digikey.co.il/product-detail/he/dfrobot/DFR0299/1738-1041-ND/6588463
  [3]: https://cdn.instructables.com/ORIG/FGT/H5J3/IUKEZCYF/FGTH5J3IUKEZCYF.pdf

title: A recommendation for a fast-response-time-resolution-mp3-module for arduino

Answers: 2

body:
I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.

https://playground.arduino.cc/Code/PwmFrequency/

The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.

body:
MP3 modules are way to complex for this project. Tracks of 5ms at max may even be stored directly on the Arduino in raw wave format (without any compression)(depending on the resolution and sample frequency), and then outputted by it.

Since the PWM with low-pass filter method is rather noisy and not very accurate (especially for higher frequencies), you may want to use an external DAC chip. These are available with parallel input port or with SPI. I would suggest using SPI, which is fast and does only need 3 pins (+1 for slave select, if needed). Put the raw wave values into an array and send them to the DAC to output. Depending on available memory and number and size of your tracks you may be able to save them directly on the Arduino. If not, you may want to use an SD card, to save a library of tracks, which then get loaded onto the Arduino and played. This way you would only need to hold 1 or 2 (if double buffered) tracks in the Arduino's RAM.


body:
I am creating a slot sensor, using photoresistor.
The goal is to send the photoresistor value, via analog read, pin A0 to my web server, so I can stored it in my database.

``void loop() {
  int sensorvalue = analogRead(A0);// LightValue, read from sensor pin A0
  data = "sensorValue=" + (sensorvalue);
  //there is a car parked
  if(sensorvalue >=1000){
    if(flagstatus == false){
            if (client.connect(server, 80)){
              Serial.println("Connected to Host Server");
              client.println("POST /dataPost.php/HTTP/1.1");
              client.print("Host:");
              client.println(server);
              client.println("Content-Type: application/x-www-form-urlencoded");
              client.print("Content-Length: ");
              client.println(data.length());
              client.println();
              client.print(data);``

I've been trying to send mock data via postman, and it works like a charm, so I can eliminate my server side from the equation. Been guessing using ``:`` or ``=`` on ``sensorvalue=analogread(a0)`` or ``sensorvalue:analogread(a0)``. Or I made mistake on the code? I don't know much in Arduino, and this issue kinda frustrate me.

[![arduinosetup][1]][1]

the Image just for confirmation only, of course I installed the protoboard correctly.

  [1]: https://i.stack.imgur.com/6VrNx.jpg

``Connect to SSID: Adamar
IP Address: 192.168.1.14
Connect to server...
Connected with network---------
Connected to Host Server
sensorvalue:1007
There is still a car parked
sensorvalue:1007
There is still a car parked
sensorvalue:1008
``
I manage to get this result from my serial monitor, so I think there is no wrong reading from my setup.

title: Can't fetch arduino param on server, Using POST method via arduino wifi shield

Answers: 0


body:
I want to make a custom Feather M0 Bluefruit LE. I know this means that I will have to add a bootloader to the ATSAMD21G18.

I have seen that there are many useful articles in relation to adding bootloader to this chip like

https://www.instructables.com/id/ATSAMD21g18-Bootloader-With-J-link-Debugger/

 and

https://learn.adafruit.com/proper-step-debugging-atsamd21-arduino-zero-m0/restoring-bootloader

and

https://learn.adafruit.com/compiling-m0-atsamd21-bootloader/compile

I wanted to make sure that the bootloader will allow me to access the Bluetooth module on the board. Does anyone know if this bootloader will do that? Or is there another type of bootloader I need? Also, do I need a J-link connection on the custom board? can I just use USB?

title: Adding bootloader to Feather M0 Bluefruit LE

Answers: 0


body:
Is it possible to change I2C address of MPU-6050 ?

I am trying to connect a bunch of MPU-6050 to my Arduino.

Almost all of them are running on the same address. Few are running on different address.

Can anyone tell me how to change I2C address of MPU-6050 if it is possible ?

title: Changing I2C address of MPU-6050

Answers: 1

body:
The MPU-6050 has an address pin, marked as A0, which can be used to set the LSB (least significant bit) of the address. So if you connect A0 to ground, the address will be `0b1101000`, if you connect it to Vcc it will be `0b1101001`. You can find this information in the table under capter 6.4 in the [MPU-6050 datasheet][1] (page 15). Normally this pin is getting hardwired, but you can also connect A0 to a digital output pin of your Arduino and dynamically change the address of the MPU.

So with this pin you can have 2 different MPU-6050's on the bus. If you need more, you can keep all MPU's on one address, while pulling the MPU, that you want communicate with, to the other address. I described this principle at the end of my answer to [this question][2]. It is about a different chip, but the principle is the same.

It is important, that you cannot have multiple devices with the same address on one I2C bus, unless you never communicate with that address. When you try to use an address, where multiple devices will answer, the I2C bus most likely will get stuck, or the data will get corrupted. As long as such an address is never called, everything is fine.

  [1]: https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3 4.pdf
  [2]: https://arduino.stackexchange.com/questions/67043/software-i2c-sending-data/67044#67044


body:
In the following code, the Arduino is reconnecting to the WiFi after several loops. The idea is to check and re-establish WiFi connection every 30 minutes or so.

However, the WiFiServer seems to stop working after the reconnecting to the WiFi network. At least I get a timeout, if I try to request data by calling the Arduino's IP address.

    #include <SPI.h>
    #include <WiFi101.h>

    // the IP address for the shield:
    IPAddress ip(12,34,56,78);

    char ssid[] = "wifinetwork";
    char pass[] = "correcthorsebatterystaple";

    int status = WL_IDLE_STATUS;
    int count = 0;
    int retries;

    WiFiServer server(80);

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

      connectToWiFi();

      server.begin();
      Serial.println("Server Started");
    }

    void loop () {
      count++;
      Serial.println(count);
      WiFiClient client = server.available();

      if(client) {
        Serial.print("Connected to a client : ");

        if(client.connected()) {
            Serial.println("Response Sent to Client");
            client.println("Data");
        }

        delay(5);
        client.stop();
        Serial.println("Client is disconnected");
      }

      if (count > 10) {
        Serial.println("Reconnect to WiFi");
        connectToWiFi();
        server.begin();
        count = 0;
      }

      delay(2000); // Wait for 2 seconds before starting to listen again
    }

    void connectToWiFi(){
      WiFi.config(ip);
      retries = 0;

      // attempt to connect to Wifi network:
      do {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        retries++;
        delay(2000);
      } while(status != WL_CONNECTED && retries < 3);

      if (WiFi.status() == 3) {
        Serial.println("Connected");
      }
    }

title: WiFiServer Stops After Reconnection to WiFi

Answers: 0


body:
I have difficulty in controlling a ***MG995 continuous motor***. For I know I can control the speed of the motor as writing servo1.write(p) , where the value of p changes the speed of the motor. When the value of p is set to 90 then the motor stops ,whereas 0 and 180 values allows it to move in the top speed in C.W and Anti C.W direction respectively.
...........** I had difficulty in writing a code where I can rotate the servo motor for 180 degrees then rotating back again to 0 and whenever my ultrasonic sensor finds any object the servo should stop at that point for further action. ** ........
*(I think this value could be useful :Operating speed: 0.2 s/60º (4.8 V), 0.16 s/60º (6 V))*

title: Effective Controlling of Continous Servo Motor

Answers: 0


body:
This is the code:

    #define TMST A2 // Thermistor
    #define BZR 10  // Buzzer
    #define FanP 11 // Fan

    void setup() {
      DDRD = B11000000;
      DDRB = B00001111;
      DDRC = B00000000;
      TCCR2B = TCCR2B & B11111000 | B00000101; // pin 3 & 11 -> 245Hz
      T0 = 25 + 273.15;
    }

    void loop() {
      if (hallState > magnetDistance) {
        PORTB &= ~(1 << 0); // port manipulation -> LOW
        strcpy(WPStatus, "OFF");
        if (Alarm == 1) { // this will be set in setting menu
          if ((millis() - BZRT) > 500) {
            tone(BZR, 2300);
            BZRT = millis();
          }
          if ((millis() - BZRT) > 250) {
            noTone(BZR);
          }
        }
        else {
          noTone(BZR);
        }
      }
      else {
        PORTB |= (1 << 0); // port manipulation -> HIGH
        noTone(BZR);
        strcpy(WPStatus, " ON");
      }

      if ((millis() - fanTimer) > 2000) { // checks every 2 seconds if temperature changed
        Thermistor();
        if (TX <= 32) {
          analogWrite(FanP, 60); // Fan spinning speed
        }
        if (TX > 32 && TX <= 36) {
          analogWrite(FanP, 120);
        }
        if (TX > 36) {
          analogWrite(FanP, 255);
        }
        fanTimer = millis();
      }
    }
    float Thermistor() { // reading and calculating from thermistor
      VRT = analogRead(TMST);
      VRT = (5.00 / 1023.00) * VRT;
      VR = 5 - VRT;
      RT = VRT / (VR / 10000);
      ln = log(RT / 10000);
      TX = (1 / ((ln / 3977) + (1 / T0)));
      TX = TX - 273.15;
      return TX; // returning the temperature
    }

The 5V buzzer connected to a PWM pin with a 100 ohm resistor, thermistor and fan are connected to Arduino like this:

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

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

<!-- End schematic -->

Why When buzzer is alarming fan stops spinning?

title: Why Buzzer interfere with PWM?

Answers: 1

body:
The `tone()` command uses Timer2 to generate the square wave (it triggers an interrupt which toggles an IO pin).

However Timer2 is also used to generate the PWM signal on pins 3 and 11.

Thus you cannot use `tone()` and PWM on pins 3 or 11 simultaneously.

The simple fix: use PWM from pins 5, 6, 9 or 10 to control your fan.


body:
Are there interrupt Pin in the GY91 Module?
If not, are there good alternative for periodic sensor reading?
(apart from mcu schedule/external timer)

title: GY91 IMU module, Interrupt?

Answers: 1

body:
No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.

The *only* way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.

If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


body:
I know this question has been asked multiple times but solutions giving there hasn't been working,

I've got an esp32 soldered to my own designed PCB board with a UART to USB converter all that is working fine, I can get connected to my esp from the Serial monitor.

But it prints every about 0.5s:

    rst:0x10 (RTCWDT_RTC_RESET)
    boot:0x13 (SPI_FAST_FLASH_BOOT)
    flash read err, 1000 ets_main.c
    371 ets Jun 8 2016 00:22:57

Solutions have been to make sure to have 3.3v on the esp. I find it unlikely to have anything to do with it, 'cause its voltage range goes from 2.6v to 3.6v, but anyway I have tested it with an advanced transformer and a multimeter to check that there was 3.3v on the Vcc pin (didn't change anything).

All help would be appreciated.

Here is a bit more info:

I've also connected a 10uF capacitor (someone told me to try that).

If I pull IO0 to ground, it prints waiting for download in the serial monitor and I can almost upload the program, this is what I get:

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

> THERE IS NO CONNECTION BETWEEN NEIGHBORING PINS

(I have checked with multimeter)

PCB board:

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

[![enter image description here][3]][3]

[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/BLthw.png
  [2]: https://i.stack.imgur.com/lGWxK.png
  [3]: https://i.stack.imgur.com/a5IWU.png
  [4]: https://i.stack.imgur.com/RCZn3.jpg

title: flash read err, 1000

Answers: 2

body: Your PCB is lacking in the majority of things you need to get the module working. These modules are not "simple" in that you provide power and forget about it. You must add all the *required* support components. Those support components are **NOT optional**. For example: you aren't setting the boot mode properly with the right pullups. You lack a capacitor on the power pins (I told you to add one already. Where is it?). Also your power traces are too thin. The impedance is too high.

body:
ok, the solution was to add a 10k pull-up resistor to the EN pin, as shown [HERE][1]

No capacitor needed

  [1]: https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/?cn-reloaded=1


body:
I'm designing a connected collar for pets for a project, for this I am using a nodemcu on ESP8266 powered by a Lipo battery I'm guessing around 1000mAh of capacity is enough for a respectable autonomy (? any advices).
Lipo model : https://www.lipolbattery.com/lithium polymer battery.html
In order to charge the battery I have found this USB LiPo charger (https://learn.sparkfun.com/tutorials/lipo-usb-charger-hookup-guide/all), my first question is: Is it still usable for higher capacity LiPo batteries (1400mA)?
Also I would like to display the battery level via and RGB LED (example: green is for battery FULL battery and RED for LOW battery level in need of charging) is there any way to do this? Thank you

title: Lipo Battery level display using nodemcu

Answers: 2

body:
It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on

body:
Answering the second question "Also I would like to display the battery level...?" (next time, please open a new question for that):

To measure the module voltage level (a.k.a. VCC) of a NodeMCU (which is just a board containing an ESP8266 chip) programmed in Arduino IDE (which I assume given that you ask on the arduino stackexchange), this here applies:

> To read VCC voltage, use ESP.getVcc() and ADC pin must be kept unconnected.
> Additionally, the following line has to be added to the sketch:
>
> ADC_MODE(ADC_VCC);
>
> This line has to appear outside of any functions, for instance right after the
> \#include lines of your sketch.

[Source: ESP8266 Arduino reference][1]

So you could just drive a red and a green LED (don't forget the mandatory current limiting resistor) from any other two pins of your NodeMCU. Then switch them in your sketch if VCC falls below 3.2V (you may need to experiment with that because of measurement tolerances; a [sketch to start with that would be here][2].

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/reference.rst
  [2]: https://gist.github.com/chaeplin/d47c2de3c6d92513996cf0163aed531b


body:
In Arduino Mega 2560 R3, properly selecting the Serial Monitor bauds, this code works with `#define R 38400`, but for some reason, not with `#define R 19200` (?),
<!-- language-all: lang-cpp -->

    #define R 38400
    int rate=R;
    HardwareSerial* hwSerial[]={&Serial,&Serial1,&Serial2,&Serial3};
    void setup() {
        for (int i=0;i<=3;i++){
            hwSerial[i]->begin(rate);
            while (!hwSerial[i]);
        }
        hwSerial[0]->print("Hello World");
    }

    void loop() {
    }

Both speeds should be not problematic for Arduino, what is happening?

It seems the `int rate R;` is problematic when changing speeds (??).

title: Serial Port fails with speeds greater than 19200

Answers: 1

body: Answer is simple. You assign 38400 to a variable of type int. The signed range of integer values that can be stored in 16 bits is −32,768 through 32,767;


body:
I would like to use my FSi6 transmitter but not the receiver that comes with it (I´m trying to save weight), for that I was planning to get one of this NRF24L01 breakout boards. The problem is, how do you interpret the incoming traffic? After some googling, I couldn´t find any information from flysky.

I would think that this is a common thing to do, as you could pair the transmitter with another receiver (perhaps other brand) so there must be a standard protocol.

Any ideas?
Thanks!

title: Decoding RC transmitter data

Answers: 1

body:
Unless the FSi6 (whatever that is) uses an nRF27L01+ as its transmitter, then no - you can't.

The nRF24L01+ chip will *only* communicate with other nRF24L01+ chips.  It contains its own custom protocol within the chip and it can only talk that protocol and no others.


body:
I'd like to know what is the maximum sampling rate achievable while using ADC on Arduino Mega2560.

Thanks

title: Maximum sampling rate of Arduino Mega2560

Answers: 1

body:
The beginning of section 26 of the [datasheet for the ATMega2560][1] gives the following data:

> • 13µs - 260µs Conversion Time
• Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

  [1]: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf


body:
The code is made to sense were an object is and send out

    int const trigPin = 10;
    int const echoPin = 9;
    int const buzzPin = 1;
    int const LED1 = 2;
    int const LED2 = 3;
    int const LED3 = 4;
    void setup()
    {
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(buzzPin, OUTPUT);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    }
    void loop()
    {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delay(1);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //                                      Go
    distance = (duration/2) / 29.1;
    if (distance <= 1000 && distance >=0) {
    digitalWrite(LED1, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED1, LOW);
    }
    delay(60);
    }
    //                                      SLOW
    if (distance <= 50 && distance >=0) {
    digitalWrite(LED2, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED2, LOW);
    }
    delay(60);
    }
    //                                      STOP
    if (distance <= 50 && distance >=0) {
    digitalWrite(buzzPin, HIGH);
    digitalWrite(LED3, HIGH);
    } else {
    digitalWrite(buzzPin, LOW);
    digitalWrite(LED3, LOW);
    }
    delay(60);
    }

title: Can you help me figure out why my arduino code is not working

Answers: 1

body:
Try adding in some serial output at important code-parts. If you see that these are getting printed you can be sure that the code gets executed until that point. If it doesn't get executed it could also be a problem with the wiring so be sure to check that everythign is set up properly.

At this part:

    ...
    void loop()
    {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delay(1);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    //                                      Go
    distance = (duration/2) / 29.1;
    ...

You are trying to divide an integer (wich can only hold whole numbers) with a real number. Please make sure to use a data type wich can hold more fine-grained results like double or float.

To set up a serial interface you have to add **Serial.begin(9600)** to you code in the setup() function. Then when you write **Serial.println("Your debugging message here")** it should be visible in the serial monitor after compiling. (Arduino IDE->Tools->Serial Monitor)


body: I am looking for the software that can help me to save arduino serial monitor data into excel file. And how to use that with your own code.

title: How to save arduino serial monitor data into excel file

Answers: 1

body:
Your computer is able to access the serial data and export it to a text file, which can then be converted to an excel file within *Excel > Data > From Text*. However, the data should be formatted in a way that excel can read it by separating values with a delimiter such as `","`.

Once you have done this, simply run your serial data and open up your computer's console and write:
`type COM(# here) >> serialdata.txt`

Finally, import this text file into excel.

You could also use [Excel VBA with MSCOMM][1] to take the serial data directly into excel.

This answer is a regurgitation of a [duplicate question][2] asked earlier.

  [1]: http://www.dailyfreecode.com/Forum/accessing-serial-port-excel-vba-26041.aspx
  [2]: https://arduino.stackexchange.com/questions/47805/how-do-i-import-data-from-serial-monitor-to-excel-document-without-copying-and-p


body:
I'm using a NodeMCU, and a working code for reading Wiegand data, with [this library](https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary).

I managed to successfully read the Wiegand signal from [this device](https://www.aliexpress.com/item/32888710502.html).

However, I also have this [new AR-721H device](http://www.soyal.com/product.php?act=view&id=23), and I can't get the Wiegand to work. This is the [manual for the device](http://www.soyal.com/data/files/download/manual/321H-331H-721H-725H-757H-en.pdf).

There is absolutely nothing coming to the mcu. Everything is wired identically as the working device.

According to the manual, everything should be working, but I am at a loss.

**Can someone please tell me what I might be doing wrong?**

The store clerk told me something about needing a controller that converts RS485 to RS232, but I have no idea what that means. I already made it work with another device...

title: NodeMCU: Wiegand not working for one device, while working for another

Answers: 1

body:
It's quite cryptic from the little information in that (somewhat chaotic) "manual", but I interpret it that the Wiegand interface is an *input* port, not an *output* port.  It is intended to connect that port to an external card reader or keypad as a remote interface (typically the other side of the door to this unit).

For communication with your Arduino you should use the RS-485 interface. For that you need an MAX485 breakout board.


body:
I am making a project in which I am using 4 Infrared sensors to take an input. The way I want it to work is such that when one of the sensors is triggered, the code listens for input from the other sensors for a fixed amount of time (say 2 seconds). Based on this data, further functions are executed.

I am assigning a number to each of the sensors, and the sequence in which they are triggered is stored in an array like:

    // All relevant pins of the IR sensors are set to input with names ir1,ir2,ir3,ir4
    int sequence[] = {0,0,0,0}
    int s1 = digitalRead(ir1); //and similarly for all other pins
    int counter = 0;

    if(s1==1){
      sequence[counter] = 1; //similarly 2 for s2 and so on
      counter ++;
    }

What I am attempting to do is something like this:

    if(s1 == 1 || s2==1 || s3 == 1 || s4 == 1){
       if(s1 == 1){
          sequence[counter] = 1;
          counter ++;

       //Start listening for other sensors
       } // similarly check which sensor is triggered first

       //Allow 2 seconds for input from all sensors (no input from either one of them is also allowed)
       // After 2 seconds execute some code based on the sequence array which got updated from inputs by different sensors
    }

How do I accomplish this?

title: Check if a set of events occur in a limited time period

Answers: 1

body:
Here's some pseudocode that might help:

       if millis() - start time >= 2000
             time is up, do what you want with the sequence so far
             maybe a boolean flag here so you only do it once
       if any button is pressed
          if counter == 0
              set start time = millis() // start the timer
              set first in sequence
          else
              add the button to the sequence


body:
I'm experiencing something strange. I opened the default ESP32 example "OTAWebUpdater" in the ArduinoIDE and modified just the network part (I created a soft AP instead). The problem is, when I connect my Android phone to the AP, I can OTA update just fine, but when I connect a laptop and try to update, it gives me an error saying "not found: serverIndex". The error occurs after selecting the .bin file and clicking the "update" button. I already tried with 3 different laptops. Any thoughts?

Below is the code:
```#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>

const char* host = "esp32";
const char* ssid = "OTAWebUpdater";
const char* password = "123456789";

WebServer server(80);

/*
 * Login page
 */

const char* loginIndex =
 "<form name='loginForm'>"
    "
"
        "
"
            ""
                "ESP32 Login Page"
                "
"
            "	"
            "
"
            "
"
        "
"
        "Username:	"
        "<input type='text' size=25 name='userid'>
	"
        "
"
        "
"
        "
"
        "
"
            "Password:	"
            "<input type='Password' size=25 name='pwd'>
	"
            "
"
            "
"
        "
"
        "
"
            "<input type='submit' onclick='check(this.form)' value='Login'>	"
        "
"
    "
"
"</form>"
"";

/*
 * Server Index Page
 */

const char* serverIndex =
""
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
   "<input type='file' name='update'>"
        "<input type='submit' value='Update'>"
    "</form>"
 "
progress: 0%
"
 "";

/*
 * setup function
 */
void setup(void) {
  Serial.begin(115200);

  // Connect to WiFi network
  WiFi.softAP(ssid, password);

  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP());

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
  });
  server.on("/serverIndex", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", serverIndex);
  });
  /*handling uploading firmware file */
  server.on("/update", HTTP_POST, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
  }, []() {
    HTTPUpload& upload = server.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  server.begin();
}

void loop(void) {
  server.handleClient();
  delay(1);
}

title: ESP32 OTAWebUpdater only works on mobile

Answers: 0


body: I have found instructions for 8 pin Tiny but none for my 20 pin. How do I set this chip up on the breadboard for bootloading with Arduino?

title: How do I set up an ATTiny861A-PU for flashing with Arduino Uno?

Answers: 1

body:
The principle is the same, it's all only ISP (In System Programming), and nothing different from any other microcontroller, that uses ISP. Look at the descriptions of the used pins for the 8-pin Attinys, then connect the pins with the same description on your 20-pin chip.

Namely you have to connect the pins MOSI, MISO, SCK, RESET, VCC and GND. MOSI and MISO are the data lines, SCK the clock signal. If you look into a pinout diagram or - even better - at the pin configuration diagram in the chips datasheet, you will see pins, that are marked this way. The rest of the pins is pretty much self explaining.

---

Since you are using an Uno as programmer and didn't have a capacitor between Reset and ground of the programmer, I will explain, why this capacitor is needed here.

The Atmega328p on the Uno doesn't have a native USB interface. So in order to connect it via USB to a PC, there is another microcontroller on the Uno (on original board the Atmega16U2), which has a native USB interface. This microcontroller then is the middleman between Atmega328P and PC. It connects to the Serial (UART) interface of the 328P and translates that to USB communication.

Everytime that the corresponding serial port is opened on the PC, the PC sends a DTR signal, which is connected to the 328P's reset pin. So, when the Arduino IDE tries to connect to the Serial port for flashing the Attiny, the Uno get's resetted and hence cannot flash the Attiny.

The capacitor between Reset and Ground will hold the Reset pin high for long enough, so that this reset does not happen and the Uno can do it's duty.

On Arduino boards with native USB interface this is not necessary, since they don't have this hardwired connection to a reset and they communicate directly over USB.


body:
New to Arduino. I am trying to use a single button to light and turn off a single LED. I followed an [online tutorial (youtube video)][1] and changed the code just a bit. I know it is for two LEDs but I tried it for one. I have no idea why it is not working. I don't see why it doesn't make sense but it just does not work.

Here is the code:
<!-- language-all: lang-cpp -->

    float LengthPush = 0; // LengthPush is the amount of time the button has been pressed.

    int ShortPush = 100; // 100 ms push. Supposed to turn on the LED.
    int LPush = 1000; // 1000 ms push. Supposed to turn it off.

    int ButtonPin = 2;
    int RLED = 13;

    void setup() {
      // put your setup code here, to run once:
      pinMode(ButtonPin, INPUT_PULLUP);
      pinMode(RLED, OUTPUT);

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (digitalRead(ButtonPin) == LOW) {
        delay(100);
        LengthPush = LengthPush + 100;

        Serial.print("ms = ");
        Serial.println(LengthPush);
      }

      if (LengthPush >= LPush) {
        digitalWrite(RLED, LOW);
      } else if (ShortPush <= LengthPush < LPush) {
        digitalWrite(RLED, HIGH);
      }
      LengthPush = 0;
    }

  [1]: https://www.youtube.com/watch?time_continue=913&v=IsDzxtaZCoI

title: Trying to light an LED with one Button and have no idea what is wrong

Answers: 1

body:
I think your problem lies in the else-if-statement, where you try to compare 3 different values. While this doesn't thrown a compiling error in my Arduino IDE, it will probably not do, what you are trying to achieve.

Instead you need to compare `LengthPush` with one value and then with the other. You can even do this inside the same if statement:

    if(ShortPush <= LengthPush && LengthPush < LPush)

The `&&` is the boolean AND operator, which means, that the if statement will be executed, if both statements around it will evaluate as `true`.

---

I'm not sure, what actually happens with your original code, since it doesn't throw a compilation error. It might be (and that's my theory here), that the program will first evaluate `ShortPush <= LengthPush` and then compare the result to `LPush`. Since boolean values evaluate as `0` or `1` in integer calculations, that messes up the whole intent of this. Take the case, that `LengthPush` is really in the required interval. Then the first part will evaluate as `true`, which means `1` as integer. Then this `1` get's compared to `LPush`, which is always higher, so the overall result is true. But the same result comes, when `LengthPush` is smaller than `ShortPush`.


body:
I am trying to have my Arduino Stream an Analog Signal using Bluetooth Module (HC-05) while being able to read commands from another Micro-controller using the same Bluetooth Module.

Currently, I am using Arduino Uno for this.

title: Can HC-05 Continuously Stream data and read data at the same time?

Answers: 0


body:
I'm working on my second Arduino project, and am somewhat stuck.

I'm running a PIR module from my Arduino Uno with the following sketch:

    /*
     *  PIR Sensor test
     */

     int pirPin = 6;

     int minSecsBetweenEmails = 60; // 60 seconds

     long lastSend = -minSecsBetweenEmails * 1000l;

     void setup()
     {
      pinMode(pirPin, INPUT);

      Serial.begin(9600);
     }

     void loop() {
      long now = millis();
      if (digitalRead(pirPin) == HIGH)
        {
           if (now > (lastSend + minSecsBetweenEmails * 1000l))
            {
                Serial.println("MOVEMENT");
                lastSend = now;
            }
          else
            {
              Serial.println("Too soon");
            }
        }
            delay(500);
     }

I'm monitoring the COM3 port using the following in JupyterLab with PySerial.

    import time
    import serial
    import smtplib

    to = 'myemail@myemail.com'
    GMAIL_USER = 'myemail@myemail.com'
    GMAIL_PASS = '**********'

    SUBJECT = 'MOTION pir'
    TEXT = 'PIR sensor detected motion'

    ser = serial.Serial('COM3', 9600)

    def send_email():
        print("Sending Email")
        smtpserver = smtplib.smtp("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(GMAIL_USER, GMAIL_PASS)
        header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
        header = header + '\n' + 'Subject:' + SUBJECT + '\n'
        print (header)
        msg - header + '\n' + TEXT + ' \n\n'
        smtpserver.sendmail(GMAIL_USER, TO, msg)
        smtpserver.close()

    while True:
            message = ser.readline()
            print(message.decode('utf-8'))
            if message[0] == 'MOVEMENT' :
                send_email()
                time.sleep(0.5)

I believe my problem is with the `ser.readline()` function. I've been reading the docs, they seem to say I need to provide some kind of endpoint or timeout for the function to provide for EOF, but my goal was to have the

    if message [0] == 'MOVEMENT' :

continuously evaluate the output lines from COM3...

Any input at all would be very much appreciated.

EDIT: Thanks to all three of you for your help! By changing the Python as shown below I was able to fulfill the `if message[0] == 'MOVEMENT' :`statement

Python should have been:

    import time
    import serial
    import smtplib

    to = 'myemail@myemail.com'
    GMAIL_USER = 'myemail@myemail.com'
    GMAIL_PASS = '**********'

    SUBJECT = 'MOTION pir'
    TEXT = 'PIR sensor detected motion'

    ser = serial.Serial('COM3', 9600)

    def send_email():
        print("Sending Email")
        smtpserver = smtplib.smtp("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(GMAIL_USER, GMAIL_PASS)
        header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
        header = header + '\n' + 'Subject:' + SUBJECT + '\n'
        print (header)
        msg - header + '\n' + TEXT + ' \n\n'
        smtpserver.sendmail(GMAIL_USER, TO, msg)
        smtpserver.close()

    while True:
            message = ser.readline()
            print(message)
            if message == b'MOVEMENT\r\n' :
                send_email()
                time.sleep(0.5)

title: Attempting to monitor serial output for a string to trigger function, apparently matching string is output but the function doesn't trigger

Answers: 1

body:
You're confusing `readlines()` with `readline()`.  The former returns an array of lines, the latter a single line.  You need to drop the `[0]` since you're not working with an array of lines, and you need to include the line endings that the Arduino sends:

    while True:
        message = ser.readline()
        print(message.decode('utf-8'))
        if message == 'MOVEMENT\r\n' :
            send_email()
            time.sleep(0.5)


body:
I'm working on a project of Ultrasonic Flow Meter with TDC-GP22 using Arduino UNO. I used the library of [leokoppel](https://github.com/leokoppel/GP22)

In my code,the configurations of the registers are copied from the [Application Note of GP22](https://ams.com/documents/20143/36005/TDC-GP22_GP30_AN000283_1-00.pdf/b93ea868-e82a-4c8b-2c71-d8f602b2a102), from page 22 to page 25. I didn't use the temperature sensor so I jumped those steps related to that. No calibration neither. I just want to get some results of time of flight to be able to calculate the distance between two sensors for now.

My code for test:

```
#include "GP22.h"
#include <SPI.h>
#include <avr/io.h>

/*
 *
 * Test setup (Arduino Uno, through 5->3.3V level shift)

 *     10 -> SS
 *     11 -> MOSI
 *     12 -> MISO
 *     13 -> SCK
 *     2  -> INT
 *     5V -> VCC
 *     GND -> GND
 *     4 -> DS18B20 temperature sensor (optional)
 */

const bool DEBUG = 1;
const int FAST_MODE = 1;
const int PIN_INT = 2;

GP22 tdc(PIN_INT, DEBUG);

float cycleFactor_ns = 0;

void setup() {

  Serial.begin(115200);
  Serial.println("Go !");

  tdc.init();

  tdc.writeRegister(0, 0x430BE800);
  tdc.writeRegister(1, 0x21444000);
  tdc.writeRegister(2, 0xA0138800);
  tdc.writeRegister(3, 0xD0A24800);
  tdc.writeRegister(4, 0x10004000);
  tdc.writeRegister(5, 0x40000000);
  tdc.writeRegister(6, 0xC0C06100);

  tdc.printConfigRegisters();

  byte a = tdc.readRegister(READ_REG_1);

  Serial.println(a,HEX);
  Serial.println("Test communication: ");
  Serial.print(tdc.testCommunication());
 }

void loop() {

  tdc.sendOpcode(OPCODE_INIT);
  tdc.sendOpcode(OPCODE_START_TOF_RESTART);
  tdc.waitForInterrupt(10000000);

  delay(20);

  Serial.println(tdc.readRegister(READ_RES_3),HEX);
}
```

From oscilloscope I got the right number of fire pulses(20) with right frequency(1MHz):
[Signal][1] (the blue one is the signal of transmitter before amplification, green one is after amplification, yellow one is the signal of receiver)

But what I got from the code:
```

Go !

attached pinChangeISR_debug

Register 0: 0x430be800

Register 1: 0x21444000

Register 2: 0xa0138800

Register 3: 0xd0a24800

Register 4: 0x10004000

Register 5: 0x40000000

Register 6: 0xc0c06100

21

Test communication:

\/Test took 180 us

1

69978000

69978000

69978000

69978000

69978000

69978000

69978000

...

```

21 is the first byte of register 1, and 1 is the result of testcommunication(). These two means the test of communication is successful. But the results of reading RES_3 are always the same, and the  waitForInterrupt() doesn't work(maybe the code shouldn't be written like this) -- Timeout all the time.

What I expect, of course, is the result can change each time it measures.(impossible to get exactly the same measurement of ToF all the time)

Any help appreciated!

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

title: Ultrasonic Flowmeter Using TDC-GP22 and Arduino Uno

Answers: 0


body:
I'm trying to interface with a Broadcom [AFBR-S50MV85G][1] ToF sensor over SPI using an Arduino, which is complicated by the fact that the provided library and reference application is written for Cortex M0-based NXP microcontrollers. The documentation says that implementing the SPI, IRQ, Debug and Timer interfaces would allow use with other platforms, but it doesn't explicitly state which functions require implementations, or if all of them do, and it's not demarcated within the source code either.

The documentation lists the available command words, but no register addresses, which I believe are used by the platform-independent compiled libraries that come with it. This leaves me with no way to interface manually over SPI, meaning that my only choice appears to be to attempt to implement the platform drivers myself, which will probably take me a significant amount of time.

Is there something else I should try before sinking time into something that may not give me results? Has anyone here used this sensor before, and if so, could you point me in the right direction?

P.S.: The documentation I'm referring to is included in the SDK provided in the downloads section of the product page, and I'm not sure I'd be allowed to rehost it somewhere else in order to link it here.

  [1]: https://www.broadcom.com/products/optical-sensors/time-of-flight-3d-sensors/afbr-s50mv85g

title: Using the Broadcom AFBR-S50 with Arduino

Answers: 2

body:
I recently looked into this again, and it turns out that Broadcom had released a [porting guide][1] for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.

I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.

P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.

  [1]: https://docs.broadcom.com/doc/AFBR-S50-PG

body:
I also have been digging for information about the AFBR-S50MV85G and similar sensors for the past week.

Well, I am trying to port it to ATxmegas (ICs that are similar to those ATmegas used in the Arduino Family), but I decided to post my findings here because this is the first forum topic that I have found about this sensor family.

As Joseph mentioned, Broadcom has released a porting guide to Arm devices, but it does not help at all when it comes to porting to other microcontrollers.
Additionally, the minimum requirements of this lib according to Broadcom's [porting guide][1] are:

> Minimum memory requirements:
>    RAM: 8kByte (4kByte Heap + 4kByte Stack)
>    ROM/Flash: 128 kByte

Because of that and other facts, I also conclude that it is not possible to port the available libraries to 8-bit microcontrollers nor develop a new one due to the lack of description about the SPI register structure.

  [1]: https://broadcom.github.io/AFBR-S50-API/porting_guide.html


body:
I am learning Arduino, a beginner in programming. I want to use Arduino UNO to connect a wind direction sensor RS485. The problem is the output in the serial monitor, the return data from the wind direction sensor is unstable.
[![enter image description here][1]][1]

I need to get the return data from the wind direction sensor to get the wind direction. From the factory manual, they said sent a data to the sensor: 0x01 0x03 0x00 0x00 0x00 0x02 0xC4 0x0B and the sensor will return, like 0x01 0x03 0x04 0x06 0x48 0x00 0xA0 0x7A 0xD5

The wind direction dat at the above 5 and 6 position, the 0x00 0xA0 => 00A0H(HEX)=160 degree.

**Tools:**
Arduino Uno Board

Wind Direction Sensor
http://www.jnrsmcu.com/equipment/299.html

RS485 Board (3.3V)
https://www.waveshare.com/rs485-board-3.3v.htm

**The following is my coding:**

```c++
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11); // RX, TX

void setup()
{
    RS485Serial.begin(4800);   // set the data rate
    Serial.begin(4800);
    Serial.println("Start");

    pinMode(12, OUTPUT);
    digitalWrite(12, HIGH);  // Init Transceiver
}

byte buf[8];

int byteReceived;

void loop()
{
    digitalWrite(12, HIGH);

    byte wind[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(wind, sizeof(wind));
    Serial.flush();
    RS485Serial.flush();
    // Serial.print(wind[0], HEX);
    Serial.println("Send");

    digitalWrite(12, LOW);
    delayMicroseconds(200);

    RS485Serial.readBytes(buf, 8);
    delay(10);
    Serial.println(buf[0], HEX);
    Serial.println(buf[5], HEX);
    Serial.println(buf[6], HEX);
    Serial.flush();
    RS485Serial.flush();
    delay (1000);
}
```

**Connection map:**
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/M6shx.png
  [2]: https://i.stack.imgur.com/8frDw.png

title: Arduino UNO and RS485 Communication Problem

Answers: 2

body:
I would suggest you simplify your setup to the point where you have a 'working baseline  configuration', and then start building the system up one step at a time from there.

Start by eliminating the SoftwareSerial interface as a possible contributor to the problem.  Get an Arduino Mega with multiple hardware serial ports.

Next, verify that you can send characters to the selected hardware serial port and receive those same characters back when the Txn and Rxn lines (the 'n' here is the selected hardware serial port number) are connected via a jumper wire. This is called a 'loopback' configuration and is a basic serial comms troubleshooting technique (software serial ports don't support simultaneous transmit and receive, so they don't support loopback testing).  Don't proceed until you have this step completed successfully.

Next, get a second RS-485 module and extend your previous 'loopback' configuration with the hardware serial port on the Mega to include the two RS-485 modules.  Then you should be able to send characters out to one RS-485 module and receive the same characters back from the other, by connecting TXn to DI on one of the two RS-485 modules, and Rxn to DO on the other.

At this point you will have verified all the communications connections, so you can be confident that whatever you send will actually show up at the DO port of the RS-485, and whatever shows up at the DI port of the RS-485 will actually make it back to your serial console.  Now you can connect the sensor and figure out any issues do to data formatting, command sequences, and the like.

This basic 'cut the problem in half' building block technique will work on any system, large or small, simple or complex.

Frank

body:
- I don't see any connection between the sensor's GND and your Arduino's. This is likely the problem if they're not connected, since a common GND is necessary even with RS-485.
- Check the sensor's power supply, make sure it's actually within the advised 10-30 V range. Also check the polarity of the differential lines.
- Have you tried using the provided configuration software?
- `flush()` does nothing for `SoftwareSerial` ports since they have no TX buffer, so you can just get rid of those lines, including the unnecessary `Serial.flush()`
- Finally, your device datasheet says to wait for at least 200 *milliseconds* not microseconds, before checking for a response. Though it really shouldn't matter since you're using `readBytes()` after that, which waits for a second anyways by default, before giving up. Instead, use a bigger buffer, say 20 bytes, then try to read just 8 (the expected length) into it with `readBytes()`:

        byte buf[20];
        int rlen = RS485Serial.readBytes(buf, 8);

Then try to print `rlen` which tells you how many bytes were actually read and also print the whole response to verify the packet format is as it should be. You should get enough info from this to at least eliminate a bunch of possible problems.


body:
I would like to pass 3.3V and Ground to an component. How can I achieve such a thing?

I for example would like to let a wire get 3.3V when I for example do digitalWrite(pin, HIGH). It is hard for me to explain this, so I created an illustration in the hope of better clarifying it.

Edit: I have an product that I have dismantled. On the PCB, there is a push button. I would like to solder some wires to the place where the button is so it can be controlled with an arduino (probably wemos d1). When plugging a cable in the 3.3v of the arduino and a cable from the ground, when connecting it to the push button it will cause a boot of the dismantled product. This explains why I would like to give power to a component ONLY when a pin is set high, so I can for example boot the product via a website / app eventually.

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

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

title: Output 3.3V when setting pin to high

Answers: 1

body:
The normal way is to use a P-channel MOSFET as a "high side" switch.

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

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

<!-- End schematic -->

R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".

Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).

You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.


body:
I am interested to use ESP-NOW as a means to transmit data between two ESP32's back and forth, - each ESP receives and sends data, taking turns. The example library provides an example sketch for Slave and one for Master, which allows for one-directional data flow. However, I would like to use ESP-NOW for two-way communication. Is it possible to combine both of these sketches to allow the data to flow in both directions at the same time?

[![ESP32 Library showing Slave and Master examples][1]][1]

I'm assuming two ESP's won't be able to send data at the same exact time, so the best approach to start, I think, would be to wait until a packet has been received before sending one from the other end. Here's a snippet of code which I tried to use, but failed:

<pre>
void setup()
{
  Serial.begin(115200);
  WiFi.mode(WIFI_MODE_APSTA);
  // configure device AP mode
  configDeviceAP();
  // This is the mac address of the Slave in AP Mode
  Serial.print("AP MAC: ");
  Serial.println(WiFi.softAPmacAddress());
  Serial.print("STA MAC: ");
  Serial.println(WiFi.macAddress());
  // Init ESPNow with a fallback logic
  InitESPNow();
  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info.
  esp_now_register_recv_cb(OnDataRecv);
  esp_now_register_send_cb(OnDataSent);
}

unsigned long nextManage;

void loop()
{
  // In the loop we scan for slave
  ScanForSlave();
  // If Slave is found, it would be populate in `slave` variable
  // We will check if `slave` is defined and then we proceed further
  if (slave.channel == CHANNEL2)
  { // check if slave channel is defined
    // `slave` is defined
    // Add slave as peer if it has not been added already
    bool isPaired = manageSlave();
    nextManage = millis() + 10000;
    while (isPaired)
    {
      if (packetRecieved)
      {
        packetRecieved = false;
        // Send data to device
        sendData();
      }

      unsigned long t = millis();
      if (t > nextManage)
      {
        nextManage = t + 10000;
        // pair success or already paired
        isPaired = manageSlave();
      }
    }
    Serial.println("Slave pair failed!");
  }
}
</pre>

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

title: ESP-NOW: Master and Slave at the same time

Answers: 0


body:
Code would not update variable inside drive method. The variable is updated inside the drive method, but it doesn't change in the rest of the class. I wrote a simple similar method in normal C++ and the variable actually updated in the rest of the class.

engine.hpp
```cpp
#pragma once
#include <Arduino.h>

namespace engine
{
class Engine
{
public:
    Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward);
    void drive(unsigned int t_speed, bool t_isForward = true);
    bool isMovingForward() const;
    void stop();

private:
    const unsigned char m_motor;
    const unsigned char m_forward;
    const unsigned char m_backward;

    // Movements
    bool m_isActive;
    bool m_isForward;
    unsigned int m_speed;
};
} // namespace engine
```

engine.cpp init list
```cpp
Engine::Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward)
    : m_motor(t_motor),
      m_forward(t_forward),
      m_backward(t_backward),
      m_isActive(false),
      m_isForward(true),
      m_speed(0U)
{
}
```

drive method
```cpp
void Engine::drive(unsigned int t_speed, bool t_isForward)
{

    if (!m_isActive || m_isForward != t_isForward)
    {
        stop();

        // Set direction
        if (t_isForward)
        {
            digitalWrite(m_forward, HIGH);
            digitalWrite(m_backward, LOW);
        }
        else
        {
            digitalWrite(m_forward, LOW);
            digitalWrite(m_backward, HIGH);
        }

        m_isActive = true;
        m_isForward = t_isForward;
    }

    if (m_speed != t_speed)
    {
        m_speed = t_speed; // Updated here
        analogWrite(m_motor, t_speed);
    }
}
```

title: Class member variable would not update

Answers: 1

body:
I figured it out.

I was passing the engine objects as references instead of pointers.

main.cpp
```cpp
// Engines
engine::Engine
    engine1(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    engine2(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    engine3(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    engine4(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);
```

engine_controller.cpp init list
```cpp
EngineController::EngineController(engine::Engine &t_e1, engine::Engine &t_e2, engine::Engine &t_e3, engine::Engine &t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}
```

The solution would be to use dynamic memory allocation.

main.cpp
```cpp
// Engines
engine::Engine
    *engine1 = new engine::Engine(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    *engine2 = new engine::Engine(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    *engine3 = new engine::Engine(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    *engine4 = new engine::Engine(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);
```

engine_controller.cpp init list
```cpp
EngineController::EngineController(
    engine::Engine *t_e1, engine::Engine *t_e2,
    engine::Engine *t_e3, engine::Engine *t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}
```


body:
Analyzing [this][1] and [this][2] answers under Arduino, which should be the proper way to pass a 2D array into a function?

The function should be applicable to different sizes of 2D arrays.

    // NOT COMPILING EXAMPLE
    void f(int** x,const int m, const int n){
    // access x as x[0][0], x[0][1], etc...
    }

    void main{}{
        int x1[16][128];
        f(x1,16,128);
        int x2[64][16];
        f(x2,64,16);
    }

  [1]: https://stackoverflow.com/questions/34188355/cannot-convert-int-size-to-int
  [2]: https://stackoverflow.com/questions/5329107/passing-a-pointer-representing-a-2d-array-to-a-function-in-c

title: Cannot convert 'int (*)[size]' to 'int**'

Answers: 1

body:
According the prototype of `f` and the usage pattern for its `x`
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
`int`. However, the matrix in `main()` is defined as an array of arrays
of `int`. If you try to pass this to a function, the matrix will decay
into a pointer to an array of `int`. That's not what you want.

If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass _that array_ to the function

```c++
int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}
```

For more information on this, see the section [Arrays and Pointers][] in
the C FAQ, and more specifically the questions 6.16 (_How can I
dynamically allocate a multidimensional array?_) and 6.19 (_How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?_).

[Arrays and Pointers]: http://c-faq.com/aryptr/index.html


body:
I am using an Arduino Mega to read a DS18B20 temperature sensor using the OneWire library in the code below which I got [here][1]:
<!-- language-all: lang-cpp -->

    #include <OneWire.h>

    #define DS18S20_Pin 20 //DS18S20 Signal pin on digital 20

    //Temperature chip i/o
    OneWire ds(DS18S20_Pin);  // on digital pin 20

     #define DS18S20_ID 0x10
     #define DS18B20_ID 0x28
     float temp;

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

    void loop(void) {
      boolean tempTest = getTemperature();
      Serial.println(tempTest);
      Serial.println(temp);

      delay(1000); //just here to slow down the output so it is easier to read

    }

     boolean getTemperature(){
     byte i;
     byte present = 0;
     byte data[12];
     byte addr[8];
     //find a device
     if (!ds.search(addr)) {
     ds.reset_search();
     return false;
     }
     if (OneWire::crc8( addr, 7) != addr[7]) {
     return false;
     }
     if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID) {
     return false;
     }
     ds.reset();
     ds.select(addr);
     // Start conversion
     ds.write(0x44, 1);
     // Wait some time...
     delay(850);
     present = ds.reset();
     ds.select(addr);
     // Issue Read scratchpad command
     ds.write(0xBE);
     // Receive 9 bytes
     for ( i = 0; i < 9; i++) {
     data[i] = ds.read();
     }
     // Calculate temperature value
     temp = ( (data[1] << 8) + data[0] )*0.0625;
     return true;
     }

When I use this code with the sensor attached to pins digital pins 20 or 21 it reads successfully, ok great, somehow by the grace of god I chose pin 20 on the first try. So then I move on to integrating my next sensor which utilizes the I2C and the Wire library, I should note that I am using [this][2] shield so I was able to connect right to the I2C without realizing I was using pins 20 and 21. Now, when I combined the two programs the I2C sensor was initialized second so it ended up getting the pins and the DS18B20 would fail to read, after pulling out my hair for a couple of hours I looked at a Mega pinout and realized it was on the I2C pins and thinking I finally figured it out I went to go and move the DS18B20 to one of the 52 other digital pins, this is when I came to the cold discovery that my DS18B20/OneWire will not work on any pins except pins 20 and 21 which I NEED for I2C. I have not checked every single digital pin but I have checked about half of them and nothing works except pins 20 and 21, I cant figure it out, nothing I can find mentions that OneWire uses or conflicts with the I2C connection.

More Info:

- Using latest OneWire

- I am not using DallasTemperature and would prefer not to, I could not get it to work whether on pins 20/21 or not

- I am using a resistor on the sensor

- I am currently only trying to run the code above to debug, no references to I2C sensor or Wire library whatsoever.

Thanks for reading and for any help, I am totally stumped here and thought I was avoiding some of these dumb double use pin issues by using the Mega instead of an Uno...

  [1]: https://tushev.org/articles/arduino/10/how-it-works-ds18b20-and-arduino
  [2]: https://www.dfrobot.com/product-560.html

title: OneWire with DS18B20 digital sensor only works on the I2C (20 and 21) pins of my Mega?

Answers: 0


body:
I am new to arduino programming and nodeMcu boards.I have two ESP8266 bards as access points and one board get some data form WiFi stations and resend that data to other access point. but the problem is second access point didn't receive any data packet from first access point.

This is the code of Access point which collect data and resend it to upper level Access point. This Access point successfully received the data from the WiFi stations.

    const char *ssid1 ="SecondAP";
    const char *pwd1 = "12345678910";

    const char *ssid2 ="FirstAP";
    const char *pwd2 = "123456789101";

    ESP8266WiFiMulti WiFiMulti;

    IPAddress local_IP(192,168,4,10);
    IPAddress gateway(192,168,4,9);
    IPAddress subnet(255,255,255,0);
    IPAddress NextAP(192,168,4,9);
    StaticJsonDocument<200> doc;
    unsigned int locPort1 = 1000;
    unsigned int locPort2 = 2000;
    WiFiUDP udp1;
    WiFiUDP udp2;
    char packetBuffer[100];
    IPAddress addrs;

    void setup() {

      Serial.begin(9600);
      delay(10);
      Serial.println('\n');

      ConnectToAP();
      delay(1000);
      EnableAP();
      delay(1000);

      udp1.begin(locPort1);
      udp2.begin(locPort2);
    }

    void loop() {

    int Icb = 0;

      Icb = udp1.parsePacket();

      if(Icb > 0){
          GetSensorDataPacket();
          Icb = 0;
        }
    }

    void EnableAP(){

      WiFi.softAPConfig(local_IP, gateway, subnet);
      WiFi.softAP(ssid2 , pwd2);
      delay(1000);

      Serial.print("Access Point \"");
      Serial.print(ssid2);
      Serial.println("\" started");
      Serial.print("IP address:\t");
      Serial.println(WiFi.softAPIP());
    }

    void ConnectToAP(){

      WiFi.mode(WIFI_STA);
      WiFiMulti.addAP(ssid1, pwd1);

      Serial.print("Connecting to ...........");
      Serial.print(ssid1); Serial.println("...");

      int i = 0;
      while (WiFiMulti.run() != WL_CONNECTED) {

       delay(1000);
       Serial.print(++i); Serial.print(' ');
      }

      Serial.println('\n');
      Serial.println("Connection established!");
      Serial.print("IP address:\t");
      Serial.println(WiFi.localIP());
    }

    void GetSensorDataPacket(){

      Serial.println("GetSensorDataPacket Function");
      udp1.read(packetBuffer,100);
      DeserializationError error = deserializeJson(doc, packetBuffer);

      IPAddress ClientAddrs = udp1.remoteIP();

      double SensorData = doc["SensorData"];
      int ClientID = doc["ID"];

      delay(1000);
      Serial.println();
      Serial.print("Sensor reading = ");
      Serial.println(SensorData);
      Serial.print("Client ID = ");
      Serial.println(ClientID);

      SendDataToNextAP(SensorData,ClientID);
    }

    void SendDataToNextAP(double Sensor_Data,int Client_ID){

      StaticJsonDocument<500> jsonBuffr;
      Serial.println("I'm in SendDataToNextAP Function");

      udp2.beginPacket(NextAP, locPort1); //gateway
      JsonObject Sob1 = jsonBuffr.to<JsonObject>();
      Sob1["SensorData"] = Sensor_Data;
      Sob1["ID"] = Client_ID;
      serializeJson(jsonBuffr, udp2);

      udp2.println();
      udp2.endPacket();

      delay(1000);
    }

  This is the code of upper Access point which should receive data packet from first access point but didn't receive any data from the first access point.

    const char *ssid = "SecondAP";
    const char *pwd = "12345678910";
    ESP8266WiFiMulti WiFiMulti;

    IPAddress local_IP(192,168,4,9); // Ip address of this node
    IPAddress gateway(192,168,3,1);
    IPAddress subnet(255,255,255,0);

    StaticJsonDocument<200> doc;
    unsigned int locPort1 = 1000;
    WiFiUDP udp1;
    char packetBuffer[100];

    void setup() {

      Serial.begin(9600);
      delay(10);
      Serial.println('\n');

      EnableAP();
      udp1.begin(locPort1);
      delay(1000);
    }

    void loop() {

    int Icb = 0;

      Icb = udp1.parsePacket();
      if(Icb > 0){
          Serial.println("Got a Udp packet");
          GetSensorDataPacket();
        }
    }

    void EnableAP(){

      WiFi.softAPConfig(local_IP, gateway, subnet);
      WiFi.softAP(ssid,pwd);
      delay(1000);

      Serial.print("Access Point \"");
      Serial.print(ssid);
      Serial.println("\" started");
      Serial.print("IP address:\t");
      Serial.println(WiFi.softAPIP());
    }

    void GetSensorDataPacket(){

      Serial.println("GetSensorDataPacket Function");
      udp1.read(packetBuffer,100);
      DeserializationError error = deserializeJson(doc, packetBuffer);

      IPAddress ClientAddrs = udp1.remoteIP();

      double SensorData = doc["SensorData"];
      int ClientID = doc["ID"];

      delay(1000);
      Serial.println();
      Serial.print("Sensor reading = ");
      Serial.println(SensorData);
      Serial.print("Client ID = ");
      Serial.println(ClientID);
    }

I couldn't find the reason for that. If anyone knows the solution for that please help me?

Thanks!

title: How to send UDP data packet between two access point?

Answers: 1

body: The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top AP has 192.168.4.x, set for the AP of the middle IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to send the UDP message.


body:
I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.
 [![Diagram of ESP8266 connected to Arduino nano Using Circuito example][1]][1]
After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.

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

title: My device doesn't recognize my Arduino

Answers: 1

body:
The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.

You need an external 3.3V regulator to power the ESP8266.


body:
On two of my Arduino Due, when connecting the pin `3.3V` to any digital inputs (`37`,`36`,`35`,`34`), no serial message nor `LED_BUILTIN` is thrown as output, only the `Test` message.

Digital Pins are set as `INPUT` by default. [`Blink`][1] works.

I have never connected any other thing on those pins, even 5V.

What I am missing?

    void setup() {
        Serial.begin(115200);
        while(!Serial);
        pinMode(LED_BUILTIN,OUTPUT);
        Serial.print("Test");
    }

    void loop() {
        if (digitalRead(37))
            Serial.print("37");
        if (digitalRead(36))
            Serial.print("36");
        if (digitalRead(35))
            Serial.print("35");
        if (digitalRead(34))
            Serial.print("34");
        digitalWrite(LED_BUILTIN,digitalRead(37));
    }

  [1]: https://www.arduino.cc/en/tutorial/blink

title: Arduino Due Digital Inputs without Response

Answers: 1

body:
A good practice is to set the pin mode for all the pins used by the sketch.

    void setup() {
        Serial.begin(115200);
        while(!Serial);
        pinMode(34, INPUT);
        pinMode(35, INPUT);
        pinMode(36, INPUT);
        pinMode(37, INPUT);
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.print("Test");
    }

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.

Cheers!


body:
I am creating a project with an ESP8266 (Arduino IDE) which requires it to serve a webpage to a client. The module will be connected to a WiFi network by default, but when that WiFi network is not available, I need it to turn on its Soft Access Point, so that the user can still access that webpage by connecting to the AP. When the WiFi network becomes available, I want the module to reconnect to the WiFi network and disable the SoftAP.

Here is the chunk of code in my sketch that deals with all the WiFi stuff:

<!-- language: lang-c -->
```
void wifi() {
  if(WiFi.status() != WL_CONNECTED){
    WiFi.mode(WIFI_AP_STA);

    if((unsigned long)(millis() - waitUntil) >= interval){            //this section I used as an alternative to the delay() function, the delay is 3 sec
      WiFi.begin(ssid, password);
      waitUntil = waitUntil + interval;

      if(WiFi.status() == WL_CONNECTED){
        Serial.println("Connection successful! ");
        Serial.print("IP: ");
        Serial.print(WiFi.localIP());
        WiFi.softAPdisconnect(true);
      }
    }
  }

  if(WiFi.status() != WL_CONNECTED && softAPEnabled == false){
    Serial.println("WiFi not connected, enabling SoftAP...");

    WiFi.softAP(softAP_ssid, softAP_password);

    softAPEnabled = true;

    Serial.println("SoftAP ON");
  }
  else if(WiFi.status() == WL_CONNECTED && softAPEnabled == true){
    WiFi.softAPdisconnect(true);
    softAPEnabled = false;
    Serial.println("SoftAP OFF");
  }
}
```

Here are the problems:

1. The webpage works fine when the module is connected to WiFi and I go to the IP address from a browser, but when SoftAP mode is enabled, and I connect to the AP and go to 192.168.1.1, it does not work. The next problem may be related to this.

2. I don't think I'm using WiFi.mode() correctly. I currently have it set to WIFI_AP_STA, but after problem 1 occurred, I tried to change it to WIFI_AP and WIFI_STA individually as I needed each mode, but this still did not work.

title: How do I properly use the WiFi capabilities of ESP8266?

Answers: 1

body:
The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings