What is a Watchdog?

ampheoampheo
2 min read

A Watchdog (or Watchdog Timer, WDT) is a critical hardware or software mechanism designed to detect and recover from system crashes or freezes in embedded systems (e.g., microcontrollers like STM32, Arduino, or ESP32). It acts as a "safety net" by resetting the system if the software fails to respond within a predefined time window.


How a Watchdog Works

  1. Initialization:

    • The watchdog timer is configured with a timeout period (e.g., 1 second).

    • The system must periodically "feed" (reset) the watchdog before this timer expires.

  2. Operation:

    • If the software runs normally, it sends regular "keep-alive" signals to the watchdog.

    • If the system freezes or crashes, the watchdog is not fed, and it triggers a reset to restore functionality.


Types of Watchdogs

TypeDescription
Hardware WatchdogDedicated timer circuit (independent of the CPU). More reliable.
Software WatchdogImplemented via firmware. Less robust (may fail if CPU locks up).

Key Applications

Embedded Systems (Prevents lockups in IoT devices, industrial controllers).
Safety-Critical Systems (Medical devices, automotive ECUs).
Remote Devices (Recovers unattended systems without manual intervention).


Example Code (STM32 with HAL)

c

#include "stm32f4xx_hal.h"

IWDG_HandleTypeDef hiwdg;  // Independent Watchdog Timer

void Init_Watchdog() {
  hiwdg.Instance = IWDG;
  hiwdg.Init.Prescaler = IWDG_PRESCALER_32;  // Timeout ~1s
  hiwdg.Init.Reload = 0x0FFF;                // Reset period
  HAL_IWDG_Init(&hiwdg);
}

void Feed_Watchdog() {
  HAL_IWDG_Refresh(&hiwdg);  // Reset the watchdog counter
}

int main() {
  Init_Watchdog();
  while (1) {
    // Normal operation
    Feed_Watchdog();  // Must be called before timeout
    HAL_Delay(500);   // Simulate work
  }
}

Failure Scenario: If Feed_Watchdog() is not called within 1 second, the system reboots.


Advantages

  • Prevents Infinite Loops: Resets the system if code gets stuck.

  • Improves Reliability: Critical for unattended devices.

  • Low Hardware Cost: Often built into microcontrollers.


Watchdog vs. Reset Button

FeatureWatchdogManual Reset
AutomationSelf-triggeringRequires human action
SpeedMilliseconds to secondsSlow (manual response)
Use CaseEmbedded systemsDebugging

Did you know? NASA’s Mars rovers use watchdogs to recover from radiation-induced glitches!

0
Subscribe to my newsletter

Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ampheo
ampheo