Jan 202015

MPLAB - Backup reset condition flagsWatchdog is probably one of the best PIC microcontroller features. Yes, it would be great if you would write perfect code and program would not get stuck in the first place, but let’s face it: mistakes are going to be made. And really, are you going to write timeout code around every communication routine just so you can detect one in million error?

In 99% of cases, you will just turn on WDT timer in your config bits and count on it to reset microcontroller if something goes wrong. If watchdog times out, program will start from scratch and all is good. For all practical purposes, watchdog-initiated restart is same as normal start. Or is it?

Most PIC microcontrollers clear their ~TO bit in STATUS register as a way to detect watchdog restart. However, if you try to read that from your XC8 compiled C program it will seem that every microcontroller start is normal. It will report any timeout. Cause? Because your compiler is clearing STATUS register before your program starts running.

If you are interested in watchdog timeouts, first you need to tell your compiler to preserve startup status for you. This can be done by going into project properties, selecting XC8 linker category and checking Backup reset condition flags item. Now your compiler will give you access to two special variables: __timeout and __powerdown. These variables will be copy of ~TO and ~PD states respectively.

If you read datasheet carefully you will notice that ~TO will be 0 if timeout has occurred. Thus code to check for it would look something as:

void main() {

    if (__timeout == 0) { //value 0 means there was a timeout
        //this restart is due to the watchdog timeout - do something here


PS: Procedure described here is specific to XC8 compiler. But same principle applies with most other compilers too.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>