The Arduino Uno board is powered by the ATmega328P microcontroller, which includes a Watchdog Timer. This feature helps the system recover from situations where it hangs or freezes due to code errors or potential hardware issues.
How the Watchdog Timer Works
The Watchdog Timer must be configured based on the application’s requirements and operates using an internal 128kHz clock source. Once enabled, it begins counting from 0 to a preset value selected by the user. If the timer reaches this value without being reset, it triggers a system reset of the microcontroller.
The ATmega328P Watchdog Timer can be configured with 10 different timeout settings (the time after which it overflows and causes a reset). These time intervals are 16ms, 32ms, 64ms, 125ms, 250ms, 500ms, 1s, 2s, 4s, and 8s.
Example
Let’s go through a basic example of configuring the Watchdog Timer on the Arduino Uno with a simple LED blinking setup.
In this example, the LED will blink for a specific duration before entering an infinite while(1)
loop. This loop simulates a system freeze. Since the Watchdog Timer is not reset within the loop, it will eventually cause the microcontroller to reset, which restarts the blinking sequence. This cycle will repeat indefinitely.
The on-board LED connected to pin 13 of the Arduino Uno is used here. No additional components are required beyond the Arduino Uno board.
Important Note
The Watchdog Timer is disabled at the start of the code, and a 3-second delay is included before enabling it. This delay is essential to allow the Arduino bootloader to check for new code uploads and burn the code to flash memory.
This precaution is crucial, as faulty code or configuration might cause the microcontroller to reset repeatedly in very short intervals, potentially damaging the Arduino and preventing further uploads. While the new Optiboot loader on recent Arduino models may avoid this issue, older versions are more susceptible.
If the Arduino gets “bricked” in this way, you’ll need to reburn the bootloader using another Arduino as an ISP to restore it.
Sketch
#include<avr/wdt.h> /* Header for watchdog timers in AVR */
void setup() {
Serial.begin(9600); /* Define baud rate for serial communication */
Serial.println("Watchdog Demo Starting");
pinMode(13, OUTPUT);
wdt_disable(); /* Disable the watchdog and wait for more than 2 seconds */
delay(3000); /* Done so that the Arduino doesn't keep resetting infinitely in case of wrong configuration */
wdt_enable(WDTO_2S); /* Enable the watchdog with a timeout of 2 seconds */
}
void loop() {
for(int i = 0; i<20; i++) /* Blink LED for some time */
{
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
wdt_reset(); /* Reset the watchdog */
}
while(1); /* Infinite loop. Will cause watchdog timeout and system reset. */
}