Do you like to write blocking code? Do you often find yourself getting stuck in random functions? If so, then you might be very interested in something called the Watchdog Timer. This little subsystem keeps track of your code execution, and if you don't talk to it within a certain period of time, it will go ahead and reset the microcontroller for you. This can be a very good thing, and it can also cause a lot of problems. As such, it is OFF by default on the M1 and M2. But if you want to explore this functionality, here's how it's done:
1. Include Watchdog Support (header files)
2. Initialize the Watchdog (reset the timer, enable the timer with a specific timeout period)
3. Reset the Watchdog each time through your code
Include Watchdog Support
To utilize the pre-written watchdog functions, include the AVR WDT header, like this:
Initialize the Watchdog
Before you enable the watchdog subsystem, you will want to reset the timer:
Then you need to enable the timer with a specific timeout period:
value is one of the following:
You need to be very careful to set the timeout period to be sufficiently longer than the longest normal code cycle that you might encounter (including interesting forks, loops, interrupts, etc.). You may want to do a quick test to see how long your code actually takes to execute before turning on the watchdog (toggling a port pin every time you return to the top of the main while loop works very well for such a test).
Reset the Watchdog Regularly
Each time through your main while loop, you will need to reset the watchdog timer (essentially letting the system know that your code is continuing to execute as expected):
And that's it. Well, almost. As with everything on the ATmega32U4, you'll find that the Watchdog can do many other things (call interrupts, etc.), but for that you'll need to explore the full datasheet.