My plan is to run it without bootloader so it can boot faster (without the waiting period). But when I upload the following code to it without the bootloader, after 4 seconds, it locks up until I unplug and replug it. When I use this code with the bootloader, the watchdog works fine. I tried the same code on a third party nano (with an atmega328p in it, with and without the bootloader), it works fine. So did I do anything wrong when I draw the circuit?
#include <avr/wdt.h>
#include <Wire.h>
// the setup routine runs once when you press reset:
void setup() {
wdt_disable(); //disable wdt at the first of code to prevent it always reboot
Serial.begin(9600);
delay(50); //this latency is waiting for the analog parts to ramp up.
wdt_enable(WDTO_4S); //
Serial.println(99999999);
Serial.println(99999999);
Serial.println(99999999);
Serial.println(99999999);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
// wdt_reset(); //
delay(100); // delay in between reads for stability
}
Okay. Does it mean I made wrong fuse setting?
Note I did the same thing to a third party nano, and it works just fine. I checked the datasheet of the 328p, and didn't find any specific fuse for the watchdog.
Thanks a lot b707! I will try this out later. I wonder why this didn't happen when I load this code to the nano board (with and without the bootloader).
In the case of the bootloader, this is understandable. Some arduino bootloaders already contains these lines in its code, so it does not have such problems.
Nah; the beginning of setup() will be fine, and setting MCUSR is not needed (I mean, it's a good idea, because those bits are sticky across resets, but...)
16ms (the minimum watchdog time) is a LONG time compared to the pre-setup initialization code.
Sorry. Yes you did. The line spacing must have confused me. If you are still experimenting you could also try, as the first statement, setting MCUSR to zero or wdt_enable(WDTO_4S) just to give it more time to carry out the later disable.
I did disable the watchdog right after it entered setup
After delay(50) is NOT "right after entering setup." Is is half-a-seconds later.
It doesn't prevent the WDT from resetting the microcontroller sometime during that 50ms. As others have said, the INTERVAL for the WDT resets to 16ms when the chip is reset (I consider that relatively undesirable behavior. But the alternative where some registers are not reset completely is also bad.)
(It might be worth pointing out that the newer AVRs, like the ATmega4809 used on Nano Every, have a fuse that sets the WDT period at reset, instead of just resetting it to zero. It can do this because they've expanded from 3 fuses to 11 fuses!)