How to Program Timer-0 in PIC16F877A (External Clock)
The following code demonstrate how to use timer-0 for clock generation or precise time delay. In this example external clock of 1Khz is used as a source for timer0. 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 @ 1.0 Hz with time0
// LED ON for 0.5 sec
// LED OFF for 0.5 sec
/* for external clock source, formula is following
Count = [Freq(Hz) x Tout(Sec)]/[Prescalar x (256-TMR0)]
// Freq(Hz) = 1000(1Khz) external clock
// Tout(Sec) = 1.0
// Prescalar = 2, the other options are:
// 1:2
// 1:4
// 1:8
// 1:16
// 1:32
// 1:64
// 1:128
// 1:256
// TMR0 = 6
// Count = 2 numeric value to be placed to obtain the 0.5 Sec delay
*/
// direction signal
sbit LED_dir at TRISB.B1;
// bit labels portb
sbit LED at PORTB.B1;
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer0 configration
TMR0 = 6; // timer0 register init
OPTION_REG.T0CS = 1; // external clock on select
OPTION_REG.T0SE = 0; // Low to High Edge
OPTION_REG.PSA = 0; // prescaler is assigned to the Timer0 module
OPTION_REG.PS0 = 0; //———————-
OPTION_REG.PS1 = 0; // prescalar 2 select
OPTION_REG.PS2 = 0; //———————-
while(1)
{
while(INTCON.T0IF == 0); // wait until T0IF = 1
INTCON.T0IF = 0; // reset T0IF = 0
TMR0 = 6; // timer0 register reset
Count++;
if (Count == 2)
{
LED = ~LED;
Count = 0;
}
}
}
// LED ON for 0.5 sec
// LED OFF for 0.5 sec
/* for external clock source, formula is following
Count = [Freq(Hz) x Tout(Sec)]/[Prescalar x (256-TMR0)]
// Freq(Hz) = 1000(1Khz) external clock
// Tout(Sec) = 1.0
// Prescalar = 2, the other options are:
// 1:2
// 1:4
// 1:8
// 1:16
// 1:32
// 1:64
// 1:128
// 1:256
// TMR0 = 6
// Count = 2 numeric value to be placed to obtain the 0.5 Sec delay
*/
// direction signal
sbit LED_dir at TRISB.B1;
// bit labels portb
sbit LED at PORTB.B1;
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer0 configration
TMR0 = 6; // timer0 register init
OPTION_REG.T0CS = 1; // external clock on select
OPTION_REG.T0SE = 0; // Low to High Edge
OPTION_REG.PSA = 0; // prescaler is assigned to the Timer0 module
OPTION_REG.PS0 = 0; //———————-
OPTION_REG.PS1 = 0; // prescalar 2 select
OPTION_REG.PS2 = 0; //———————-
while(1)
{
while(INTCON.T0IF == 0); // wait until T0IF = 1
INTCON.T0IF = 0; // reset T0IF = 0
TMR0 = 6; // timer0 register reset
Count++;
if (Count == 2)
{
LED = ~LED;
Count = 0;
}
}
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment