Watchdog timer
Independent and windowed watchdogs, and feeding them correctly.
The last line of defence
A watchdog is a hardware timer that resets the microcontroller unless the software restarts ("feeds", "kicks", "refreshes") it regularly. If the firmware hangs, loops forever, deadlocks or runs off into garbage, the feeding stops and the chip resets into a known state. For a device nobody can reach to press a reset button (a sensor on a pole, a pacemaker, a satellite) it is essential.
A watchdog does not fix bugs. It turns a permanent hang into a brief outage, which is much better, and its reset cause tells you a hang happened.
Two kinds
| Independent watchdog (IWDG) | Window watchdog (WWDG) | |
|---|---|---|
| Clock | Its own low-speed RC oscillator (LSI) | The system clock (APB) |
| Survives a clock failure | Yes | No |
| Can be stopped by software | No, once started | Depends on the part |
| Timeout range | Milliseconds to tens of seconds | Short: around milliseconds to ~100 ms |
| Fails if fed | Too late | Too late or too early |
| Purpose | Catch hangs | Catch hangs and code running too fast or skipping steps |
STM32 names are used here; other vendors have equivalents (nRF WDT, ESP32 RWDT and TWDT, the Microchip WDT with window mode).
Independent watchdog timing
Timeout = reload × prescaler / f_LSI. The LSI is inaccurate (often ±5 to ±50% across temperature and parts), so design for the worst case: if it runs fast, the watchdog fires earlier than you calculated.
#include <stdio.h>
int main(void) {
double lsi_nominal = 32000.0; /* Hz */
int prescaler = 64, reload = 999;
double nominal_ms = (reload + 1) * prescaler / lsi_nominal * 1000.0;
printf("nominal timeout: %.0f ms\n", nominal_ms);
/* The LSI may be anywhere from about 17 to 47 kHz on some parts. */
printf("if LSI runs at 47 kHz: %.0f ms\n", (reload + 1) * prescaler / 47000.0 * 1000.0);
printf("if LSI runs at 17 kHz: %.0f ms\n", (reload + 1) * prescaler / 17000.0 * 1000.0);
return 0;
}
With a feed every 500 ms, a nominal 2 s timeout is still safe at the fast extreme (1.36 s).
Windowed mode
A window watchdog rejects a refresh that comes too early, before the window opens, as well as one that comes too late. That catches failure modes a plain watchdog misses: a tight loop that keeps feeding, or a sequence that skips work and arrives at the feed point early. Configure the window around the expected period of the main loop or the control cycle.
Feeding strategies
Where and when the feed happens determines what the watchdog actually protects against.
Wrong: feed in a timer interrupt. The interrupt keeps running while the main loop is hung, so the watchdog never fires. This defeats it completely.
Better: feed once per main-loop pass, at a single point, after all work is done.
With an RTOS: feed only when every task has checked in. Each monitored task sets its bit in a shared mask each cycle; a supervisor (often a low-priority task) feeds the watchdog only when all bits are set, then clears them. One stuck task means no feed.
#include <stdio.h>
#include <stdint.h>
#define TASK_SENSOR (1u << 0)
#define TASK_COMMS (1u << 1)
#define TASK_CONTROL (1u << 2)
#define ALL_TASKS (TASK_SENSOR | TASK_COMMS | TASK_CONTROL)
static volatile uint32_t checkins;
static int feeds;
static void task_checkin(uint32_t bit) { checkins |= bit; } /* atomic OR in a real system */
static void watchdog_supervisor(void) {
if ((checkins & ALL_TASKS) == ALL_TASKS) {
feeds++; /* IWDG->KR = 0xAAAA on real hardware */
checkins = 0;
printf("all tasks alive: watchdog fed (%d)\n", feeds);
} else {
printf("missing 0x%X: NOT feeding, reset will follow\n", ALL_TASKS & ~checkins);
}
}
int main(void) {
task_checkin(TASK_SENSOR); task_checkin(TASK_COMMS); task_checkin(TASK_CONTROL);
watchdog_supervisor();
task_checkin(TASK_SENSOR); task_checkin(TASK_CONTROL); /* comms task is stuck */
watchdog_supervisor();
return 0;
}
Practical details
- Start it early, ideally from option bytes ("hardware watchdog") so it runs even if the firmware crashes before
main. - Debugging: halting at a breakpoint stops the CPU but not the IWDG, so the chip resets under the debugger. Set the debug-freeze bit (
DBGMCUon STM32) in debug builds. - Long operations: a flash erase can take longer than the timeout. Feed before and after, choose a timeout longer than the worst case, or split the operation.
- Low-power modes: some watchdogs keep running in stop mode, so the device must wake periodically to feed. Check this when designing sleep schedules.
- After a watchdog reset: read and log the reset cause, plus any crash record saved in no-init RAM. Count consecutive watchdog resets; after several, boot into a safe mode or roll back a recent firmware update instead of crashing in a loop.
Pitfall: Feeding the watchdog inside a loop that waits for hardware (
while (!(SPI->SR & TXE)) { feed(); }) means a dead peripheral hangs the product forever with a perfectly happy watchdog. Put timeouts on waits; feed only from the top-level loop or supervisor.
Interview question: How do you use a watchdog in an RTOS-based system with several tasks?
Answer: Do not let any single task feed it unconditionally. Each critical task reports liveness each cycle, for example by setting its bit in an event group or check-in mask, and a supervisor task feeds the hardware watchdog only when all expected bits have been set within the period, then clears them. The timeout is set from the slowest task's period plus margin. A blocked or starved task then stops the feeding and causes a reset, and the supervisor can log which task failed before the reset.
Interview question: What is a windowed watchdog and what does it catch that a normal one does not?
Answer: A watchdog that must be refreshed within a time window: a refresh that is too late or too early causes a reset. Besides hangs, it catches code that runs too fast, such as a loop stuck feeding the watchdog repeatedly, or a control sequence that skips steps and reaches the refresh early, and clock faults that change the loop timing. It is common in safety-related systems where execution timing itself must be monitored.
Build it: a watchdog supervisor for the whole greenhouse
This is step 5, the last of the module project. The controller now runs three jobs from one main loop: reading the soil (step 3), the pump (step 1) and the fan (step 2). The watchdog must restart the controller if any one of them stops working, not only if the whole loop stops.
Lab: Feed the watchdog only when every task is alive
The independent watchdog (IWDG) counts down on the 32 kHz LSI clock and resets the chip when it reaches 0. Each job calls task_alive(id) when it completes a cycle, and the main loop calls supervisor_poll() once a time round.
wdg_start(timeout_ms)picks the smallest prescaler that fits: the counter clock is LSI / (4 << PR) for PR from 0 to 6, and the reload valueRLR = timeout_ms * 32000 / 1000 / (4 << PR) - 1must fit in 12 bits (at most 4095). UnlockPRandRLRby writing0x5555toKR, write them, wait untilSRreads 0 (the values have reached the watchdog's clock domain), reload with0xAAAA, then start with0xCCCC.task_alive(task)records that task 0, 1 or 2 is still working.supervisor_poll()feeds the watchdog (KR = 0xAAAA) only when all three tasks have checked in since the last feed, and then starts counting again.
The classic mistake is to feed the watchdog on every pass of the main loop. Then a hung sensor task never causes a reset, because the loop itself keeps running. When the watchdog fires, the output shows iwdg: reset and the run ends there.
Going deeper
Interview question: How would you choose and feed a watchdog in a greenhouse controller?
Answer: Choose a timeout longer than the longest legitimate loop pass (with margin) but shorter than the time the system can safely be unresponsive. Feed it only from the main loop, after checking every task made progress, never from a timer interrupt that keeps running while the loop hangs. Record the reset cause and count watchdog resets.
Interview question: How should firmware behave after several consecutive watchdog resets?
Answer: Count watchdog resets in a no-init RAM variable or a reset-cause log. After a threshold within a short time, assume the current firmware or configuration is faulty: boot into a safe or degraded mode, revert to factory configuration, or roll back to the previous firmware image, and report the problem. Otherwise the device can loop forever, resetting every few seconds.
Interview question: Why do some watchdogs keep running in low-power modes, and what does that imply?
Answer: An independent watchdog clocked from its own oscillator is designed to catch any hang, including one in a sleep or stop mode, so on many parts it cannot be stopped once started. Firmware must then wake periodically to refresh it, which limits the maximum sleep time and adds energy cost; some parts offer an option to freeze it in stop or standby, set in option bytes.
Explain it: In your own words, explain why a watchdog should be fed only when every critical task has shown it is still working.
Answer: The point of a watchdog is to reset the system when the software is no longer doing its job. If one place feeds it unconditionally, such as a timer interrupt or a single task, the watchdog only proves that that one place still runs, while another task could be stuck forever. Having each critical task check in, and feeding the watchdog only when all of them have checked in during the period, means a hang in any of them stops the feeding and triggers the reset.