Watchdog

What is a watchdog?

A watchdog in embedded systems is a feature to increase safety in your system. How and how much it will increase safety will depend on how it is implemented but use of one is critical to assure at least a base level of safety in your projects. I rarely see these mentioned for beginners, and that is understandable. But they are simple enough to start playing around with that I think they are worth using for even quite novice programmers

How does a watchdog work?

A watchdog can theoretically be a quite advanced feature to make sure an embedded device is running safely. But what is normally meant is a built in watchdog timer peripheral. The operation of this is then quite simple. It will count down at a set rate and if it reaches zero it will perform a safety action, usually a reset of the microcontroller. The program need to "kick" the watchdog before it reaches zero. This is done by writing to a special register specified in the datasheet. This sets the counter to a higher value again, and the program can continue to run. It is usually not a simple register write, normally the register need to be "unlocked" by following a sequence. In the STM32 controllers I used in some other project the sequence was to write a special value into the register, followed by the new counter value within a few ms.

What can watchdogs protect against?

Watchdogs can protect against some different problems. The most basic protection is to protect against the program getting stuck in infinite loops. This is easily achieved by placing the "kick" function at the end of the main while() loop like this. 

while(1){

stuff;
more_stuff;
potentially_infinite_loop_stuff;
kick_watchdog;
}

The MCU will reset if the program takes to long to iterate through the while() loop content. 

Another more advanced way to use it is to make sure certain very important functions are actually run at the rate they should. Imagine you have a state machine with one very important state, say, a safety check state. Placing the "kick" function at the end of this check will now enforce that this function is run at a predictable rate. If it does not, the MCU will reset. 

Should I use one?

A simple watchdog protecting against infinite loops is so simple to implement there is in my opinion no reason to not use one as soon as a device is deployed for real. It does not need to be super time sensitive or so but it is pretty nice to know that there is some kind of protection against logic errors forcing the program into a strange state. 

This article was updated on February 21, 2025