How to Program Timer-1 in PIC16F877A
The following code demonstrate how to use timer-1 for clock generation or precise time delay. In this example internal clock is used as a source for timer1. 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.
Code in mikroC
// LED blinking @ 10 Hz with time1
// 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 (65536-TMR1)]
// Fosc(Hz) = 8000000(8Mhz) crystal frequency
// Tout(Sec) = 50 mSec
// Prescalar = 1:1, the other options are:
// 1:2
// 1:4
// 1:8
// TMR1 = 55,536 (0xD8F0)
// Count = 10 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 T1Config(void);
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer1 configration
T1Config();
while(1)
{
while(PIR1.TMR1IF == 0); // wait until TMR1IF = 1
PIR1.TMR1IF = 0; // reset TMR1IF = 0
TMR1H = 0xD8; // reload higher byte
TMR1L = 0xF0; // reload lower byte
Count++;
if (Count == 10)
{
LED = ~LED;
Count = 0;
}
}
}
void T1Config(void)
{
TMR1H = 0xD8; // load higher byte
TMR1L = 0xF0; // load lower byte
T1CON.T1CKPS1 = 0; // 1:1 prescale value
T1CON.T1CKPS0 = 0; // 1:1 prescale value
T1CON.T1OSCEN = 1; // Oscillator is enabled
T1CON.T1SYNC = 0; // This bit is ignored
T1CON.TMR1CS = 0; // Internal clock (FOSC/4)
T1CON.TMR1ON = 1; // Enables Timer1
}
// 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 (65536-TMR1)]
// Fosc(Hz) = 8000000(8Mhz) crystal frequency
// Tout(Sec) = 50 mSec
// Prescalar = 1:1, the other options are:
// 1:2
// 1:4
// 1:8
// TMR1 = 55,536 (0xD8F0)
// Count = 10 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 T1Config(void);
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer1 configration
T1Config();
while(1)
{
while(PIR1.TMR1IF == 0); // wait until TMR1IF = 1
PIR1.TMR1IF = 0; // reset TMR1IF = 0
TMR1H = 0xD8; // reload higher byte
TMR1L = 0xF0; // reload lower byte
Count++;
if (Count == 10)
{
LED = ~LED;
Count = 0;
}
}
}
void T1Config(void)
{
TMR1H = 0xD8; // load higher byte
TMR1L = 0xF0; // load lower byte
T1CON.T1CKPS1 = 0; // 1:1 prescale value
T1CON.T1CKPS0 = 0; // 1:1 prescale value
T1CON.T1OSCEN = 1; // Oscillator is enabled
T1CON.T1SYNC = 0; // This bit is ignored
T1CON.TMR1CS = 0; // Internal clock (FOSC/4)
T1CON.TMR1ON = 1; // Enables Timer1
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment