text:
DHT11 sensor providing -999 outputs
I'm new here, trying to learn Arduino by hacking, that is plugging stuff in, looking for code and then trying to understand it bit by bit so I can move on to bigger and better projects.
My issue is that I am getting a periodic readout of -999.0 from a 3 pin DHT11 temperature and humidity sensor in between actual readouts. I can't find anything online explaining this but maybe I haven't looked hard enough. Attached is a screenshot containing both the code and serial monitor readout. Mechanical engineering background, so no electronic knowledge but feel free to get techy with your response.
if the image doesn't load this is the code;
#include <dht.h>

dht DHT;

#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  constrain (DHT.temperature, -25, 70);
  constrain (DHT.humidity, 0, 90);

  if((DHT.temperature || DHT.humidity) > -25)
  {
  Serial.print("Temperature, Humidity = ");
  Serial.print(DHT.temperature);
  Serial.print(", ");
  Serial.println(DHT.humidity);
  delay(1000);
  }
}

Thanks in advance for help or direction to help.

-999 means that it didn't get a result from the DHT.  You need to filter them out - which you are attempting to do, but wrongly.
Your line of code:
if((DHT.temperature || DHT.humidity) > -25) {

is not doing what you thing it is.
If you start from the inner most brackets and "reduce", you get:
Is DHT.temperature or DHT.humidity?

That makes no real sense - except in C any number that isn't 0 is "true" and 0 is "false", so that really means:
Is DHT.temperature not 0 or DHT.humidity not 0?

And of course that will be "true" in 99.99999% of situations.  So insert that into the if again:
if (true > -25) {

Is true more than -25? Well, the reverse of what I stated above is also true: "true" is 1 and "false" is 0.  So is 1 greater than -25? Yes. It is.
Instead you should be testing each value separately:
if ((DHT.temperature > -25) && (DHT.humidity > -25)) {

Also your constraints are doing nothing.  constrain() doesn't modify (limit) the variable you pass to it. Instead it takes the value in that variable, constrains it, and returns the new constrained value to you for you to assign to a new variable.  So you should:
float temperature = constrain (DHT.temperature, -25, 70);

And then you can use the temperature variable instead of DHT.temperature, and you can guarantee that it will be between -25 and +70.

As I recall you're not supposed to read from a DHT11 or DHT22 more frequently than every 2 seconds. If you wait until 2 seconds pass before reading again you should avoid -999 readings.
Majenko's answer shows you how to check for and skip out-of-range readings, but only reading once every 2 seconds should let you avoid them entirely.
Note that you should also check for NaN (not a number) values returned. That means there was a read error, which does happen from time to time.

Try to use Pull up resistor. Connect the 4.7K resistor parallel to 5v (if your supply for DHT11 is 5v 4.7K is Good, for other voltage, you need another value of resistor) and Data pin.


text:
When are global constuctors executed?
Apologies if this has been discussed before but I couldn't find anything.
I have written a simple LED class. For illustration (it is actually a bit more complex) but it goes something like;
class LED {
    LED(byte pin);
  private:
    int _pin;
};

And the constructor is simply;
LED::LED(byte pin) {
    _pin = pin;
};

and I create a global instance of this class at the top of my code thus;
LED redLED(5);

It is necessary to create this as a global object because (a) I can't create the object in the setup() function because it would go out of scope and (b) I can't create in the loop() function because I don't want to create an infinite number of these objects.
This all seems to work OK but it just leaves me wondering exactly when this constructor gets executed? I suppose that it must be before setup()?
Answered!
Many thanks to all the respondents. So when using the Arduino IDE the build process must silently insert the main() procedure. I was not aware that it did this. I guess that most of the time you can get away with not knowing when the global constructors are called.
It is good practice (I think) to create a "wrapper" class for all/any external (or perhaps internal) hardware devices that are connected to your arduino. And it is thus perhaps tempting (but risky) to do initialisation work in the constructor.
So given what I now know, it is better to create an "init()" method for such classes that can be called from setup(). Even if just to do the the pinmode() call.
Thanks again.

Re “the build process must silently insert the main() procedure”: It is provided by the Arduino core library. Re “it is better to create an ‘init()’ method”: It would seem that begin() is the canonical name for such a method.

The global constructors run right after the initializations performed by
the C runtime startup code, and right before main() gets called.
In a nutshell, the C runtime initialization code:

does some low-level initializations (e.g., setup the memory)
calls the global constructors
calls main(), which in turn

calls init() to do the Arduino-specific initializations
calls setup()
repeatedly calls loop()

The fine details are probably platform-specific. For AVR-based boards,
they are documented in the avr-libc manual.

class LED {
private:
  const byte _pin;
public:
  LED(const byte pin);
};

With an even simpler c'tor:
LED::LED(const byte pin) : _pin(pin) {};

To be a bit on-topic: The initializer list is even executed before the constructor body, and is thus the way to initialize constants.
Question remains whether it's guaranteed that this works:
class LED {
private:
  const byte _pin;
public;
  LED(const byte pin) : _pin(pin) {pinMode(_pin,OUTPUT);}
  set(bool state) {digitalWrite(_pin, state); }
};

( Can pinMode be called that early, or should one invent an init() method? )
My experience says : works well ...

Note that the constructor runs before the Arduino core is initialized. Are you sure it works well on every Arduino board? On AVR, it sure does, because pinMode() happens to not rely on the Arduino core being ready.

I have only tested this on a Nano

It is executed before the main() is called (in the main() there is setup() called and then loop() is called in infinite loop).
It has its own sections for the constructors and destructors:
http://beefchunk.com/documentation/sys-programming/binary_formats/elf/elf_from_the_programmers_perspective/node4.html

source: Stack Exchange

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

sort: votes


text:
Problems uploading with a new Nano
My first post - I am a relative newbie.
I want to make a smartcontroller for my boat - I have built the electronics and written and tested a sketch for the Nano, all working totally fine. I then decided that I would  like to keep my existing Nano (Nano-A) as a development system and buy another one (Nano-B) to actually deploy. Both of these are cheap chinese clones (from different suppliers).
However I cannot upload anything to Nano-B. It seems to be basically working (LEDs flash) but not wishing to accept any sketch uploads. The COM port seems to be working OK and I have tried all the various options available in the Arduino IDE (boards, programmers etc.) without success.
So I came to the conclusion that possibly the bootloader on Nano-B needs to be re-flashed.
So I setup Nano-A as a programmer, loaded up "ArduinoISP", connected up the ISP pins and hit "burn bootloader".
It seems as if this is "nearly working". I have turned on the -v (verbose) option for avrdude and pasted the log below. It looks to me as if the IDE is invoking avrdude twice; (1) To set the Fuses etc, and (2) to upload the actual bootloader. I seems that (1) is working OK but (2) is failing.
I've been tearing my hair out for about 3 weeks with this and would be really keen to get some ideas.
Thanks in advance.
Arduino "burn bootloader" IDE Log - follows;
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

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\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8

         Using Programmer              : stk500v1

         Overriding Baud Rate          : 19200

         AVR Part                      : ATmega328P

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PC2

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500

         Description     : Atmel STK500 Version 1.x firmware

         Hardware Version: 2

         Firmware Version: 1.18

         Topcard         : Unknown

         Vtarget         : 0.0 V

         Varef           : 0.0 V

         Oscillator      : Off

         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: erasing chip

avrdude: reading input file "0x3F"

avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lock written

avrdude: verifying lock memory against 0x3F:

avrdude: load data lock data from input file 0x3F:

avrdude: input file 0x3F contains 1 bytes

avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of lock verified

avrdude: reading input file "0xFD"

avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of efuse written

avrdude: verifying efuse memory against 0xFD:

avrdude: load data efuse data from input file 0xFD:

avrdude: input file 0xFD contains 1 bytes

avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of efuse verified

avrdude: reading input file "0xDA"

avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of hfuse written

avrdude: verifying hfuse memory against 0xDA:

avrdude: load data hfuse data from input file 0xDA:

avrdude: input file 0xDA contains 1 bytes

avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of hfuse verified

avrdude: reading input file "0xFF"

avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lfuse written

avrdude: verifying lfuse memory against 0xFF:

avrdude: load data lfuse data from input file 0xFF:

avrdude: input file 0xFF contains 1 bytes

avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...

avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -Uflash:w:C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:i -Ulock:w:0x0F:m

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\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM8

         Using Programmer              : stk500v1

         Overriding Baud Rate          : 19200

         AVR Part                      : ATmega328P

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PC2

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff

           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500

         Description     : Atmel STK500 Version 1.x firmware

         Hardware Version: 2

         Firmware Version: 1.18

         Topcard         : Unknown

         Vtarget         : 0.0 V

         Varef           : 0.0 V

         Oscillator      : Off

         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed

         To disable this feature, specify the -D option.

avrdude: erasing chip

avrdude: reading input file "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"

avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_cmd(): programmer is out of sync

avrdude: stk500_cmd(): programmer is out of sync

avrdude: stk500_cmd(): programmer is out of sync

avrdude: 32768 bytes of flash written

avrdude: verifying flash memory against C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

avrdude: load data flash data from input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:

avrdude: input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes

avrdude: reading on-chip flash data:

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

avrdude: loadaddr(): (b) protocol error, expect=0x14, resp=0x3f

avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x10

avrdude: stk500_cmd(): protocol error

avr_read(): error reading address 0x7e01

    read operation not supported for memory "flash"

avrdude: failed to read all of flash memory, rc=-2

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xff

avrdude done.  Thank you.

Error while burning bootloader.

Edit ... Connections between the Arduinos. Nano A is the programmer. Nano B is the target

Nano A    Nano B
ISP 1  --     ISP 1 (MISO)
ISP 2  --     ISP 2 (VCC - 5v)
ISP 3  --     ISP 3 (SCK)
ISP 4  --     ISP 4 (MOSI)
ISP 6  --     ISP 6 (GND)
D10    --     ISP 5 (RESET)

I have also now added a 60ohm resistor between RESET and +5V on Nano A
I have also tried connecting a capacitor between RESET and GND. (2uF and 100uF - I didn't have a 10uF) - but it made no difference
Further investigations.
I have tried running avrdude in "terminal" mode and can confirm that I can do all of the usual read/write operations except writing to anywhere in flash memory. This seems to be the only operation that does not work. I will now try breaking down the flash write operation into the individual SPI programming instructions to see if I can work out where it is failing. I suspect that my MCU is a "brick" but I have learned loads!
Another edit;
I have now been using the avrdude terminal mode "send" command to step throuh the individual SPI operations one at a time to write flash memory and hey! it works! (see below)

So, if this works, why does ArduinoISP fail to load the bootloader?
I will set this up as another/new question

What, if anything, did you do with the reset signal on the nano that runs the arduinoisp.ino sketch?

Could you show how you've connected both Nano's?

I have connected the two nanos using the 6 pin ISP headers. as follows;

@RobW: please [edit] your question to add details, don't add them as comments

I have now fixed this problem, but still do not fully understand what the original problem was.
Please see my other post on this qusetion to see what I did
Link to other post

There is more then one bootloader in the Nano's, a new one and the old one. I had the same problem so I simply went to tools in the IDE and switched from the new  to the old, it solved my problems.

Thanks Gil - This is one of the first things that I tried - without success.

Sorry I am out of ideas. I hope somebody can help you.

Perhaps this isn't the answer to the bootloader issue but I went through the same thing recently, I realized a little late about what was exactly the problem, so I checked the uC on the Nano Board and it has an ATMega168 instead of the normal ATMega328p.
So if you are using ArduinoIDE you need to check the ATMega168 option while you are selecting your uC chip (as in the picture above)... Sometimes (as it happened to me, just going for the basics solve all the problems)
Hope this could help you mate

Thanks Cyborg. I had a look at the uC and it is an ATMega328p. Interestingly (perhaps) it is a lot bigger that the uC that is on the other Nano - also a 328p

Yeah mate, this link may help you to learn something new about ATMega328p packages: https://www.eeweb.com/the-different-atmega328-packages/

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


text:
Can't get "Burn Bootloader" working - Arduino Nano
This is a follow up from a previous question. I have one Nano working perfectly (I think) (Nano A) and another one (Nano B) which seems to be working but has no bootloader. So I am trying to use Nano-A as an ISP programmer to burn the bootloader into Nano-B. I am pretty confident with my hardware and Arduino IDE setup. See previous question for the details; Problems uploading with a new Nano
I have pasted below two screen sessions. The first shows the Arduino IDE Log when I (unsuccesfully) try to run "Burn Bootloader" - IT almost works! (but not quite). - So I beleive that there is not too much wrong with my setup.
The second session is me using running avrdude in "terminal" mode from a Windows command prompt. I have used individual "send" commands to send the ISP instructions required to programme a single word into bootloader flash memory and this all seems to work OK. So I don't understand why avrdude is not working when invoked by the IDE.
Arduino IDE Log (lengthy)
C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m

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\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: erasing chip
avrdude: reading input file "0x3F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x3F:
avrdude: load data lock data from input file 0x3F:
avrdude: input file 0x3F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of lock verified
avrdude: reading input file "0xFD"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFD:
avrdude: load data efuse data from input file 0xFD:
avrdude: input file 0xFD contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xDA"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDA:
avrdude: load data hfuse data from input file 0xDA:
avrdude: input file 0xDA contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.04s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

C:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -Uflash:w:C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:i -Ulock:w:0x0F:m

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\--\Documents\ArduinoData\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.11s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_cmd(): programmer is out of sync
avrdude: stk500_cmd(): programmer is out of sync
avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: load data flash data from input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: input file C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

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

avrdude: loadaddr(): (b) protocol error, expect=0x14, resp=0xc0

avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x10
avrdude: stk500_cmd(): protocol error
avr_read(): error reading address 0x7e00
    read operation not supported for memory "flash"
avrdude: failed to read all of flash memory, rc=-2
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xd1

avrdude done.  Thank you.

Error while burning bootloader.

avrdude session (short)

Note that when writing to the bootloader flash, using the "send" instruction, you have to supply the address as a "word" - i.e. 16bit address - hence 0x3C00. When usning the "read" instruction, the address is a "byte" (8 bit) address, hence 0x7800 - this is the same address.
Update: I have now managed to upload my original sketch to the application area of flash on this Nano using the "Sketch->upload using programmer" menu option of the Arduino IDE. So I do now have a useable Nano but I have still not solved my original problem i.e. this  Nano still does not have a bootloader. I would like to fix this problem becaue I am sure that I will want to update/modify my app int the future. So there is now an ancilliary question - i.e. is it possible to burn a  bootloader without erasing a pre-existing application? - Answer, I think is no because maybe you have to do a chip erase before writing to the bootloader area?

Dear timemage - once again that is really useful I will give it a try with the addresses that you suggest. The reason why I said 0x7C00 (which I now realise is wrong anyway) is that the hfuse setting is 0xDA which is binary 10111010 - i.e. the "BOOTSZ" bits are 01 which according, to the datasheet, should give a bootloader size of 1024 words. So is the correct start address 0x3C00?

Alright, so this is bizarre. I tried it here just as a sanity check. Although my setup is a bit different than yours, I don't have a normal nano to work with.  I'm using an UNO as my target but programming it to be a nano. There's essentially no difference hardware-wise.  I can confirm that it fuses 0xDA but puts the 512 byte optiboot program on it.  Apparently is basically NOP-sliding from the configured reset vector at 0x3C00 to where the bootloader code actually begins at what would be the UNO reset vector 0x3f00.  Anyway, it's stupid but it works.

Thanks again - I have now updated my question as suggested. Now that I have got my addresses sorted out I can see that the avrdude "send" commands are able to write into the bootloader area OK. So it's beginning to like my problem has  something to do with the way that arduino IDE invokes avrdude - I'll now look more carefully at this.

Show the wiring I guess.

I'm thinking that if I can get avrdude to  use Nano A as an ISP programmer in terminal mode, then doesnt this prove that the wiring is OK?

It suggests to me that it's not so bad that it is failing constantly.

I now semi-understand why the fuses are being set to start the bootloader area at 0x7800 - I thk that it's because the Arduino IDE supports a couple of different options for nano bootloaders. It's a  bit dumb I guess.

Yay! - I now have a fully working Nano with new bootloader and application loaded using this.
I have done so much that I'm not sure what the original problem was but the final change was modifying the "programmers.txt" file such that "Arduino as ISP" entry was changed as follows;
Original line;
arduinoasisp.protocol=stk500v1

Changed to;
arduinoasisp.protocol=arduino

I did this because I noticed that the menu option "Upload using programmer" (which worked) invoked avrdude with the parameter "-c arduino" whereas the "burn bootloader" option used "-c stk500v1" (which was not working).
I can't pretened that I fully understand but I'm happy that this now works and that I have now learnt enough to know where to start looking if I get similar problems in the future.
I should also add that I would never have got here without the help of @timemage - who has helped a lot - many many thanks

There are differences between stk500v1 and "arduino" in terms of how reset is explicitly handled and how signatures are read; otherwise they're the same.  I have no idea why this would fix your problem.  What is it that made you try this to begin with?

I looked closely at the Arduino IDE logs - especially the avrdude invokations - to see what the IDE was doing differently between (1) "Upload using programmer" (which was working) and (2) "Burn bootloader" (which was not working) and noticed that the "burn bootloader" invokation had the "-c stk500v1" parameter.

Well, I'm glad something is working. But I am skeptical that alone is the cause and solution.  It fails and then works again consistently with changing that option back and forth?

I suspect that the original problem was that there was something amiss in the supplied  configuration of the cheap chinese nano clone that I bought on eBay. I suspect that it may have been supplied without a bootloader, but I do not know this for sure. So  I cannot get back to my original starting point, unless I order another Nano from the same supplier, which I might do, just for the hell of it. At £3.00  it might be worth it just to prove my theory. I have purchased two other cheap Nano clones from other suppliers and have not had any problems. I share your skepticism.


text:
Decode rf remote signals with ESP32 or node MCU?
I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```

Please include the wiring and your code into the question. You can edit it to add these information.

Maybe it's related with 3.3V/5V difference?

@chrisl I have also put up the code

@MichelKeijzers I used the vin pin on both the boards which provide 5v and the reciever also works on 5v so I don't this that's the case and also I used the 5v pin on Arduino just to be sure

io 0 has a pull-up resistor because it is a boot config pin and on esp the interrupt pin numbers are the same as the labels on ocb

I thought ESP32 was 3.3V (but it was just an idea it might be caused by voltage difference).

For ESP32, you should provide real GPIO number.
For instance:
mySwitch.enableReceive(13);
And without deep explanation, believe that it properly works
with GPIO 13 and 27.
Details you can find by google...


text:
What is an ICSP pin?
What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

When would you use the ISPC Header?

@DavidAbela ISP or ICSP (same meaning) is used mainly when developing complex applications onto the ATMega328 (where the Arduino IDE doesn't suffice: https://www.instructables.com/id/Using-an-In-System-Programmer). Since most users aren't creating complex projects, very few users need it.

ICSP stands for In Circuit Serial Programming, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.
A typical Arduino ICSP header has six pins, arranged 2x3.  The article Connecting the Programmer:
In-Circuit Serial Programming (ICSP) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.
Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.
Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

AVR refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an ARM instruction set architecture.

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


text:
Continuous push button detection in for Stepper control
Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards.
but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW,  That means it cannot detect the press of another pushbutton to make it counterclockwise.
I realize that the program isn't detecting the second push button after pressing 1st one.
Tried different options to make it work. but failed.
any suggestions?
Here's my code for reference:-

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.
it would be a great help pointing out my mistakes.

See Arduino - button does not work

Hi can't it be done simply by coding?

What is your debug output saying? It's probably printing a lot. How often does it change between ok and ok2? Add a "stop" state (with Serial debug output), forget about the motor until you see the expected output lines properly. What should happen if both buttons are pressed? Should that kill the motor?

 That means it cannot detect the press of another pushbutton to make it counter clock wise Why is that? How did you connect the buttons. | Also, I would set the max speed in the setup function since you only have to do this once.

this looks great, is there anything else i need to do to add a stepper, im struggling a bit, but with some friendly makers helping i know ill get this sorted. as im new to this site, G'Day FROM AUSTRALIA!!!!!!

I implemented your code here on a UNO using 2 pushbuttons (with the stepper motor functions commented out) and it seems to work fine.  When I press button1 I get a lot of "ok" printouts for as long as the button is held down. When I press button2, the same thing happens except with "ok2" instead of "ok".
Here's the code I used:
/*
    Name:       TwoPushButtonTest.ino
    Created:    9/28/2020 2:36:07 PM
    Author:     FRANKNEWXPS15\Frank
*/

//#include <AccelStepper.h>

const int button1Pin = A2;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

//AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);

  Serial.begin(115200);
}

void loop()
{

  //int sensorReading = analogRead(A0);
  //int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  //stepper.setMaxSpeed(2000);
  //stepper.setSpeed(motorSpeed);

  if (button1State == HIGH)
  {

    Serial.print("ok");
    //stepper.setSpeed(motorSpeed);
    //stepper.runSpeed();

  }

  if (button2State == HIGH)
  {

    Serial.print("ok2");
    //stepper.setSpeed(-motorSpeed);
    //stepper.runSpeed();

  }
}

and here's the wiring diagram:

Note the two 10K pull-down resistors.  If these are not present, then the A2/A3 inputs are indeterminate whenever the buttons are in the 'disconnected' state, and anything can happen.


text:
Help with millis to get accurate timing
I'm essentially trying to create a music box which is light activated using an LDR. When it's open a song plays, while a servo rotates a figurine back and forth, and an LED dims and illuminates in sync with the servo. The code sort of works when I don't include the analogWrite for the LED, but even then the music timing is not great. When I do include analogWrite for the LED the music is completely distorted and doesn't work whatsoever. Is there some obvious mistake I've made? Is millis just bad for keeping time? I'm sure there is a better way to approach this overall, but I'm still an amateur at arduino. My code works by using an array for the notes and the duration of each. I refer to the duration array and use it as dynamic intervals for my millis to keep time. Hopefully that makes sense, my coding jargon is pretty basic!
    #include <Servo.h>

//defining the value of the notes
#define NOTE_C4  262
#define NOTE_D4  294
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_G4  392
#define NOTE_A4  440
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_D5  587
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_G5  784
#define NOTE_A5  880
#define NOTE_B5  988

//order of the notes
int melody[] = {
   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,

   NOTE_A4, NOTE_A4,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
   NOTE_A4, NOTE_G4, NOTE_A4, 0,

   NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
   NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
   NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

   NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
   NOTE_D5, NOTE_E5, NOTE_A4, 0,
   NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
   NOTE_C5, NOTE_A4, NOTE_B4, 0,

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4,

   NOTE_E5, 0, 0, NOTE_F5, 0, 0,
   NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
   NOTE_D5, 0, 0, NOTE_C5, 0, 0,
   NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4
};

// duration of each note
int duration[] = {
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,

  250, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 125,

  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 250, 125, 125,
  125, 125, 125, 250, 125,

  125, 125, 250, 125, 125,
  250, 125, 250, 125,
  125, 125, 250, 125, 125,
  125, 125, 375, 375,

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 500,

  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 125, 125, 125, 375,
  250, 125, 375, 250, 125, 375,
  125, 125, 125, 125, 125, 3000
};

Servo myservo;  // create servo object to control a servo

int servoPin = 9;
int ledPin = 11;
int buzzerPin = 3;
int sensorPin = A4;
int sweep = 0; // variable to control which direction the servo is moving
int sensorValue = 0;
int counter = 0; //a counter to keep track of which note the song is up to
float tempo = 1; // a variable for the tempo - lower number = faster temp (2 =  double speed)
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
int threshold = 500;

void setup()
{
  myservo.attach (servoPin);
  pinMode (ledPin, OUTPUT);
  pinMode (buzzerPin, OUTPUT);
  pinMode (sensorPin, INPUT);
  Serial.begin(9600);
}

void loop(){

sensorValue = analogRead (sensorPin);
if (sensorValue > threshold)
{

  if (sweep == 0)
  {

    for (int pos = 0; pos <= 180; pos ++) // goes from 0 degrees to 180 degrees in steps of 1 degree
    {
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      analogWrite(ledPin, map(pos, 0, 180, 0, 255)); //mapping the value from the for loop to get the full range of PWM for led fading

        currentMillis = millis();
        if (currentMillis - previousMillis > duration[counter]/tempo)
        {
          tone(buzzerPin, melody[counter], duration[counter]/tempo);
          counter++;
          previousMillis = currentMillis;
        }

          if (counter == 196)
          {
            counter = 0; //reset the counter so the song starts again
          }

            if (pos == 179)
            {
              Serial.println("SWEEP 1");
              sweep = 1;
            }

              sensorValue = analogRead (sensorPin);
              if (sensorValue < threshold)
                {
                  break;
                }
     }
  }

  if (sweep == 1)
  {

    for (int pos = 180; pos >= 0; pos --)  // goes from 180 degrees to 0 degrees
    {
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      analogWrite(ledPin, map(pos, 0, 180, 0, 255));

       currentMillis = millis();
       if (currentMillis - previousMillis > duration[counter]/tempo)
        {
          tone(buzzerPin, melody[counter], duration[counter]/tempo);
          counter++;
          previousMillis = currentMillis;
        }

          if (counter == 196)
          {
            counter = 0;
          }

            if (pos == 1)
            {
              sweep = 0;
              Serial.println("SWEEP 2");
            }

              sensorValue = analogRead (sensorPin);
              if (sensorValue < threshold)
                {
                  break;
                }
    }
  }
}

   if (sensorValue <= threshold) //if the light is low turn the servo back to starting point and stop doing anything
   {
    Serial.println("OFF");
    noTone(buzzerPin);
    myservo.write(0);
    counter = 0;
   }
}

What board are you using? Try moving the LED to pin 5, 6 or 10 (on Uno), tone and analogWrite would be using the same timer on pins 3 and 11 on a Uno, which sounds problematic.

What Mat said.
Also, the music timing is inside the for loop that drives the servo; you could also decouple those and set up a millis timer for the music and a millis timer for the servo and let the loop do its work without the for loop. That won't solve the timer problem, but the code would be much shorter and easier to read, and the music and servo timings would be independent (but tuneable). I'll post code that shows how to do that in an answer if you want.

@Mat Arduino pin 10 uses the same timer for PWM as the servo library does (timer 1). So I'd stick with Arduino pin 5 or 6 for the LED.

@Gerben: ah good point. Or maybe just put the LED on the same pin as the servo if that's it is just supposed to be on when the servo moves. Frees up a timer :-)

If you're still interested in refactored code, here is your code with for loops removed and restructured so state is tracked/updated appropriately in the void loop() as below:
[your variable declaration code as given]
...
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
int threshold = 500;

int pos = 0;
int dir = 1;

void setup()
{
  myservo.attach (servoPin);
  pinMode (ledPin, OUTPUT);
  pinMode (buzzerPin, OUTPUT);
  pinMode (sensorPin, INPUT);
  Serial.begin(9600);
  pos = 0;
  dir = 1;
  previousMillis = millis();
}

void loop(){

    sensorValue = analogRead (sensorPin);
    if (sensorValue > threshold)
    {
        pos += dir;
        if (pos == 180) || (pos == 0)
        {
            dir *= -1;
        }

        myservo.write(pos);
        analogWrite(ledPin, map(pos, 0, 180, 0, 255));

        currentMillis = millis();

        if ((currentMillis - previousMillis) > duration[counter]/tempo)
        {
            tone(buzzerPin, melody[counter], duration[counter]/tempo);
            counter += (counter > 195) ? -196 : 1;
            previousMillis = currentMillis;
        }
    }
    else
    {
        Serial.println("OFF");
        noTone(buzzerPin);
        myservo.write(0);
        counter = 0;
        pos = 0;
        dir = 1;
    }
}


text:
BLE HM10 - Set Password - Android Pairing Problem
I have developed an application on Android, which connects to a Bluetooth HM10, launches commands, and turns LEDs on and off through my Arduino. All of this works properly.
So, I want to make Bluetooth secure, so that nobody can connect to it, and keep it busy and I can't connect myself.
To do this, from my Serial Monitor I execute the corresponding configuration commands, but I never get it to link correctly on my Android.
I have tried many options, to no avail:
OPTION 1)

AT+ROLE? = Ok+Get:0 (Slave or Periphe)
AT+TYPE2 = Ok+Set:2 (Auth with PIN)
AT+PASS123456
AT+RESET

OPTION 2)

AT+ROLE? = Ok+Get:0 (Slave or Periphe)
AT+TYPE3 = Ok+Set:3 (Auth and bond)
AT+PASS123456
AT+RESET

In both cases (and more failed tests), I see the BLE device on my Android Bluetooth.
I give it to connect and the window to enter the password pops up.
I introduce 123456
And it always tells me that it could not be linked.
Any ideas for why?
Thank you.

I'm not an expert but the AT commands seems a bit strange. e.g. I would expect to enter a new PIN with AT+PASS123456. Perhaps the space is part of the PIN in your case. Just a guess. Also, the question mark after PASS is used (AFAIK) to read the PIN, not to set it. Just some guesses, without knowing much about AT commands. Perhaps it works. Cheers.

The ROLE command also has a question mark. But as 0 is the default it is not a problem. PASS is just an alias for PIN so the official AT-command to set a new PIN is AT+PIN123456.

As you set the type to 3, the module requires authentication, but (I guess) the password/PIN is still 000000.

@PeterPaulKiefer I have modified the initial message, because yes, I put it wrong. The password setting is without "?"
And, no, I am not putting any spaces after the password. I have made sure they are only 6 digits, clean, with no spaces.

@PeterPaulKiefer
AT+PIN? it never gives me a value of OK, with the default pin.
And AT+PIN123456 does not react the Bluetooh module for that command.

@PeterPaulKiefer I have tried AT+TYPE1, AT+TYPE2 and AT+TYPE3 right now, with Pin 000000 and I cannot link it

I wrote about the space before the PIN. I don't know if AT commands may have spaces between their parts. I only know the compact versions. ATPIN? does not respond? What about the other commands? Do they respond? Have you tried AT+RENEW before the other commands? That would reset to the factory setup.

For the HM10 model, the AT commands above do not respond. They are not supported. Its specification in the DataSheet (https://people.ece.cornell.edu/land/courses/ece4760/PIC32/uart/HM10/DSD%20TECH%20HM-10%20datasheet.pdf) defines that the commands are AT+. They never have spaces between the command and the values to assign. The commands and the values to be assigned are continuous. And the AT+RENEW command, effectively, resets to factory values, which, I have tried many times.

ATPIN? was a typo I made in a text I repeated from your comment. I know that AT+ is the AT-command prefix. I also know he spec. But I was not sure if spaces are allowed, sometimes specs and reality differ ;-).  Your last comment lets me think, that the communication between the Arduino and the HM10 does not work. I have no idea, why. You could edit your question and add the code that runs on the Arduino. And a schematic of you setup would also be helpful.

Don't say that the setup works without authentication. In this case the Module communicates with the arduino. When you try to configure the HM10 from the serial monitor that's the other direction. Or do you configure the HM10 direct from your PC/Laptop without a Arduino between?

@PeterPaulKiefer The communication between Arduino and HM10 works perfectly because if I run AT+PASS123456 and then turn off the arduino, turn on the arduino and do an AT+PASS? returns Ok:Get:123456. So the communication is correct. In addition, without securing the HM10, I can send commands from Android, I turn off LEDs and turn on LEDs on my protoboard, via bluetooth. So it works. It only fails to secure the HM10

When I say that the communication works without authentication, I mean that from my Android application, I pair with the HM10 (automatically, from programming, without password or anything), I launch commands, the arduino picks them up, and I turn LEDs off and on. At the moment that I secure HM10 (by setting it with an authentication configuration), I cannot pair with the HM10 from the Android application because it asks me for a password and the password never works.

I configure HM10 from Arduino, using the Serial Monitor (as I mentioned in my initial post).

You could use the Serial monitor with the Arduino in between the PC and the HM10 or you can connect the HM10 direct to the PC. That's what I asked for. You also commented that the AT+PASS? does not respond. Now you comment that it responsed with the correct PIN. What is true? --- I'll stop this discussion now. Sorry, but I have not the time to guess what you might want to say. And my english is not good enough to correct yours. --- One final tip: perhaps the bluetoth authenticaten mechanism differs between the peers.

I can't connect my HM10 to my computer, because it's a Mac, and Macs can only connect to factory Bluetooth.
At all times I have said that the execution of AT+PASS commands both to obtain the password and to define a new one, have always worked well. And when I say that they have worked well, it means that the HM10 module has answered "Ok" for all cases.
The problem, as the post describes, is that from an Android device, I cannot pair the HM10.

I live similar problem.
http://kio4.com/arduino/161_HM10_BLE_Actualizar.htm
Your page is very very successful.All the instructions are working.
I will use the pio for opening the door of my car.
Thank you very very much for you help. I have a problem but.I give password to module and give the typr 3 or 2 .I try this but iphone asks for paşrşng password.I wrote wrong password but system connects and works.Beaceuse of this issue I can not use on my car because, if I wrote wrong pin it connects also.There is no password protection on the car than.so I cannot solve the password problem.What must I


text:
Where can I know voltage between GND(ground) and each port of UNO R3?
Currently I'm new to arduino uno r3.
Where can I find each voltage between each port and GND(ground)?
Or can the voltage be changed?
I don't want to break my led bulbs since large difference of 2 potentials

I don't really understand, what you mean. But the Uno runs on 5V, so the maximum voltage on its pins imposed by it is 5V.

I see. I'm too new to arduino.

https://majenko.co.uk/blog/what-exactly-gpio-pin

I'll read the article.

Maybe using a voltmeter?

You can measure each one at the output of the port (where you plug a connecting-wire to the port). Measure from that wire to ground with your DVM. It should be either 0v or 5v, depending on whether the port is set LOW or HIGH. (Or it could be pulsing from 0v - 5v - 0v - ... , if it is one of the PWM ports and the port has been set to provide a PWM output.) If the pin is in INPUT mode (and not INPUT_PULLUP), you're likely to read noise picked up by the connection between the pin and the meter, as an INPUT pin will be in high-impedance mode - no voltage will be asserted by the MCU, so the connection will behave almost like an un-connected wire, e.g., an antenna.

5[V] is ideal EMF(electromotive force) of arduino UNO R3.
Since I stated "ideal" ,the actual EMF be slightly lower than 5[V].
In this instance , EMF can be assumed as voltage between GND and port of UNO R3 as ports are connected only by a wire.

EMF (Electromotive Force)? That’s a rather odd term to use in this instance. Just voltage will do.

5V is not the EMF or Voltage of an Arduino Uno. It is the EMF or Voltage the microcontroller of the Arduino Uno (ATmega328) should be supplied with. If a digital pin is set to be high, it will have a voltage slightly under the supply voltage, depending of the amount of current that is drawn from that pin.

Oh,I see. I edited the answer.


text:
I'm desperate and need help with MFRC522 (stops working randomly)
I've made a light switcher that switches lights on for 15s after a correct tag is presented, and also when door is opened for 6 seconds (its for outside) so i can see a keyhole after leaving for a brief amount of time. It works perfectly, but the rfid reader stops reading tags after random amounts of time (sometimes after hour and sometimes after days) - I've tried i think everything in terms of software (except watchdog) and i simply ran out of ideas. I need it to work, so i draw all the connections in the picture below - if anyone got any ideas, please let me now.
Side note - everything is mounted and hidden outside so each even smallest hardware change is very hard to do so please, don't throw random ideas in this matter even tho every help is appreciated

EDIT: I made a photo of interior of the enclosure that holds relay, arduino and charger PCB and decided to add it here too

#include <SPI.h>
#include <MFRC522.h>

//blue
const byte UID1[] = {0xA7, 0x8C, 0x24, 0xD9};
//blacks
const byte UID2[] = {0x10, 0x84, 0xD2, 0x2A};
const byte UID3[] = {0xDC, 0x46, 0xB6, 0x91};
const byte UID4[] = {0xB0, 0xE8, 0xC4, 0x2A};
//reds
const byte UID5[] = {0x9E, 0xC8, 0xEA, 0xB3};
const byte UID6[] = {0xFE, 0xA5, 0xF7, 0xB3};
//const byte UID6[] = {0x70, 0xBA, 0x35, 0xA5};

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
int in1 = 7;
int dooropen = 8;
int state = 0;
int testerbester = 0;
void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  pinMode(in1, OUTPUT);
  pinMode(dooropen, INPUT);
  digitalWrite(in1, LOW);
  delay(2000);
}

void loop() {
  delay(200);
  state = digitalRead(dooropen);
  if (state == HIGH) {
    //Serial.println("Door Opened");
    testerbester = 1;
    digitalWrite(in1, HIGH);
  } else {
    if (testerbester == 1) {
      delay(6000);
      testerbester = 0;
      digitalWrite(in1, LOW);
    } else {
      digitalWrite(in1, LOW);
    }
    if ( ! rfid.PICC_IsNewCardPresent())
    {
      return;
    }
    if ( ! rfid.PICC_ReadCardSerial())
    {
      return;
    }
    if ((rfid.uid.uidByte[0] == UID1[0] &&
         rfid.uid.uidByte[1] == UID1[1] &&
         rfid.uid.uidByte[2] == UID1[2] &&
         rfid.uid.uidByte[3] == UID1[3]) ||
        (rfid.uid.uidByte[0] == UID2[0] &&
         rfid.uid.uidByte[1] == UID2[1] &&
         rfid.uid.uidByte[2] == UID2[2] &&
         rfid.uid.uidByte[3] == UID2[3]) ||
        (rfid.uid.uidByte[0] == UID3[0] &&
         rfid.uid.uidByte[1] == UID3[1] &&
         rfid.uid.uidByte[2] == UID3[2] &&
         rfid.uid.uidByte[3] == UID3[3]) ||
        (rfid.uid.uidByte[0] == UID4[0] &&
         rfid.uid.uidByte[1] == UID4[1] &&
         rfid.uid.uidByte[2] == UID4[2] &&
         rfid.uid.uidByte[3] == UID4[3]) ||
        (rfid.uid.uidByte[0] == UID5[0] &&
         rfid.uid.uidByte[1] == UID5[1] &&
         rfid.uid.uidByte[2] == UID5[2] &&
         rfid.uid.uidByte[3] == UID5[3]) ||
        (rfid.uid.uidByte[0] == UID6[0] &&
         rfid.uid.uidByte[1] == UID6[1] &&
         rfid.uid.uidByte[2] == UID6[2] &&
         rfid.uid.uidByte[3] == UID6[3]))
    {
      digitalWrite(in1, HIGH);
      delay(15000);
      digitalWrite(in1, LOW);
    }
    rfid.PICC_HaltA();
  }
}

"but the rfid reader stops reading tags".  Does it still respond to opening the door when that happens?

Yes, rest of "features" works 100% of time - only the reader stops responding :/.

Your sketch doesn't look very robust, what with long delays in the middle of the main loop. How long does the reader remain unresponsive? Did you make sure the door was closed when you scanned the card? What sort of enclosure did you use around the reader?

What sort of distance is there between the RFID reader and the Nano?

200ms delay at the start is to overall slow everything down, 6000ms one is a timer that starts when door is opened and then closed leaving lights turned on 6s (didn't have it before and problem was still there) and 15000ms one is for when correct tag is present so that light turns on for 15s. Reader stays unresponsive for (i think) forever until the reset. Door is closed 100%, because often when i come back and find it not working i just open the door without it and then light turns on. Enclosure for scanner is a 3D printed case. Relay, arduino and power share space in one separate enclosure

@timemage about 5-6 meters of cable (used ethernet cable for that)

Well, I'm not sure how to continue with this without turning it into a conversation or doing something what will probably trigger your "throw random ideas" clause, but suffice it to say I think that distance plays a role in the problem.

@timemage I mean it could be true, but why would it just stop working randomly like that, and how to solve/test it if thats the case (i can't have a shorter cable - this one is made as short as possible)

I refer you back to my previous comment.


text:
Upload of software working unreliably
I've got a new Keyestudio ATmega2560 (compatible with Arduino Mega 2560) board and was trying to upload a simple sketch. I noticed that both the Arduino IDE and PlatformIO were unable to do so, they detected the device but at various points during the upload stage they encountered a timeout.
After dozens of failed attempts I was already concluding that the serial interface must be broken so I created a serial loopback (grounded RESET and connected TX and RX) and opened it in the serial monitor of the Arduino IDE. I noticed that it works perfect, whatever I type gets sent back.
After trying some more and experimenting with different programmers in Arduino IDE I managed to get it to write the software once (write completed but subsequent verifying of the flash memory failed) and opening the serial monitor now it really shows the output I had in my program.
I am wondering, what can I do to isolate further where the problem could be? It seems in theory it is working as expected since I was able to upload the code once, but it is clearly not doing so all the time...
Some outputs:
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:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

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

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Wiring
         Description     : Wiring
         Programmer Model: AVRISP
         Hardware Version: 15
         Firmware Version Master : 2.10
         Vtarget         : 0.0 V
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout

And one that probably got the furthest:
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:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

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

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Wiring
         Description     : Wiring
         Programmer Model: AVRISP
         Hardware Version: 15
         Firmware Version Master : 2.10
         Vtarget         : 0.0 V
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e9801 (probably m2560)
avrdude: reading input file "C:\Users\yanic\AppData\Local\Temp\arduino_build_482951/sketch_feb19a.ino.hex"
avrdude: writing flash (2012 bytes):

Writing | #####################################avrdude: stk500v2_ReceiveMessage(): timeout
############# | 100% 10.31s

avrdude: 2012 bytes of flash written
avrdude: verifying flash memory against C:\Users\yanic\AppData\Local\Temp\arduino_build_482951/sketch_feb19a.ino.hex:
avrdude: load data flash data from input file C:\Users\yanic\AppData\Local\Temp\arduino_build_482951/sketch_feb19a.ino.hex:
avrdude: input file C:\Users\yanic\AppData\Local\Temp\arduino_build_482951/sketch_feb19a.ino.hex contains 2012 bytes
avrdude: reading on-chip flash data:

Reading | avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port

Have you tried a dedicated ISP programmer, like USBasp or USBtinyISP, to upload firmware directly to the mcu? Just to check if the mcu still alive? I think there is a chance they overcooked the mcu why reflowed it. For me, I just don't trust made in china arduino clones in general.

the USBtinyISP is actually the one that worked once. I guess it might be the board, too bad, never had problems with keyestudio before... I typcially go for the original one as well, but they fixed so many of the things I hate about the Arduino :)

Not helpful to solve your problem, but I suggest you move on to a different electronic platform, like ARM 32-bit mcu. This 8-bit ATmega family is like a relic of the past, still good for simple applications though.

What error message do you get? Enable "verbose" output in the settings to get a more details. Please edit your question to include the output you get when trying to upload.

PS programming the board via ISP will overwrite the bootloader, making it impossible to upload over serial(, without first restoring the bootloader)

I've added two sample outputs

This may sound like a dumb question, but there is a theory behind it: What happens if you upload a blank sketch, just void setup(){} void loop(){}  Does it do that reliably?

Two suggestions, first try a slower baud rate, if that does not fix it try a different USB cable.


text:
Arduino mega ethernet Udp client randomly failing
I have a keyestudio board identical to the arduino mega 2560. I use the matching keyestudio ks0156 W5100 ethernet shield. My code uses the following library for ethernet paulstoffregen/Ethernet@0.0.0-alpha+sha.9f41e8231b
I have the following code (initialization and "loop" code):
const int port_broadcast{27333};
char udp_packet_buffer[UDP_TX_PACKET_MAX_SIZE + 1];

const byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

EthernetUDP udp;

void init_ethernet() {
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Error initializing Ethernet using DHCP");

    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.");

      while (true) {
        delay(1);
      }
    }

    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }

    Ethernet.begin(mac, ip, dns);
  } else {
    Serial.print("DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

  udp.begin(port_broadcast);
}

void update_time() {
  int packet_size = udp.parsePacket();
  if (packet_size > 0) {
     const auto num_read = udp.read(udp_packet_buffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.print("Received ");
    Serial.print(num_read);
    Serial.println(" bytes: ");
    if(num_read > 0) {
      udp_packet_buffer[num_read] = '\0';
      Serial.println(udp_packet_buffer);
    }
  }
}

On my Windows device in the same network I have a service that every 2 seconds posts the current time in the format 2021-09-19 15:37:30 over UDP broadcast to my local network. This works quite well until suddenly the board starts receiving wrong values. Here is a sample output from the board:
DHCP assigned IP 192.168.1.120
Received 19 bytes:
2021-09-19 19:59:37
Received 19 bytes:
2021-09-19 19:59:39
Received 19 bytes:
2021-09-19 19:59:41
Received 19 bytes:
2021-09-19 19:59:43
Received 19 bytes:
2021-09-19 19:59:45
Received 19 bytes:
2021-09-19 19:59:47
Received 19 bytes:
2021-09-19 19:59:49
Received 19 bytes:
2021-09-19 19:59:51
Received 19 bytes:
2021-09-19 19:59:53
Received 19 bytes:
2021-09-19 19:59:55
Received 19 bytes:
2021-09-19 19:59:57
Received 19 bytes:
2021-09-19 19:59:59
Received 19 bytes:
2021-09-19 20:00:01
Received 19 bytes:
2021-09-19 20:00:03
Received 19 bytes:
2021-09-19 20:00:05
Received 19 bytes:
2021-09-19 20:00:07
Received 19 bytes:
2021-09-19 20:00:09
Received 19 bytes:
2021-09-19 20:00:11
Received 19 bytes:
2021-09-19 20:00:13
Received 19 bytes:
2021-09-19 20:00:15
Received 19 bytes:
2021-09-19 20:00:17
Received 19 bytes:
2021-09-19 20:00:19
Received 19 bytes:
2021-09-19 20:00:21
Received 19 bytes:
2021-09-19 2
Received 19 bytes:
␒0"1    0
Received 19 bytes:
2021-09-19 20:00:␒7
Received 19 bytes:
2021-09-1        ␒0
Received 3 bytes:
2
Received 24 bytes:
20:00␚3!␁B��

As you can see suddenly the output makes no sense anymore. There is no sensor attached, no input happening or anything else going on, it just randomly starts outputing wrong values. Also when it starts outputing wrong values it does not continue for long before completely stopping to receive anythin alltogether. According to Wireshark the windows service keeps posting the right data, so I can rule out that it has something to do with the service.
So my question is, why would my board suddenly stop receiving data over UDP without any apparent reason or interaction from the outside? Reseting the board will immediately continue to print more data, but until then it stopped. It got adequate power supply and the LAN cable is very short. Am I doing something wrong in my code? Does it look like an issue with the Ethernet shield?
For completeness sake this is the C# code from the service that is sending to the UDP broadcast:
        private UdpClient _time_broadcaster;
        private readonly IPEndPoint _broadcast = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 27333);

        private void timer_elapsed(object source, ElapsedEventArgs args) {
            var now = DateTime.Now;
            var year = now.Year;
            var month = now.Month;
            var day = now.Day;

            var hour = now.Hour;
            var minute = now.Minute;
            var second = now.Second;

            var result = $"{year:D4}-{month:D2}-{day:D2} {hour:D2}:{minute:D2}:{second:D2}";
            var data = Encoding.ASCII.GetBytes(result);
            _time_broadcaster.Send(data, data.Length, _broadcast);
        }

seems like a buffer is getting cumulatively overfilled ... possibly by not retrieving all data from buffer at each read .... does the program always fail at the same location?

Yea, I thought something similar too, so I also checked that and sometimes it fails after a few seconds, sometimes after a minute, sometimes even more. What did make a change is changing the windows service to send to 192.168.1.120 (the assigned IP) instead of 192.168.1.255 (broadcast), it has been running for 30 minutes now without any interruption. I need to do some more testing there.

that probably eliminates the buffer overflow idea ... possible bug in the library

does not necessarily eliminate overflow- depends on what you are listening for.  it may also be a feature related to monitoring network traffic between other devices rather than a bug.  try reverting to old settings and having network of only 2 devices.

did you try the Ethernet library from Library Manager?

I am using PlatformIO, I will check out which one is the official one from Library Manager in Arduino IDE and try to find that one in PIO.


text:
nRF52832 BLE "conn_handle" to disconnect the current connected devices
I'm working on nRF52832 Bluefruit Adafruit Module. I want the BLE connection to disconnect using a function and can call whenever required. But the issue is the disconnect function needs "conn_handle" to disconnect from the current connected Client.
Can anyone help me find where I can get the "conn_handle" of the connected client?
/**
 * Callback invoked when a connection is dropped
 * @param conn_handle
 * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
 */
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
  (void) conn_handle;
  (void) reason;

  connection_num--;

  // Mark the ID as invalid
  int id  = findConnHandle(conn_handle);

  // Non-existant connection, something went wrong, DBG !!!
  if ( id < 0 ) return;

  // Mark conn handle as invalid
  prphs[id].conn_handle = BLE_CONN_HANDLE_INVALID;

  Serial.print(prphs[id].name);
  Serial.println(" disconnected!");
}

The below complete code is for "Central Bleuart Multi"-
/*********************************************************************

 This is an example for our nRF52 based Bluefruit LE modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution
*********************************************************************/

/* This sketch demonstrates the central API() that allows you to connect
 * to multiple peripherals boards (Bluefruit nRF52 in peripheral mode, or
 * any Bluefruit nRF51 boards).
 *
 * One or more Bluefruit boards, configured as a peripheral with the
 * bleuart service running are required for this demo.
 *
 * This sketch will:
 *  - Read data from the HW serial port (normally USB serial, accessible
 *    via the Serial Monitor for example), and send any incoming data to
 *    all other peripherals connected to the central device.
 *  - Forward any incoming bleuart messages from a peripheral to all of
 *    the other connected devices.
 *
 * It is recommended to give each peripheral board a distinct name in order
 * to more easily distinguish the individual devices.
 *
 * Connection Handle Explanation
 * -----------------------------
 * The total number of connections is BLE_MAX_CONNECTION (20)
 *
 * The 'connection handle' is an integer number assigned by the SoftDevice
 * (Nordic's proprietary BLE stack). Each connection will receive it's own
 * numeric 'handle' starting from 0 to BLE_MAX_CONNECTION-1, depending on the order
 * of connection(s).
 *
 * - E.g If our Central board connects to a mobile phone first (running as a peripheral),
 * then afterwards connects to another Bluefruit board running in peripheral mode, then
 * the connection handle of mobile phone is 0, and the handle for the Bluefruit
 * board is 1, and so on.
 */

/* LED PATTERNS
 * ------------
 * LED_RED   - Blinks pattern changes based on the number of connections.
 * LED_BLUE  - Blinks constantly when scanning
 */

#include <bluefruit.h>

// Struct containing peripheral info
typedef struct
{
  char name[16+1];

  uint16_t conn_handle;

  // Each prph need its own bleuart client service
  BLEClientUart bleuart;
} prph_info_t;

/* Peripheral info array (one per peripheral device)
 *
 * There are 'BLE_MAX_CONNECTION' central connections, but the
 * the connection handle can be numerically larger (for example if
 * the peripheral role is also used, such as connecting to a mobile
 * device). As such, we need to convert connection handles <-> the array
 * index where appropriate to prevent out of array accesses.
 *
 * Note: One can simply declares the array with BLE_MAX_CONNECTION and use connection
 * handle as index directly with the expense of SRAM.
 */
prph_info_t prphs[BLE_MAX_CONNECTION];

// Software Timer for blinking the RED LED
SoftwareTimer blinkTimer;
uint8_t connection_num = 0; // for blink pattern

void setup()
{
  Serial.begin(115200);
  while ( !Serial ) delay(10);   // for nrf52840 with native usb

  // Initialize blinkTimer for 100 ms and start it
  blinkTimer.begin(100, blink_timer_callback);
  blinkTimer.start();

  Serial.println("Bluefruit52 Central Multi BLEUART Example");
  Serial.println("-----------------------------------------\n");

  // Initialize Bluefruit with max concurrent connections as Peripheral = 0, Central = 4
  // SRAM usage required by SoftDevice will increase with number of connections
  Bluefruit.begin(0, 4);

  // Set Name
  Bluefruit.setName("Bluefruit52 Central");

  // Init peripheral pool
  for (uint8_t idx=0; idx<BLE_MAX_CONNECTION; idx++)
  {
    // Invalid all connection handle
    prphs[idx].conn_handle = BLE_CONN_HANDLE_INVALID;

    // All of BLE Central Uart Serivce
    prphs[idx].bleuart.begin();
    prphs[idx].bleuart.setRxCallback(bleuart_rx_callback);
  }

  // Callbacks for Central
  Bluefruit.Central.setConnectCallback(connect_callback);
  Bluefruit.Central.setDisconnectCallback(disconnect_callback);

  /* Start Central Scanning
   * - Enable auto scan if disconnected
   * - Interval = 100 ms, window = 80 ms
   * - Filter only accept bleuart service in advertising
   * - Don't use active scan (used to retrieve the optional scan response adv packet)
   * - Start(0) = will scan forever since no timeout is given
   */
  Bluefruit.Scanner.setRxCallback(scan_callback);
  Bluefruit.Scanner.restartOnDisconnect(true);
  Bluefruit.Scanner.setInterval(160, 80);       // in units of 0.625 ms
  Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE);
  Bluefruit.Scanner.useActiveScan(false);       // Don't request scan response data
  Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds
}

/**
 * Callback invoked when scanner picks up an advertising packet
 * @param report Structural advertising data
 */
void scan_callback(ble_gap_evt_adv_report_t* report)
{
  // Since we configure the scanner with filterUuid()
  // Scan callback only invoked for device with bleuart service advertised
  // Connect to the device with bleuart service in advertising packet
  Bluefruit.Central.connect(report);
}

/**
 * Callback invoked when an connection is established
 * @param conn_handle
 */
void connect_callback(uint16_t conn_handle)
{
  // Find an available ID to use
  int id  = findConnHandle(BLE_CONN_HANDLE_INVALID);

  // Eeek: Exceeded the number of connections !!!
  if ( id < 0 ) return;

  prph_info_t* peer = &prphs[id];
  peer->conn_handle = conn_handle;

  Bluefruit.Connection(conn_handle)->getPeerName(peer->name, sizeof(peer->name)-1);

  Serial.print("Connected to ");
  Serial.println(peer->name);

  Serial.print("Discovering BLE UART service ... ");

  if ( peer->bleuart.discover(conn_handle) )
  {
    Serial.println("Found it");
    Serial.println("Enabling TXD characteristic's CCCD notify bit");
    peer->bleuart.enableTXD();

    Serial.println("Continue scanning for more peripherals");
    Bluefruit.Scanner.start(0);

    Serial.println("Enter some text in the Serial Monitor to send it to all connected peripherals:");
  } else
  {
    Serial.println("Found ... NOTHING!");

    // disconnect since we couldn't find bleuart service
    Bluefruit.disconnect(conn_handle);
  }

  connection_num++;
}

/**
 * Callback invoked when a connection is dropped
 * @param conn_handle
 * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
 */
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
  (void) conn_handle;
  (void) reason;

  connection_num--;

  // Mark the ID as invalid
  int id  = findConnHandle(conn_handle);

  // Non-existant connection, something went wrong, DBG !!!
  if ( id < 0 ) return;

  // Mark conn handle as invalid
  prphs[id].conn_handle = BLE_CONN_HANDLE_INVALID;

  Serial.print(prphs[id].name);
  Serial.println(" disconnected!");
}

/**
 * Callback invoked when BLE UART data is received
 * @param uart_svc Reference object to the service where the data
 * arrived.
 */
void bleuart_rx_callback(BLEClientUart& uart_svc)
{
  // uart_svc is prphs[conn_handle].bleuart
  uint16_t conn_handle = uart_svc.connHandle();

  int id = findConnHandle(conn_handle);
  prph_info_t* peer = &prphs[id];

  // Print sender's name
  Serial.printf("[From %s]: ", peer->name);

  // Read then forward to all peripherals
  while ( uart_svc.available() )
  {
    // default MTU with an extra byte for string terminator
    char buf[20+1] = { 0 };

    if ( uart_svc.read(buf,sizeof(buf)-1) )
    {
      Serial.println(buf);
      sendAll(buf);
    }
  }
}

/**
 * Helper function to send a string to all connected peripherals
 */
void sendAll(const char* str)
{
  Serial.print("[Send to All]: ");
  Serial.println(str);

  for(uint8_t id=0; id < BLE_MAX_CONNECTION; id++)
  {
    prph_info_t* peer = &prphs[id];

    if ( peer->bleuart.discovered() )
    {
      peer->bleuart.print(str);
    }
  }
}

void loop()
{
  // First check if we are connected to any peripherals
  if ( Bluefruit.Central.connected() )
  {
    // default MTU with an extra byte for string terminator
    char buf[20+1] = { 0 };

    // Read from HW Serial (normally USB Serial) and send to all peripherals
    if ( Serial.readBytes(buf, sizeof(buf)-1) )
    {
      sendAll(buf);
    }
  }
}

/**
 * Find the connection handle in the peripheral array
 * @param conn_handle Connection handle
 * @return array index if found, otherwise -1
 */
int findConnHandle(uint16_t conn_handle)
{
  for(int id=0; id<BLE_MAX_CONNECTION; id++)
  {
    if (conn_handle == prphs[id].conn_handle)
    {
      return id;
    }
  }

  return -1;
}

/**
 * Software Timer callback is invoked via a built-in FreeRTOS thread with
 * minimal stack size. Therefore it should be as simple as possible. If
 * a periodically heavy task is needed, please use Scheduler.startLoop() to
 * create a dedicated task for it.
 *
 * More information http://www.freertos.org/RTOS-software-timer.html
 */
void blink_timer_callback(TimerHandle_t xTimerID)
{
  (void) xTimerID;

  // Period of sequence is 10 times (1 second).
  // RED LED will toggle first 2*n times (on/off) and remain off for the rest of period
  // Where n = number of connection
  static uint8_t count = 0;

  if ( count < 2*connection_num ) digitalToggle(LED_RED);
  if ( count % 2 && digitalRead(LED_RED)) digitalWrite(LED_RED, LOW); // issue #98

  count++;
  if (count >= 10) count = 0;
}

GitHub Source code
I want to invoke this disconnect function, but I don't know where to get conn_handle. If anyone has any idea please help me.
I have already tried going into libraries; the best it shows is just the definition of the callback function:
1: Bluefruit.Central.setDisconnectCallback(disconnect_callback);

2: void BLECentral::setDisconnectCallback( ble_disconnect_callback_t fp )
   {
     _disconnect_cb = fp;
   }

3: class BLECentral
   {
     ...
     private:
       ble_disconnect_callback_t _disconnect_cb;
   }

4: typedef void (*ble_disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason);

This is all I got regarding this disconnect function in different libraries following the definition but nothing related to conn_handle.

Idk if its a right or not but it works.
When there's is a new connection established, "connect" gets revoked, with "conn_handle" as its argument. If someone knows please tell how is this function revoke itself.
But what I did is make a global variable uint16_t conn_handle
uint16_t g_conn_handle;
void connect_callback(uint16_t conn_handle)
    {
      g_conn_handle=conn_handle;
      // Find an available ID to use
      int id  = findConnHandle(BLE_CONN_HANDLE_INVALID);

      // Eeek: Exc
      ...

Now I can call the Disconnect function with this g_conn_handle global variable.


text:
Read Digital Input from Arduino Pin defined as OUTPUT
I'm working on a Home Automation Project.
I can turn on-off ESP32 pin from Alexa and Google Assistant Successfully now.
What I need help is with a way to read if the AC supply is ON/OFF on the Arduino pin.
Or if possible to save pins I would want to read it on the same pin which id defined as Digital output to control the relay.
Below attached image of what I have in mind.

Normal switch turns On/off supply to load without any requirement of WiFi.
Load is also connected to Relay NO, which is controlled by Arduino Pin D13.

What I want is instead of just reading the status of the D13 pin, I want to read the status of the Mechanical Switch which directly provide to Load.
So I'll actual status of the Load whether it's turned on by Switch or Relay with interrupting directly connected switch from load to supply.

Edited: As others suggested it is not possible to use the Same Pin to control the relay and read AC load status. So is there a way to read the AC supply through the GPIO pin of ESP32 maintaining galvanic isolation, (opposite working of Relay)?

if your manual switch has a second contact, you can read that

Every time I want to answer I stop myself because it's dangerous to connect to the high voltage 110 or 220 VAC side.  I like @edgar's answer.  If your load is resistive (old incandescent lamps) you might look at old X10 schematics to see what they did.  If new (LED lamps) then do what edgar said.

If you want to know the state of the load, I suggest to put the
mechanical switch on the low-voltage side of the relay:

simulate this circuit – Schematic created using CircuitLab
The voltage divider R1/R2 is meant to lower the
voltage at the transistor's collector (up to one diode threshold above
Vcc) to a value suitable for the Arduino digital input.
Note that you still need two separate inputs for controlling and for
sensing the state.

That was my concern, I don't want to use the switch to turn on the load indirectly, as changing the switch in the future will be easier than the relays also any fault in the circuit won't affect the manual system. But if I consider your case why don't I use the Switch in the same place as the Control Pin?

@JustdoinGodswork: If you connect the switch and the control pin together, you will likely short the pin, and possibly destroy its output stage.

What you want to do is not possible, you'll need an extra pin. The reason is that the relay requires a lot of current (works like a very strong pulldown resistor). So, whatever (high impedance) sense signal you apply to the relay, it will just be "consumed" by the relay.
When reading the state of the switch, i.e. the voltage across it, galvanic isolation is absolutely mandatory (mains voltage can be deadly). This can be achieved with an opto coupler and some lines of code or additional hardware - as it's AC voltage, you can't simply read a steady voltage, so you'd either have to sample the AC signal or incorporate some kind of circuitry (software is simpler and cheaper).
Another issue with your circuit is that you must not drive the relay directly with the GPIO. The relay sinks way to much current, it'll fry the GPIO. Use a transistor to switch it.

My bad for the cheap circuit, I couldn't find an online tool to make it. I'll use the proper Opto coupler driver circuit for the relay in actual hardware. Then I'll try to find an increased GPIO pin controller as my priority is not to interfere with the manual system. Is there any device that is opposite to the relay?
Eg. If AC passes through the coil I'd be able to read it at a GPIO pin?