</>EmbeddedInterview

What is a watchdog timer and how should you use it?

EasyEmbedded C

Short answer: A watchdog is an independent hardware timer that resets the microcontroller unless software "kicks" (refreshes) it before it expires. It recovers the system from software hangs, infinite loops, deadlocks and runaway code. To be effective, the kick must prove that the whole system is healthy, not just that one timer interrupt is still running.

Types

  • Independent watchdog (e.g. STM32 IWDG): runs from its own low-speed oscillator, so it works even if the main clock fails; often cannot be stopped once started.
  • Window watchdog (WWDG): a refresh that comes too early also triggers a reset, catching code that runs too fast or loops around the kick.
  • External watchdog ICs: a separate chip, required in some safety designs, can also monitor supply voltage.

Good practice

  1. Kick from one place, after checking that every critical task has checked in. Each task sets its bit in a "alive" mask; a supervisor (main loop or low-priority task) kicks only when all bits are set, then clears them.
static volatile uint32_t alive;
#define TASK_COMMS  (1u << 0)
#define TASK_CTRL   (1u << 1)
#define ALL_TASKS   (TASK_COMMS | TASK_CTRL)

void task_checkin(uint32_t bit) { __atomic_fetch_or(&alive, bit, __ATOMIC_RELAXED); }

void supervisor_tick(void)                 /* every 100 ms */
{
    if ((alive & ALL_TASKS) == ALL_TASKS) {
        IWDG->KR = 0xAAAAu;                /* refresh */
        alive = 0;
    }                                      /* else: let the watchdog reset the chip */
}
  1. Never kick from a timer ISR alone: the ISR keeps running when the main loop is stuck, so the watchdog never fires.
  2. Record the reset cause at boot (RCC->CSR flags on STM32) and log or report watchdog resets; they are evidence of field bugs.
  3. Choose the timeout longer than the worst-case loop time (including flash erase and slow operations), but short enough to recover quickly; disable or extend it carefully during long operations instead of kicking in many places.
  4. Low-power modes: decide whether the watchdog should run (and wake the device) in stop/sleep modes.
  5. Debugging: freeze the watchdog when the core is halted by the debugger (DBGMCU freeze bits), or you get resets while stepping.
  6. After a watchdog reset: consider a safe mode if resets repeat (count them in a .noinit variable), instead of an endless reset loop.