How to Program Watchdog Timer Reset in PIC16F877A

The following code demonstrate how to use watchdog timer in your program to avoid processor hanging. The watchdog timer is needed when processor goes to unknown state or in an infinite loop, this timer reset the program after the time overflow and processor start again execution from the main() program. The code is written in “mikroC PRO for PIC v.6.6.3” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.
According to datasheet, watchdog timer overflow time is approximate 18 mSec (prescalar 1:1) to 2.304 Sec (prescalar 1:128). Reference is following:
Picture 2017-11-22 21_05_04
Enable the watchdog timer:
wdt config
wdt config 1
Picture 2017-11-22 21_15_32

Code in mikroC

/*
// watchdog overflow time calculation
// according to device datasheet
// at no prescalar (1:1), the overflow
// time is following.
// min typ max
// 7 18 33 (ms)
// WDT Overflow = Tcons * prescalar
// = 18(ms) * 128
// = 2.304 sec
*/
sbit LED_WDT_Dir at TRISC.B0;
sbit LED_WDT at PORTC.B0;
void WDTEnable(void);
void main(void)
{
unsigned char count=0;
TRISB = 0x00; // portb as output
PORTB = 0x00; // portb init to 0x00
LED_WDT_Dir = 0;
LED_WDT = 1;
Delay_ms(500);
WDTEnable();
while(1)
{
LED_WDT = 0;
PORTB = count++;
if(count == 150)
{
// WDT counter overflow and software reset
// approx. 2.304 sec wait
while(1); // just to demonstrate WDT
}
asm CLRWDT; // clear WDT
Delay_ms(100);
}
}
void WDTEnable(void)
{
OPTION_REG.PS0 = 1; //—————
OPTION_REG.PS1 = 1; // prescalar 128
OPTION_REG.PS2 = 1; //—————
OPTION_REG.PSA = 1; // Prescaler is assigned to the WDT
asm CLRWDT; // clear WDT
}

Download Files

For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.

Comments

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)