Tuesday, 27 September 2011

OverviewIn this post I will be describing how to use the Watchdog Timer of the ATmega1281 in order to detect and handle code lock-ups and at the same time, as a timer to wake the device from low power sleep mode.Note this same approach should work with the ATmega640, ATmega1280, ATmega2560 and ATmega2561 micro-controllers.This entry assumes the reader has some experience developing for the ATmega1281 micro-controller, understands how a typical Watchdog Timer works and understands the sleep modes of he ATmega1281.

Atmega1281 Watchdog Timer (WDT)FunctionalityThe WDT has three modes of operation:

Interrupt - The WDT_vect interrupt sub-routing will be called when the WDT times out. Can be used to wake the micro from sleep modes, including the lowest power sleep mode (SLEEP_MODE_PWR_DOWN), where other timers are not available.

System Reset - A watchdog time-out reset will occur, i.e. the micro-controller will be restarted. For use in handling code lockups.

Interrupt and System Reset - First the WDT_vect interrupt sub-routing will be called, when completed a watchdog time-out reset will occur.

The WDT has it's own internal clock, that gives us time-out resolutions from 16ms to 8s.

Note, after a System Reset the WDT is still enabled, also the configuration will have reverted to default, i.e. 16ms time-out, If the user doesn't re-configure or disable the WDT before that time-out you can end up with the micro in a continuous System Reset loop. The following will disable the WDT before user code is executed:

Control & RegistersThere are two sets of registers to be used when controlling the WDT:

WDTCSR - Watchdog timer Control Register, used for configuring the time-out, mode of operation, etc.

MCUSR - MCU Status Register, used to tell the cause of the last reset, such as brown-out reset, watchdog reset, etc. NOTE: for security reasons, there is a timed sequence for clearing the WDE and changing the time-out configuration. If you don't use this sequence properly, you'll get unexpected results.

AVR LibrariesAtmel provide a set of macros for controlling the WDT. If you simply want to use the WDT to detect code lock-ups, that library will be fine. If you want to do anything more advanced, you will also have to manually configure the above registers.

CodeWe want to use the WDT for two purposes simultaneously; detect/handle code lock-ups and as a timer to bring us out of sleep mode.For this we will use the WDT in interrupt mode only. Depending on why the interrupt has entered, we will either force a watchdog system reset or wake the main application from it's sleep mode.