Watchdog Timer with MicroPython and CircuitPython
Apr 20, 2023Microcontrollers are single purposes devices that run unattended. Consider the following microcontroller mission:
- Connect to a wifi network
- Query a API enpoint
- Process data received from the API
- Update an LCD with data
While this mission is not overly complex, the microcontroller is interacting with external devices; a network, a server, an LCD panel, and lights. Things can go wrong and over time and it's likely there will be an untrapped error condition at some point. This is where a watchdog timer comes in. Instead of having the microcontroller be unresponsive, the watchdog can reboot it. This is ideal for an unattended device.
A watchdog timer is started for a specific time, in seconds. When the timer runs out, the microcontroller is reset. To prevent the watchdog from resetting, it needs to be fed before the timer runs out.
In the example programs below, the watchdog timer is set for 5 seconds. Each interaction of the While loop, the watchdog is fed. With the sleep timer set at 1 second, the watchdog is fed every 1 second, therefore, it never resets the microcontroller. If you set sleep_time to 6 seconds, the watchdog timer will expire in the first interaction and the microcontroller will reboot.
Example 1: MicroPython on Pi Pico
# main.py
# MicroPython v1.19
# WatchDog Timer exmaple - Pi Pico
from machine import WDT
import time
# Set watchdog to 5 seconds
wd = WDT(timeout=5000)
sleep_time = 1
counter = 1
while True:
print(counter)
# Feed the dog
wd.feed()
time.sleep(sleep_time)
counter += 1
Example 2: CircuitPython on Pi Pico
At the time of this writing, the CircuitPython watchdog timer methods described in the documentation are not working.
# code.py
# CircuitPython 8.0.5
# WatchDog Timer exmaple - Pi Pico
from microcontroller import watchdog as wd
from watchdog import WatchDogMode
import time
# Set watchdog to 5 seconds
wd.timeout=5
# Start the watchdog
wd.mode = WatchDogMode.RESET
sleep_time = 1
counter = 1
while True:
print(counter)
# Feed the dog
wd.feed()
time.sleep(sleep_time)
counter += 1