Course contentsShow
← Rust
Lesson 1499 of 1,91012. Unsafe Rust and Low-Level AccessFree lesson

Watchdog Timer Implementation

You will implement code to reset the system if critical tasks become unresponsive.

Watchdog Timer Implementation

In this lesson, you will learn how to implement a hardware watchdog timer to ensure system recovery when critical tasks hang or enter an unresponsive state.

The Mechanism of a Watchdog

In embedded systems, a watchdog timer (WDT) is a hardware counter that continuously counts down to zero. If the counter reaches zero, the hardware triggers a system reset. To prevent this, the software must periodically "kick the dog"—writing a specific value to a memory-mapped register to reset the counter back to its starting value.

Implementation in Rust

Since we are operating in a no-std environment with memory-mapped I/O (MMIO), we interact with the WDT using raw pointers. Because these operations are inherently unsafe, we wrap them in a safe abstraction to ensure the hardware state remains consistent.

Consider this simplified implementation for a hypothetical platform:

use core::ptr::{read_volatile, write_volatile};

pub struct Watchdog {
    base_addr: *mut u32,
}

impl Watchdog {
    // Kick the dog: reset the timer to prevent a system reset
    pub fn kick(&self) {
        unsafe {
            // Write a "magic number" to the register to reset the counter
            write_volatile(self.base_addr.add(0x04), 0xCAFEBABE);
        }
    }

    // Set the timeout period in milliseconds
    pub fn set_timeout(&self, ms: u32) {
        unsafe {
            write_volatile(self.base_addr.add(0x08), ms);
        }
    }
}

Critical Task Integration

The primary challenge is ensuring the kick method is called within a strict real-time constraint. If your main processing loop hangs due to a deadlock or an infinite logic loop, it will stop calling kick. Once the hardware counter expires, the watchdog forces a hard system reboot.

When implementing this, ensure your kick logic is not blocked by interrupts or lower-priority tasks. In complex systems, you might implement a "task-check" mechanism where the main thread must update a shared atomic variable to prove it is still alive, and only then does the background watchdog task perform the actual kick. This ensures that even if the watchdog interrupt is still firing, the system only recovers if the main logic is verified as functional.

Key Takeaway: A watchdog timer acts as a hardware safety net that resets the system if the software fails to signal its vitality within a defined, time-critical window.