Architecture and Hardware

What Is a Watchdog Timer and How Does It Work?

What a watchdog timer is, how it resets a hung microcontroller, the main types, AVR and STM32 code examples, and where to kick it so it actually catches faults.

On this page
  1. The short answer
  2. How a watchdog timer works
  3. Why embedded systems need one
  4. Types of watchdog timer
  5. Example: watchdog on an Arduino Uno (AVR)
  6. Example: STM32 independent watchdog
  7. Where to kick the watchdog (and where not to)
  8. Choosing a timeout
  9. Common pitfalls
  10. What a watchdog can’t do
  11. Summary

The short answer

A watchdog timer is a hardware timer that resets a microcontroller if the software stops responding. Once started, it counts towards a timeout. Your firmware must regularly restart the count, called “kicking,” “feeding,” “petting” or “refreshing” the watchdog, to show it’s still running properly. If the firmware hangs, crashes or gets stuck in a loop and misses a refresh, the timer runs out and resets the chip, so the system can start again in a known state.

It’s a last line of defence for devices that have to keep working without anyone around to press a reset button.

How a watchdog timer works

The basic sequence is the same on almost every chip:

  1. Configure and start. Firmware sets a timeout, typically somewhere between a few milliseconds and several seconds, and enables the watchdog. Some chips can also enable it automatically at power-up through a configuration fuse or option byte.
  2. Count. The watchdog counts from its own clock, independently of what the CPU is doing.
  3. Refresh. While things are healthy, firmware writes to a watchdog register, often with a specific key value, to restart the count before it expires.
  4. Timeout. If no refresh arrives in time, the watchdog takes action: usually it resets the microcontroller, and on some chips it first raises an interrupt.
  5. Restart. After the reset, firmware can read a reset-cause register to see that the watchdog triggered it, and log or handle that.

The key idea is that the watchdog doesn’t need the CPU to be working in order to act. That independence is what lets it recover from faults that the software itself can’t detect.

Why embedded systems need one

Desktop computers have a person who can notice a freeze and restart them. Many embedded devices don’t: a remote sensor, a pump controller, a vehicle module or a satellite may have to recover on its own. A watchdog helps with:

  • Software bugs: infinite loops, deadlocks between tasks, or code waiting forever for a flag that’s never set
  • Peripheral hangs: for example, an I2C transfer that never completes because a device is holding the bus
  • Electrical disturbances: noise, brownouts or radiation corrupting a register or the program counter
  • Unexpected conditions: input data or timing the code was never tested against

A well-known example is the Mars Pathfinder lander in 1997. A priority inversion problem caused a high-priority task to miss its deadline, which was detected by a watchdog-style timer that reset the system. The resets kept the spacecraft recoverable while engineers diagnosed the bug and uploaded a fix.

Types of watchdog timer

Internal vs external

  • Internal watchdogs are built into the microcontroller. Nearly every modern MCU has at least one, and they cost nothing extra to use.
  • External watchdogs are separate chips, often combined with a voltage supervisor, that pull the microcontroller’s reset pin if a watchdog input pin isn’t toggled in time. They’re used when the design needs a watchdog that’s fully independent of the MCU’s own clock, silicon and configuration, which is common in safety-related designs.

Independent watchdog

An independent watchdog runs from its own low-speed oscillator rather than the main system clock, so it keeps running even if the main clock fails. STM32 chips call theirs the IWDG. On many such parts, once started, the independent watchdog can’t be switched off by software; only a reset stops it.

Windowed watchdog

A basic watchdog only checks that you refresh it before the deadline. A windowed watchdog also resets the chip if you refresh it too early. That catches a different kind of fault: code that is stuck in a tight loop which happens to include the refresh call. STM32’s WWDG is an example.

Reset, interrupt, or both

Some watchdogs can raise an interrupt before, or instead of, a reset. The AVR watchdog in the ATmega328P, for instance, can be set to interrupt mode, reset mode, or interrupt-then-reset. An early-warning interrupt gives firmware a chance to save diagnostic information, such as the address it was executing, before the reset happens. Interrupt-only mode is also used as a low-power wake-up timer.

Example: watchdog on an Arduino Uno (AVR)

The AVR C library provides simple macros for the ATmega328P’s watchdog, which supports timeouts from about 16 ms up to about 8 seconds:

#include <avr/wdt.h>

void setup() {
  MCUSR = 0;               // clear reset flags, including the watchdog flag
  wdt_disable();           // turn off any watchdog left running from a previous reset
  wdt_enable(WDTO_2S);     // reset if not refreshed within about 2 seconds
}

void loop() {
  readSensors();
  updateOutputs();
  wdt_reset();             // kick the watchdog once per healthy pass
}

Clearing MCUSR and disabling the watchdog early matters. On AVR, after a watchdog reset the watchdog stays enabled, often at its shortest timeout. If your startup code takes longer than that before it reaches wdt_reset(), the chip resets again and again. Some older Arduino bootloaders had trouble with this, so a watchdog reset could leave a board stuck in a reboot loop. Check that your board’s bootloader handles watchdog resets before relying on it.

Example: STM32 independent watchdog

With the STM32 HAL, the IWDG is set up with a prescaler and a 12-bit reload value, then refreshed with one call:

IWDG_HandleTypeDef hiwdg;

void watchdog_init(void) {
    hiwdg.Instance = IWDG;
    hiwdg.Init.Prescaler = IWDG_PRESCALER_64;
    hiwdg.Init.Reload = 1000;   // roughly 2 s with a ~32 kHz LSI clock
    HAL_IWDG_Init(&hiwdg);      // starts the watchdog
}

while (1) {
    do_work();
    HAL_IWDG_Refresh(&hiwdg);
}

The timeout is approximately prescaler × (reload + 1) / LSI frequency. The LSI is an internal RC oscillator, and its frequency can vary noticeably between parts and with temperature, so treat the calculated timeout as approximate and check your chip’s datasheet for its range. Field names and some details vary between STM32 families.

Where to kick the watchdog (and where not to)

Where you place the refresh call decides whether the watchdog actually protects you.

Don’t kick from a timer interrupt

It’s tempting to refresh the watchdog from a periodic timer interrupt so it “never fires by accident.” But a timer interrupt can keep running while the main code is completely stuck, so the watchdog never notices the hang. Similarly, scattering refresh calls throughout the code, especially inside loops that wait on hardware, lets a stuck section keep the watchdog happy.

A good rule: refresh the watchdog in one place, and only when you’ve confirmed that the system is doing useful work.

Checking several tasks before kicking

With an RTOS or several independent activities, a single refresh in one task proves only that that task is running. A common pattern is:

  1. Each important task sets its own “I’m alive” flag, or increments a counter, each time it completes a cycle.
  2. A supervisor routine checks that every flag has been set since the last check.
  3. Only if all tasks have checked in does it refresh the watchdog and clear the flags.

If any task stalls, the watchdog isn’t refreshed and the system resets. Some platforms provide this built in; ESP-IDF on the ESP32, for example, includes a task watchdog that can monitor selected FreeRTOS tasks. For more on how tasks, drivers and hardware fit together, see our overview of embedded system architecture.

Choosing a timeout

There’s no single correct value. Some points to weigh:

  • Longer than your worst-case healthy cycle. Include slow operations such as flash erases, network retries or long sensor conversions. If some operations are unavoidably long, break them up and refresh between steps, or allow for them explicitly, rather than setting a huge timeout for everything.
  • Short enough to matter. A motor controller may need to recover within milliseconds; a weather station logging once a minute can tolerate seconds.
  • Allow for clock tolerance. Watchdog oscillators are often imprecise, so leave a comfortable margin.
  • Consider what the reset itself does. A reset should leave outputs in a safe state. Make sure actuators default to off or safe at power-up, for instance with pull-down resistors on driver inputs.

Common pitfalls

  • Debugging with the watchdog running. When you halt the CPU at a breakpoint, the watchdog may keep counting and reset the chip mid-session. Many MCUs, including STM32 parts through their debug configuration registers, can freeze the watchdog while the core is halted.
  • Ignoring the reset cause. Read and log the reset-cause register at boot. A device that silently resets every few hours has a bug you’d want to know about.
  • Reset loops. If a fault happens early in startup, the device can reset endlessly. Counting consecutive watchdog resets, stored somewhere that survives a reset, lets firmware fall back to a safe mode after several in a row.
  • Low-power modes. Some watchdogs keep running in sleep, so a device that sleeps longer than the timeout will reset. Check how your chip’s watchdog behaves in each power mode.
  • Starting it too late. If the watchdog is only enabled after a long initialisation, hangs during start-up aren’t covered.

What a watchdog can’t do

A watchdog helps the system recover; it doesn’t fix the underlying fault. It won’t catch code that keeps running and keeps refreshing the timer while producing wrong results, and resetting can itself be disruptive if the device was in the middle of something important. Treat it as one safety layer alongside careful design, testing, input validation and, where needed, hardware protections such as brownout detection.

Summary

  • A watchdog timer resets the microcontroller if firmware fails to refresh it within a set time.
  • It runs independently of the CPU, so it can recover from hangs the software can’t detect.
  • Types include internal and external, independent and windowed, and reset or interrupt-based.
  • Refresh it in one place, only after confirming that the whole system is healthy, never from a timer interrupt.
  • Pick a timeout with margin, check the reset cause at boot, and plan for debugging and low-power modes.

The complete guide to architecture and hardware

Embedded System Architecture: Hardware and Software Components
Read the guide

Keep exploring

Guides from other topics

All topics →