D2 · A0MCUATmega328P01WDRFWATCHDOG0limit 2 s0.0 s128 kHz1void setup() {2 wdt_enable(WDTO_2S);3}4void loop() {5 int v = readSensor();6 wdt_reset();7 delay(500);8}2 sv?wdrRST
Back: the sensor node's board (sensor, microcontroller, WDRF flag, watchdog, 128 kHz oscillator)Front: the firmware card, setup() and loop()Tokens: oscillator ticks, wdt_enable, wdt_reset (wdr), sensor values and the reset pulseA sensor node on an Arduino Uno R3: a sensor, the ATmega328P, its watchdog timer with its own 128 kHz oscillator, and the firmware on a card in front. setup() arms the watchdog with a limit of 262,144 ticks (about 2 s); each pass of loop() feeds it with wdt_reset() after about 0.5 s. When the sensor dies, loop() stops feeding it, the count reaches the limit and the watchdog resets the chip; MCUSR's WDRF bit records why.

Why a watchdog

  1. 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.

Arm it and feed it

When it bites

Using it well

What happens

;; step 1/9 · hang
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);
}

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.