Why a watchdog
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.
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.
Arm it and feed it
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.
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.
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.
When it bites
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.
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.
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.
Using it well
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.
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.