I see that the user is asking for a general explanation of watchdog timers, not tied to any specific platform. I’ll provide a brief overview of the concept, including how it's used in different architectures.
I can illustrate this using an example like a bare-metal Cortex-M processor such as the STM32, where I’d show how to set up an independent watchdog in C. It’s important to emphasize the initialization, periodic kicking, and what happens if it fails to kick, along with pseudocode for register representation.
I'll also consider providing a software watchdog using a timer and the system_reset() function, along with a simple C library that can be adapted for different environments.Designing a watchdog interface
I’m thinking about creating a simple interface for a watchdog timer with functions like watchdog_init(timeout_ms), watchdog_kick(), and watchdog_handler() that gets triggered by a timer.
I’d like to give implementations for both hardware and a software fallback since the user didn’t specify complexity. I can use generic pseudo-hardware watchdog definitions, but realizing that microcontrollers vary.
I wonder if it’d be better to focus on the Linux /dev/watchdog approach since it uses real C code. On Linux, if I forget to ping /dev/watchdog, it results in a hardware reset, which is essential for system reliability.Outlining a watchdog implementation
I’m thinking about providing template code for a watchdog timer. I’ll assume functions like void mcu_watchdog_init(uint32_t timeout_ms);, void mcu_watchdog_kick(void);, and void mcu_system_reset(void); exist.
It seems useful to show registers that could be adapted. For example, I could present a simple software watchdog in C, using a background thread or timer to increment a counter. If the time since the last kick exceeds a threshold, I'd call system_reset().
While this software approach requires the CPU to be running, a hardware watchdog is generally more reliable. I might consider showing both in a way that the user can adapt to their environment. The user just wants to see how to implement one in C, so presenting an OS-agnostic library with stubs seems like a good way to go.Explaining watchdog functionality
I want to provide a clear explanation of a watchdog timer. It’s designed to reset a system if it hangs. The general pattern is to configure the watchdog timer and periodically "kick" it from the main loop. If it isn't kicked, the hardware performs a reset.
I think I’ll provide two distinct examples: one for a generic MCU using an independent hardware watchdog, perhaps using STM32 as a reference without getting too specific with the registers. It could also be helpful to include sections on using /dev/watchdog in Linux and a software watchdog version for bare-metal or RTOS environments. While it might make the response longer, I believe separating these examples will make it more comprehensive. I could ask the user which environment they're targeting to tailor the response further!Creating a watchdog implementation
I can't make assumptions about the user's situation, but I can provide a general explanation and sample code for a watchdog. Given the importance of safety, I’ll ensure that while resetting a system through software may be sensitive, using a watchdog is a common practice that’s not harmful.
I’m thinking of designing a portable watchdog module with functions like watchdog_init(), watchdog_kick(), and watchdog_update(). The update function will be called periodically from a timer or main loop. If certain time thresholds are exceeded, a reset function will be triggered.
I’ll provide example code, differentiating between hardware and software watchdog implementations. Furthermore, I’ll include an example for using /dev/watchdog in Linux, since that provides practical, compilable code. I'll keep the examples concise and relevant to different environments. A watchdog timer is normally hardware-specific, so the exact registers and calls depend on your MCU/OS. Below are two practical patterns in C:
A generic “software” watchdog you can drop into most C projects (bare-metal or RTOS).
A Linux hardware watchdog example using /dev/watchdog.
1. Generic software watchdog in C (portable pattern)
This is a simple watchdog you can integrate into any C project. You periodically “kick” it from your main loop or task. If it isn’t kicked within the timeout, it calls a platform-specific system_reset() function.
watchdog.h
c
#ifndef WATCHDOG_H
#define WATCHDOG_H
#include <stdint.h>
typedef void (*watchdog_reset_fn_t)(void);
/**
* Initialize watchdog.
*
* @param timeout_ms Timeout in milliseconds.
* @param reset_fn Function called when watchdog expires (must not return).
*/
void watchdog_init(uint32_t timeout_ms, watchdog_reset_fn_t reset_fn);
/**
* "Kick" (feed) the watchdog to prevent reset.
* Call this regularly from healthy code paths.
*/
void watchdog_kick(void);
/**
* Must be called periodically with elapsed time since last call.
* Typically called from a timer interrupt or main loop.
*
* @param elapsed_ms Time elapsed in milliseconds.
*/
void watchdog_update(uint32_t elapsed_ms);
#endif // WATCHDOG_H
watchdog.c
c
#include "watchdog.h"
static uint32_t wdt_timeout_ms = 0;
static uint32_t wdt_counter_ms = 0;
static watchdog_reset_fn_t wdt_reset_fn = 0;
void watchdog_init(uint32_t timeout_ms, watchdog_reset_fn_t reset_fn)
{
wdt_timeout_ms = timeout_ms;
wdt_counter_ms = 0;
wdt_reset_fn = reset_fn;
}
void watchdog_kick(void)
{
// System is alive; reset the counter
wdt_counter_ms = 0;
}
void watchdog_update(uint32_t elapsed_ms)
{
if (wdt_timeout_ms == 0 || wdt_reset_fn == 0) {
return; // Not initialized
}
if (wdt_counter_ms < wdt_timeout_ms) {
wdt_counter_ms += elapsed_ms;
}
if (wdt_counter_ms >= wdt_timeout_ms) {
// Watchdog expired – trigger reset action.
// This function should not return.
wdt_reset_fn();
// If it returns anyway, block here.
while (1) {}
}
}
Example integration (bare-metal/RTOS-like)
You must provide system_reset() for your platform:
c
#include <stdint.h>
#include "watchdog.h"
// Example for ARM Cortex-M (CMSIS)
#include "stm32f4xx.h" // or your device header
static void system_reset(void)
{
NVIC_SystemReset(); // CMSIS function to reset MCU
}
volatile uint32_t g_ms_ticks = 0;
// Called every 1 ms from SysTick_Handler or similar timer ISR
void SysTick_Handler(void)
{
g_ms_ticks++;
watchdog_update(1); // Tell watchdog 1 ms has passed
}
int main(void)
{
// Configure SysTick to generate 1ms interrupts
SystemCoreClockUpdate();
SysTick_Config(SystemCoreClock / 1000);
// Initialize watchdog with 2000 ms timeout
watchdog_init(2000, system_reset);
while (1) {
// Application code
// ...
// As long as this is called at least once every < 2000 ms,
// the system will not reset.
watchdog_kick();
// Simulate work
// (On real system use tasks/RTOS/loops etc.)
}
}
If your code hangs (e.g., infinite loop before watchdog_kick() is called again), watchdog_update() will eventually detect timeout and call system_reset().
To adapt to another platform:
Replace NVIC_SystemReset() with your platform’s reset function.
Ensure watchdog_update() is called periodically (timer ISR, RTOS tick, or main loop with accurate timing).
Note: This is a software watchdog; it depends on the CPU still running the timer/ISR. A true hardware watchdog is safer because it will reset even if interrupts are disabled or the CPU is stuck.
2. Linux hardware watchdog example (/dev/watchdog)
On Linux systems with a hardware watchdog driver enabled, you access it via /dev/watchdog. If your program stops “kicking” it, the hardware will reset the machine.
Simple Linux watchdog daemon in C
c
#define _GNU_SOURCE
#include <fcntl.h>
#include <linux/watchdog.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
static int wdt_fd = -1;
static volatile int running = 1;
static void handle_signal(int sig)
{
running = 0;
}
int main(void)
{
int timeout = 10; // seconds
// Open the watchdog device
wdt_fd = open("/dev/watchdog", O_WRONLY);
if (wdt_fd < 0) {
perror("open /dev/watchdog");
return 1;
}
// Set the timeout, if supported
if (ioctl(wdt_fd, WDIOC_SETTIMEOUT, &timeout) < 0) {
perror("WDIOC_SETTIMEOUT");
// Not fatal; some drivers don't support setting timeout.
} else {
printf("Watchdog timeout set to %d seconds\n", timeout);
}
// Catch signals so we can clean up
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
while (running) {
// "Kick" the watchdog by writing any byte
if (write(wdt_fd, "\0", 1) < 0) {
perror("write to watchdog");
break;
}
// Your health checks go here:
// - is main service alive?
// - is system load reasonable?
// - etc.
// If a check fails, simply stop kicking (break the loop).
sleep(1);
}
// Optionally disable watchdog on exit:
int flags = WDIOS_DISABLECARD;
if (ioctl(wdt_fd, WDIOC_SETOPTIONS, &flags) < 0) {
perror("WDIOC_SETOPTIONS");
// Some systems will reboot shortly if you just close.
}
close(wdt_fd);
return 0;
}
As long as the program runs and writes to /dev/watchdog, the system won’t reboot.
If the program hangs or exits without disabling the watchdog, the system will reset after timeout seconds.
Using a true hardware watchdog on an MCU
On a microcontroller, replace the software module with the chip’s watchdog:
Conceptually:
c
void watchdog_init_hw(void)
{
// 1. Enable watchdog clock
// 2. Set timeout reload value
// 3. Enable reset on timeout
}
void watchdog_kick_hw(void)
{
// Write the special "reload" key to the watchdog register
// to prevent it from timing out.
}
You then call watchdog_kick_hw() from your main loop/tasks. If the firmware locks up and stops calling it, the hardware automatically resets the chip.
The exact implementation depends on your MCU (e.g., STM32 IWDG, AVR WDT, NXP WDT). You must follow the reference manual for register names and magic keys.
If you tell me your target (e.g., STM32F4 bare-metal, AVR, ESP32, or Linux), I can provide a concrete hardware-specific implementation in C.