How to Program Timer-2 in PIC16F877A

The following code demonstrate how to use timer-2 for precise delay and clock generation. 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.
Picture 2017-11-26 07_24_22
Picture 2017-11-26 15_48_10

Code in mikroC

// LED blinking @ 10 Hz with time2
// LED ON for 50 mSec
// LED OFF for 50 mSec
/* for internal crystal as clock source, formula is following
Count = [Fosc(Hz) x Tout(Sec)]/[4 x Prescalar x (PR2-TMR2) x Postscaler]
// Fosc(Hz) = 8000000(8Mhz) crystal frequency
// Tout(Sec) = 50 mSec
// Prescalar = 1:1, the other options are:
// 1:4
// 1:16
// PR2 = 0xFF;
// TMR2 = 0x05
// Postscaler = 1:16, and the all options are:
// 1:1
// 1:2
// 1:3 .. 1:16
// Count = 25 numeric value to be placed to obtain the 50 mSec delay
*/
// direction signal
sbit LED_dir at TRISB.B1;
// bit labels portb
sbit LED at PORTB.B1;
// function pro-type
void T2Config(void);
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer2 configration
T2Config();
while(1)
{
while(PIR1.TMR2IF == 0); // wait until TMR2IF = 1
PIR1.TMR2IF = 0; // reset TMR2IF = 0
Count++;
if (Count == 25)
{
LED = ~LED;
Count = 0;
}
}
}
void T2Config(void)
{
PR2 = 0xFF; // load Timer2 Period Register
TMR2 = 0x05; // load timer2 register
T2CON.T2CKPS0 = 0; // 1:1 prescale value
T2CON.T2CKPS1 = 0; // 1:1 prescale value
T2CON.TOUTPS0 = 1; // ———————-
T2CON.TOUTPS1 = 1; // postscalar 1:16
T2CON.TOUTPS2 = 1; //
T2CON.TOUTPS3 = 1; // ———————-
T2CON.TMR2ON = 1; // Enables Timer2
}

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 Interrupts in PIC16F877A

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program SPI in PIC16F877A (Slave Mode)