In this lesson, you will learn how to configure a hardware Watchdog Timer (WDT) to ensure your system recovers automatically if it hangs during a critical bootloader or firmware update process.
The Watchdog Concept
A hardware Watchdog Timer is a dedicated peripheral that acts as a "dead-man's switch." Once enabled, it runs on an independent clock source. If the processor fails to "kick" or "feed" the watchdog (by resetting its internal counter) before it reaches zero, the hardware automatically triggers a system reset. In the context of a bootloader or a multi-stage firmware update, this is your safety net against infinite loops caused by hardware glitches, corrupted memory, or unexpected interrupts during flash programming.
Implementing the Recovery Pattern
For an update process, you must choose a timeout value that is longer than the longest possible atomic flash operation. If your flash driver takes 50ms to write a page, set your watchdog for 100ms or 200ms to allow for overhead.
Here is how you structure the "kicking" logic:
void flash_update_process(void) {
for (int i = 0; i < total_pages; i++) {
// 1. Kick the watchdog before starting a long operation
watchdog_feed();
// 2. Perform the atomic flash write
if (write_flash_page(i) != SUCCESS) {
handle_error();
}
// 3. Keep feeding until the process completes
}
}
Strategic Placement
The biggest mistake beginners make is feeding the watchdog inside a broad while(1) loop that could potentially hang. Instead, place your watchdog_feed() calls inside the specific stages of your update sequence. If the system hangs inside write_flash_page() due to a peripheral bus error, the watchdog will not be kicked, the timer will expire, and the hardware will pull the reset line, forcing the system back to the reset vector. From there, your startup code can check a "boot failure" flag in non-volatile memory to decide whether to roll back to the previous firmware version or retry the update.
Key Takeaway: The watchdog is your final line of defense; always size your timeout based on worst-case execution time and place your feed calls strategically to avoid deadlocks in your recovery logic.