The watchdog timer
A watchdog is a down-counter on its own clock that resets the microcontroller unless the firmware refreshes it in time. Kick it only when the real work is done, and a hung program recovers by itself instead of waiting for someone to press reset.
A timer that resets you
Firmware hangs: a peripheral never answers, a loop never exits, a pointer goes astray. In the field nobody is there to press reset, so most microcontrollers have a watchdog. An independent watchdog is a down-counter that starts from a reload value. Each refresh, or kick, reloads it. If it ever reaches zero, it resets the whole chip.
It runs on its own low-speed internal oscillator, not on the CPU clock, so it keeps counting even if the main clock or the PLL fails (see The clock system). On many parts, software can't stop it once it has started; only a reset does. That's deliberate, because a runaway program must not be able to switch it off. STM32's independent watchdog (IWDG) is one example; most MCU families have an equivalent.
Start it, then kick it
Setup comes down to three choices: a clock divider, a reload value, and the moment you start it. From then on, the firmware has to refresh the watchdog before it runs out. Starting and refreshing usually take a special write, such as a key value or a fixed sequence, so a stray pointer write can't kick or reconfigure it by accident.
- Timeout: roughly the watchdog clock period × the divider × the reload count.
- Margin: the internal oscillator is imprecise and varies from chip to chip, so pick a timeout well above your longest loop.
- Details: for the exact registers, key values and timeout ranges, check your chip's reference manual.
Kick from the right place
Refresh in the main loop, and only after the real work has finished, as the diagram shows. Never kick from a timer interrupt: interrupts keep firing while the main loop is stuck, so the watchdog would never see the hang.
Most MCUs record the cause of the last reset. Check it at boot, log a watchdog reset so you learn that it happened, then clear it. On STM32 these are the reset flags mentioned in Reset and boot sequence.
One trap when debugging: on many parts the watchdog keeps counting while a debugger halts the core, so it resets the chip in the middle of your session. Many chips have a debug setting that freezes it; check your chip's reference manual.