Arduino — WDT

A watchdog timer (WDT) is a hardware timer that automatically generates a system reset if the main program neglects to periodically service it. It is often used to automatically reset an embedded device that hangs because of a software or hardware fault. The Arduino Uno board has an ATmega328P chip as its controlling unit, which has a Watchdog Timer that helps the system recover from scenarios when the system hangs or freezes due to errors in the code or due to conditions that may arise due to hardware issues.

How does the Watchdog timer work?

The watchdog timer uses an internal 128kHz clock source and needs to be configured according to the need of the application. When enabled, it starts counting from 0 to a value selected by the user. If the watchdog timer is not reset by the time it reaches the user-selected value, the timer resets the microcontroller.

The main program usually has a loop that it constantly goes through performing various functions. The watchdog timer is loaded with an initial value greater than the worst-case time delay through the main program loop, so each time it goes through the main loop the code resets the watchdog timer. If a fault occurs and the main program does not get back to reset the timer before it counts down to zero, an interrupt is generated to reset the processor. This way, the watchdog timer can detect a fault on an unattended Arduino program and attempt corrective action with a reset. After the reset, a register can also be read to determine if the watchdog timer generated the reset or if it was a normal reset. This register on the Arduino is called the Watchdog Reset Flag Register (WDRF).

Image for post

The ATmega328P watchdog timer can be configured for 10 different time settings (the time after which the watchdog timer overflows, thus causing a reset). The various times are: 16ms, 32ms, 64ms, 0.125s, 0.25s, 0.5s, 1s, 2s, 4s and 8s.

Image for post

Now that we have a basic idea of how the timer works, to learn how to configure it. We’ll use a simple example of the on-board LED blinking on the Arduino UNO.

Image for post

Once you run the aforementioned program, the LED on board will blink for a certain time before entering the while loop. The while loop here substitutes for a system in the hanged state. Since the watchdog timer is not reset in the while loop, the timer causes a system reset and the LED starts blinking again before the system hangs and restarts again. This keeps continuing in a loop.

Note: The watchdog timer is disabled at the start of the code and a delay of 3 seconds is used before enabling the timer. The delay is important in order to let the bootloader in Arduino to check if a new code is being uploaded and give it time to burn the code into the flash.

In this blog, we learned about the Watchdog timer in the Arduino UNO, how it works, and saw a simple sketch to enable it.