How to Program Timer-0 in PIC16F877A (Internal Clock)
The following code demonstrate how to use timer-0 for clock generation or precise time delay. In this example internal clock 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 internal crystal as clock source, formula is following
Count = [Fosc(Hz) x Tout(Sec)]/[4 x Prescalar x (256-TMR0)]
// Fosc(Hz) = 8000000(8Mhz) crystal frequency
// Tout(Sec) = 0.5 sec
// Prescalar = 256, the other options are:
// 1:2
// 1:4
// 1:8
// 1:16
// 1:32
// 1:64
// 1:128
// 1:256
// TMR0 = 0
// Count = 15.25 ~ 15 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;
// function proto-type
void T0Config(void);
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer0 configration
T0Config();
while(1)
{
while(INTCON.T0IF == 0); // wait until T0IF = 1
INTCON.T0IF = 0; // reset T0IF = 0
Count++;
if (Count == 15)
{
LED = ~LED;
Count = 0;
}
}
}
void T0Config(void)
{
TMR0 = 0; // timer0 register init
OPTION_REG.T0CS = 0; // internal clock select
OPTION_REG.T0SE = 0; // Low to High Edge
OPTION_REG.PSA = 0; // prescaler is assigned to the Timer0 module
OPTION_REG.PS0 = 1; //———————-
OPTION_REG.PS1 = 1; // prescalar 256 select
OPTION_REG.PS2 = 1; //———————-
}
// LED ON for 0.5 sec
// LED OFF for 0.5 sec
/* for internal crystal as clock source, formula is following
Count = [Fosc(Hz) x Tout(Sec)]/[4 x Prescalar x (256-TMR0)]
// Fosc(Hz) = 8000000(8Mhz) crystal frequency
// Tout(Sec) = 0.5 sec
// Prescalar = 256, the other options are:
// 1:2
// 1:4
// 1:8
// 1:16
// 1:32
// 1:64
// 1:128
// 1:256
// TMR0 = 0
// Count = 15.25 ~ 15 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;
// function proto-type
void T0Config(void);
void main(void)
{
int Count = 0;
// set direction as output
LED_dir = 0;
// init LED
LED = 0;
// timer0 configration
T0Config();
while(1)
{
while(INTCON.T0IF == 0); // wait until T0IF = 1
INTCON.T0IF = 0; // reset T0IF = 0
Count++;
if (Count == 15)
{
LED = ~LED;
Count = 0;
}
}
}
void T0Config(void)
{
TMR0 = 0; // timer0 register init
OPTION_REG.T0CS = 0; // internal clock select
OPTION_REG.T0SE = 0; // Low to High Edge
OPTION_REG.PSA = 0; // prescaler is assigned to the Timer0 module
OPTION_REG.PS0 = 1; //———————-
OPTION_REG.PS1 = 1; // prescalar 256 select
OPTION_REG.PS2 = 1; //———————-
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment