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

Handling Hardware Glitches

Implement defensive programming techniques to mitigate against transient electrical faults affecting registers.

In this lesson, you will learn how to implement software-level redundancy to defend your firmware against transient electrical faults that can corrupt register values.

When operating in electrically noisy environments, high-energy particles or electromagnetic interference can trigger "bit-flips"—a phenomenon where a register’s state changes spontaneously despite your code’s logic. In embedded Rust, while we often rely on the compiler’s safety, the underlying hardware registers for critical state machines (like safety interlocks or motor controllers) are susceptible to these external glitches.

Defensive Register Shadowing

A common technique to mitigate transient faults is Register Shadowing. Instead of performing a read-modify-write directly on a peripheral register, you maintain a "shadow" copy in RAM. When setting a critical state, you update both the shadow variable and the peripheral register, then perform periodic verification checks.

struct CriticalController {
    peripheral: *mut u32,
    shadow: u32,
}

impl CriticalController {
    // Update state and verify against the hardware register
    fn update_state(&mut self, new_val: u32) {
        self.shadow = new_val;
        unsafe {
            core::ptr::write_volatile(self.peripheral, new_val);
            
            // Verify immediately: detect transient electrical noise
            if core::ptr::read_volatile(self.peripheral) != self.shadow {
                self.recover();
            }
        }
    }
}

Triple Modular Redundancy (TMR)

For ultra-critical variables held in registers or SRAM, you can implement Triple Modular Redundancy. By storing three identical copies of a critical value and using a "voting" logic (majority rules), you can detect if a single bit-flip has occurred. If two values match and one differs, your software can overwrite the corrupted register with the correct value detected by the majority.

By treating hardware registers as potentially "untrustworthy" sources of truth, you shift from a model of blind execution to one of constant verification. When a mismatch occurs, your logic should trigger a safe-state transition or a controlled reset via your hardware watchdog, ensuring the device doesn't operate on corrupted state variables.

Key Takeaway: Implement register shadowing and majority voting logic to ensure that transient hardware faults are detected and corrected before they result in unsafe firmware behavior.