0
0
Embedded Cprogramming~5 mins

Why watchdog timer is needed in Embedded C

Choose your learning style9 modes available
Introduction

A watchdog timer helps keep an embedded system running smoothly by restarting it if it gets stuck or stops working properly.

When a device must keep running without human help, like a home security system.
In machines that control important tasks, such as medical devices or cars.
When software might freeze or crash due to unexpected errors.
In remote systems where fixing problems manually is hard or slow.
To improve reliability by automatically recovering from software faults.
Syntax
Embedded C
void watchdog_init(void);
void watchdog_reset(void);
void watchdog_enable(void);
void watchdog_disable(void);
The watchdog timer is usually set up to reset the system if not reset regularly.
You must reset (kick) the watchdog timer in your code to show the system is working.
Examples
Initialize and enable the watchdog, then regularly reset it inside the main loop.
Embedded C
watchdog_init();
watchdog_enable();

while(1) {
    // main code
    watchdog_reset(); // reset timer to prevent reset
}
Disable the watchdog timer if you want to stop it temporarily (not recommended for safety).
Embedded C
watchdog_disable();
Sample Program

This program simulates a watchdog timer that resets the system if it detects a problem. When the system hangs at loop 3, the watchdog triggers a reset.

Embedded C
#include <stdio.h>
#include <stdbool.h>

// Simulated watchdog functions
bool watchdog_triggered = false;

void watchdog_init(void) {
    printf("Watchdog initialized.\n");
}

void watchdog_enable(void) {
    printf("Watchdog enabled.\n");
}

void watchdog_reset(void) {
    printf("Watchdog reset. System is alive.\n");
}

void watchdog_check(bool system_ok) {
    if (!system_ok) {
        watchdog_triggered = true;
        printf("Watchdog triggered! System will reset.\n");
    }
}

int main() {
    watchdog_init();
    watchdog_enable();

    bool system_ok = true;

    for (int i = 0; i < 5; i++) {
        if (i == 3) {
            system_ok = false; // Simulate system hang
        }

        if (system_ok) {
            watchdog_reset();
        } else {
            watchdog_check(system_ok);
            if (watchdog_triggered) {
                printf("System reset by watchdog.\n");
                break;
            }
        }
    }

    return 0;
}
OutputSuccess
Important Notes

Always reset the watchdog regularly in your main program to avoid unwanted resets.

Watchdog timers are a safety net, not a fix for bad code.

Summary

A watchdog timer helps detect and recover from system freezes.

It resets the system if the program stops responding.

Use it to improve reliability in embedded systems.