ENع
←Watchdog timers
Lesson 45 · Low power and reliability

Watchdog timers

12 min9 steps5 questionsAdvanced
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 45 · Interactive
01 / 09

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);
}
Loading figure…
or ← →
Read the lesson step by step
  1. 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);
    }
  2. 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 reset
  3. Arm 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 reset
  4. The 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 s
  5. Feed 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 ...
  6. 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 ticks
  7. The 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 again
  8. Why 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 over
  9. Feed 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.

Quiz Unlocks after the last step.