A watchdog timer helps your device recover if it stops working properly. It resets the system if the program freezes or crashes.
0
0
Watchdog timer operation in Embedded C
Introduction
When you want to make sure your device restarts if it gets stuck.
In safety-critical systems like medical devices or cars to avoid failures.
For embedded devices running long without human help, like sensors or robots.
When debugging to catch unexpected program hangs.
To improve reliability in devices that run continuously.
Syntax
Embedded C
void watchdog_init(void); void watchdog_reset(void); void watchdog_disable(void);
watchdog_init() sets up the timer with a timeout period.
watchdog_reset() must be called regularly to prevent reset.
Examples
Starts the watchdog timer with a preset timeout value.
Embedded C
watchdog_init();
// Initialize watchdog with default timeoutRegularly resets the watchdog inside the main loop to avoid reset.
Embedded C
while(1) { // Your main code watchdog_reset(); }
Stops the watchdog timer, usually used for debugging.
Embedded C
watchdog_disable(); // Turn off watchdog if needed (not always recommended)
Sample Program
This program shows initializing the watchdog, resetting it in a loop, then simulating a hang where the watchdog would reset the system.
Embedded C
#include <stdio.h> #include <stdbool.h> // Simulated watchdog functions static bool watchdog_triggered = false; void watchdog_init(void) { printf("Watchdog initialized with 5 seconds timeout.\n"); } void watchdog_reset(void) { printf("Watchdog reset called.\n"); } void watchdog_disable(void) { printf("Watchdog disabled.\n"); } int main(void) { watchdog_init(); for (int i = 0; i < 3; i++) { printf("Main loop iteration %d\n", i+1); watchdog_reset(); } printf("Simulating program hang... Watchdog will reset system if not reset in time.\n"); // No watchdog_reset() here simulates hang printf("System reset by watchdog!\n"); return 0; }
OutputSuccess
Important Notes
Always call watchdog_reset() before the timeout to avoid unwanted resets.
Watchdog timers are hardware features; their setup depends on your microcontroller.
Disabling the watchdog is usually only for debugging; keep it enabled in real use.
Summary
Watchdog timers help recover from program freezes by resetting the system.
You must regularly reset the watchdog to show the program is running well.
Use watchdogs to improve reliability in embedded systems.