I’m posting this for general info re use of watchdog timers in Arduino framework on AVR Mega2560, where I’ve had a bug in my code which has been very elusive, as debugging with serial prints showed there was no problem.
The code uses
#include <avr/wdt.h>
and in Setup() I enabled the watchdog at 4 seconds like this
wdt_enable(WDTO_4S);
and at various points in the code, it was reset like this
wdt_reset();
all standard stuff.
So my problem was to do with a digital i/o pin used to control a MOSFET gate.
The pin is defined:
#define power_pin 9
and the pinMode set:
pinMode(power_pin, OUTPUT);
When I measured the pin voltage with a dvm (gnd to pin) the voltage was zero. Even though the code set it to HIGH
digitalWrite(power_pin, HIGH);
I appreciate this is all basic stuff, and it was very frustrating trying to debug with serial prints, which showed the pin state was HIGH, when my DVM showed it was LOW.
I eventualy found the problem which was that wdt_reset(); was called before wdt_enable(WDTO_4S);
I ran this past copilot AI and the result was that this wouldn’t cause a problem. However after correcting the code so that the timer was enabled before it was reset, the problem went away and my power_pin state in code, reflected its voltage state, and could be switched with digitalWrite as expected.
I ran this conclusion past copilot AI again and got this back:
‘It’s possible that the Arduino’s internal pin control registers (PORTx
and DDRx
) were affected during this undefined watchdog state, briefly overriding the digitalWrite(power_pin, HIGH)
instruction. Even though the code and serial output indicated HIGH
, the actual hardware state could have been inconsistent.’
Whether the above is correct or not, I can’t comment, but something odd does happen if the timer is reset before it’s enabled.
I thought I’d post this in the hope it might help others. It seems that resetting the WDT before enabling it can have strange consequences when trying to debug.