Course contentsShow
← Rust
Lesson 1865 of 1,91016. Specialized Runtime TargetsFree lesson

Hardware Watchdog Integration

Implement watchdog timer management to provide system-level fault recovery.

In this lesson, you will learn how to implement a hardware watchdog timer in Rust to ensure system-level fault recovery by automatically triggering a reset if your firmware stops responding.

The Watchdog Principle

A hardware watchdog is essentially a countdown timer tied directly to the system reset line. Once enabled, your software must "kick" or "pet" the watchdog (reset its counter) at regular intervals. If a software hang, infinite loop, or critical fault occurs and you fail to pet the dog in time, the hardware assumes the system is unresponsive and forces a hard reset.

Implementation Strategy

In Rust, this is typically handled via volatile register writes to a memory-mapped I/O (MMIO) address. Since the watchdog is a safety mechanism, it must be robust against compiler optimizations. We use the core::ptr::write_volatile function to ensure the "petting" operation is never optimized away by the LLVM backend.

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

pub struct Watchdog {
    base_addr: *mut u32,
}

impl Watchdog {
    // Pet the watchdog by writing a specific magic value to the control register
    pub fn pet(&self) {
        unsafe {
            // Writing the 'kick' pattern to the WDT_KICK register
            write_volatile(self.base_addr.add(0x04), 0xFEED);
        }
    }
}

Critical Considerations

When integrating this into a real-time system, you must be careful about where you pet the dog. Avoid placing the pet() call inside an interrupt service routine (ISR) that might be pre-empting the main logic; if the main task hangs but interrupts continue to fire, the watchdog will remain unaware of the application-level failure.

Instead, establish a "heartbeat" pattern. Each core component of your system must report a healthy state to a supervisor task. Only if all components report as "ready" should the supervisor perform the final write to the watchdog register. This ensures that a stall in any critical thread eventually leads to a system recovery.

Key Takeaway: A hardware watchdog is your final safety net; by using volatile writes to signal health, you ensure that the system recovers from catastrophic hangs that would otherwise brick your device.