Watchdog timers
About this lesson
A device on a battery in a field has nobody to press reset when its firmware hangs. A watchdog timer does it for you: a counter on the chip, with its own 128 kHz oscillator, that resets the microcontroller unless the firmware restarts the count in time. Follow a sensor node on an Arduino Uno R3 as setup() arms the ATmega328P's watchdog with a limit of about 2 seconds, loop() feeds it every 0.5 seconds, and then a dead sensor makes the firmware hang until the watchdog bites. The same timer has an interrupt mode that can wake the chip from sleep (see “Sleep modes and wake-up sources”); here it guards against faults. “Brown-out, resets and fault handling” comes next.
Code that gets stuck
Our sensor node is an Arduino Uno R3, far from anyone. Each pass, readSensor() waits until the sensor says its value is ready. If the sensor dies, that wait never ends, and nobody is there to press reset.
hang code that waits for something that never comes
sensor raises pin D2 when a new value is ready
readSensor() loops until it sees that pin go HIGH
a dead sensor never raises it: the loop never ends
// Arduino Uno R3 (ATmega328P): a sensor with a "ready" pin on D2 and its value on A0
#include <avr/wdt.h>
const int READY = 2;
int readSensor() {
while (digitalRead(READY) == LOW) { } // waits forever if the sensor dies
return analogRead(A0);
}
void setup() {
wdt_enable(WDTO_2S);
}
void loop() {
int v = readSensor();
wdt_reset();
delay(500);
}Read the lesson step by step
Code that gets stuck
Our sensor node is an Arduino Uno R3, far from anyone. Each pass, readSensor() waits until the sensor says its value is ready. If the sensor dies, that wait never ends, and nobody is there to press reset.
hang code that waits for something that never comes sensor raises pin D2 when a new value is ready readSensor() loops until it sees that pin go HIGH a dead sensor never raises it: the loop never ends // Arduino Uno R3 (ATmega328P): a sensor with a "ready" pin on D2 and its value on A0 #include <avr/wdt.h> const int READY = 2; int readSensor() { while (digitalRead(READY) == LOW) { } // waits forever if the sensor dies return analogRead(A0); } void setup() { wdt_enable(WDTO_2S); } void loop() { int v = readSensor(); wdt_reset(); delay(500); }A timer that must be fed
The fix is a watchdog timer: a counter inside the chip, driven by its own 128 kHz oscillator. It counts up by itself. If the count ever reaches its limit, the watchdog resets the whole chip.
watchdog a counter on the chip, clocked by its own 128 kHz oscillator (not the 16 MHz system clock) feed it restart the count before it reaches the limit miss it the watchdog resets the chip ATmega328P limits: 16 ms up to 8 s modes: interrupt, system reset, or interrupt then resetArm it in setup()
In setup(), wdt_enable(WDTO_2S) switches the watchdog on with a limit of 262,144 oscillator ticks: about 2 seconds. From now on it counts all the time, even while delay() waits.
line 2 wdt_enable(WDTO_2S); WDTO_2S = 7 in <avr/wdt.h> limit 256K = 262,144 ticks of 128,000 Hz = 2.048 s; the datasheet says 2.0 s typical at 5 V mode system resetThe count climbs
While loop() works, the oscillator adds 128,000 to the count every second. readSensor() gets a value and delay(500) waits. After one pass the count stands at about 0.5 seconds of its 2.
oscillator 128,000 ticks per second into the count line 5 int v = readSensor(); the sensor is fine: quick line 7 delay(500); half a second count 64,000 ticks = 0.5 s of 2.048 sFeed it: wdt_reset()
wdt_reset() runs the WDR instruction, which sets the count back to 0. Each pass takes about 0.5 seconds, well under 2, so the count never gets near the limit. Programmers call this feeding or kicking the dog.
line 6 wdt_reset(); the WDR instruction count back to 0 pass about 0.5 s limit about 2 s kicks at 0.5 s, 1.0 s, 1.5 s after arming ...The sensor stops answering
Now the sensor fails. readSensor() waits for a ready signal that never comes, so line 6 never runs. Nobody feeds the watchdog, and the count climbs past 0.5, 1 and 1.5 seconds.
t = 1.5 s last wdt_reset(), count = 0 line 5 stuck in readSensor(): pin D2 stays LOW line 6 never reached count 0.5 s = 64,000 ticks count 1.0 s = 128,000 ticks count 1.5 s = 192,000 ticksThe watchdog bites
At 262,144 ticks, about 2 seconds after the last feed, the watchdog resets the chip. Its I/O registers go back to their start values and the program starts again: setup() runs, then loop(). No human was needed.
count 262,144 ticks = limit (t = 3.548 s) reset a one-clock reset pulse to the CPU I/O registers to their initial values start again from the reset vector line 1 setup() runs again, the watchdog is armed againWhy did it restart?
The reset leaves a note: bit WDRF in register MCUSR becomes 1, so start-up code can tell a watchdog reset from a power-on. Clear it early: while WDRF is 1, the watchdog stays switched on.
MCUSR bit 3 WDRF = 1 watchdog reset bit 2 BORF, bit 1 EXTRF, bit 0 PORF: the other causes read save MCUSR, then write MCUSR = 0 early why WDE is forced on while WDRF is 1: forget it and the chip resets over and overFeed it in one place
Feed the watchdog only after the real work is done, in loop(). Never feed it from a timer interrupt: interrupts keep firing while loop() is stuck, so the hang would stay hidden. Choose a limit longer than the slowest normal pass.
feed once per pass, after the work succeeded never from a timer interrupt (it runs even when loop() hangs) limit longer than the slowest pass: 0.5 s < 2 s ESP32 (ESP-IDF): the task watchdog watches each idle task; esp_task_wdt_add() subscribes a task, which then must call esp_task_wdt_reset(). By default a timeout only prints a warning; CONFIG_ESP_TASK_WDT_PANIC makes it reset.
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What does a watchdog timer do if the firmware does not restart its count in time?
In system reset mode the watchdog resets the chip when its count reaches the limit, so the firmware starts again from the top.
02The ATmega328P watchdog counts a 128 kHz oscillator. How many ticks is the WDTO_2S limit?
The datasheet's table gives 256K = 262,144 oscillator cycles for a typical 2.0 s time-out. At exactly 128,000 Hz that is 2.048 s.
03Each pass of loop() takes about 0.5 s and calls wdt_reset() once. The limit is about 2 s. When does the watchdog reset the chip?
wdt_reset() sets the count back to 0 on every pass, so it never gets near the limit. Only when the code hangs and stops feeding it does the count reach the limit.
04Why is feeding the watchdog from a timer interrupt a bad idea?
A timer interrupt runs on its own schedule. If it feeds the watchdog, a loop() stuck in readSensor() still looks healthy and the watchdog never bites.
05After a watchdog reset, which bit tells the start-up code what happened?
MCUSR's WDRF bit is set by a watchdog system reset. Read it and clear it early: while WDRF is 1 the watchdog stays enabled. On an Uno the Optiboot bootloader clears MCUSR first.
Glossary
- Watchdog timer
- A counter on the chip that resets the microcontroller if the firmware does not restart the count before it reaches a limit.
- Feed (kick) the watchdog
- Restart the watchdog's count. On AVR chips wdt_reset() does it with the WDR instruction.
- Time-out (limit)
- How long the watchdog waits without being fed before it acts; 16 ms to 8 s on the ATmega328P.
- Hang
- Firmware that stops making progress, for example waiting forever for a signal that never comes.
- System reset
- A restart of the chip: its I/O registers return to their start values and the program runs again from the beginning.
- MCUSR and WDRF
- The ATmega328P's reset status register. Its WDRF bit is 1 after a watchdog reset.
- Bootloader
- A small program that runs first after a reset; on the Uno it is Optiboot, which loads new sketches over USB.
Notes and sources
- The card shows setup() and loop(). The whole sketch also includes <avr/wdt.h> and defines readSensor(), which waits in a while loop for the sensor's ready pin on D2 and then returns analogRead(A0).
- The 128 kHz oscillator is not exact: its frequency changes with voltage and temperature, so 262,144 ticks are 2.048 s only at exactly 128,000 Hz. The datasheet gives 2.0 s as typical at 5 V. Leave a wide margin.
- On an Uno the Optiboot bootloader runs first after every reset. Its version 4.4 reads MCUSR, sets it to 0 and turns the watchdog off before your sketch starts, so the sketch sees MCUSR = 0. To read WDRF yourself, program the chip without the bootloader or use a newer Optiboot that passes the flags on.
- A watchdog gets the chip running again; it does not fix the fault. If the sensor is still dead, the node hangs and resets every 2 seconds. Add timeouts as well, such as Wire.setWireTimeout() for I2C, and count resets so the device can report them.
- Microchip ATmega48A/PA/88A/PA/168A/PA/328/P datasheet (DS40002061B), §11 System Control and Reset: Watchdog Timer, MCUSR, WDTCSR
- avr-libc user manual: <avr/wdt.h> Watchdog timer handling
- Arduino AVR core: Optiboot bootloader source (optiboot.c)
- Arduino AVR core: boards.txt (the Uno's bootloader file)
- Arduino language reference: delay() (source)
- Arduino language reference: Wire.setWireTimeout() (source)
- Espressif ESP-IDF programming guide: Watchdogs (ESP32)
Quiz Unlocks after the last step.