Raspberry Pi Pico Tips and Tricks

Friday 1 March 2024

The Watchdog timer on the Raspberry Pi Pico (Don't forget to feed the dog!)

The Watchdog Timer

A WatchDog Timer (WDT) is a hardware timer that is used to detect and recover from errors in our programs or faults in their execution. Once initiated, a watchdog timer is constantly counting down and when (or if) it reaches zero, it reboots our device. The only thing that stops the timer reaching zero is periodic resetting of the timer back to its starting position. We place lines in our code at strategic points that perform this reset, so that under normal operation the timer should never reach zero. These resets are referred to as ‘patting the dog’, ‘feeding the dog’ or cruelly, ‘kicking the dog’ (not happy about that one).

While we aren’t going to purposely design our software to freeze, strange things can happen (cosmic rays - really!) and it is often practical to prepare for the unexpected. Conversely, you might notice that your device hangs for no apparent reason after long periods. Weird stuff does happen. When it’s more important that the system keeps functioning than it is to troubleshoot the problem, a watchdog timer could be your friend.

In the Raspberry Pi Pico or more precisely the RP2040, the watchdog has a 24-bit counter that decrements from a user defined value. The maximum time between resetting the watchdog counter is approximately 8.3 seconds before it reaches zero and reboots our device.

In a very simple code example from the MicroPython documentation we can see the watchdog timer library loaded, the timer is enabled with a time of 2000 milliseconds (2 seconds) and then the watchdog is fed.

from machine import WDT
wdt = WDT(timeout=2000)  # enable it with a timeout of 2s
wdt.feed()

In our code we would set our timer appropriate for the occasion and place the feeding statements in strategic places so that under normal circumstances, there shouldn’t be a situation where it would run down for more than the specified amount of time before being fed again.

Don't forget, if you're looking for the book 'Raspberry Pi Pico Tips and Tricks'. You can download it for free (or donate if you wish) from here.

No comments:

Post a Comment