Hello Guys;
Happy to see you back again, to check how to program timer.
We need to do some mathematical calculation to configure the timer. Lets see how.
Clock Source : 20MHZ.
so FCPU = Clock/4 (20Mhz/4)
FCUP = 5MHZ.
Time Period= 1/FCPU (1/5MHZ)
Time Period = 0.2uS.
Prescaler = 256.
Prescaler Period = 0.2us * 256
Prescaler Period= 51.2us
Overflow Period = 51.2us * 256 = 13107.2us
Overflow Period = 0.013107 S
For 1 Sec time delay we need 1/0.013107
1 Sec = 76.29 Overflow.
The best way to understand the working of timer is Led Blinking. We are going to program to blink a led every 1Sec (76 Overflow).
Registers Configuration:
T0CON is Timer0 register. we need to configure it according to our calculation.
Prescaler: Bit 0 to 2 are prescaler selection. we need to configure according to table.
T0PS0=1; //Prescaler is divide by 256
T0PS1=1;
T0PS2=1;
PSA: we need to low this bit, so that it will take prescaler select bit.
PSA=0; //Timer Clock Source is from Prescaler
T0CS: Timer source select bit.
T0CS=0; //Prescaler gets clock from FCPU (5MHz)
T08BIT: To make timer work in 8 Bit mode or 16 Bit mode.
T08BIT=1; //8 BIT MODE
TMR0ON: Timer0 ON/OFF Bit
TMR0ON=1; //Now start the timer!

Now we need to configure the Timer interrupt,
Timer0 Interrupt:
TMR0IE=1; //Enable TIMER0 Interrupt
Peripheral Interrupt:
PEIE=1; //Enable Peripheral Interrupt
Global Interrupt:
GIE=1; //Enable INTs globally
We have successfully configured the timer. lets built and test drive it.
SOURCE CODE:
#include <htc.h>
// PIC 18F4550 fuse configuration:
// Config word 1 (Oscillator configuration)
// 20Mhz crystal input scaled to 48Mhz and configured for USB operation
__CONFIG(1, USBPLL & IESODIS & FCMDIS & HSPLL & CPUDIV1 & PLLDIV5);
// Config word 2
__CONFIG(2, VREGEN & PWRTDIS & BOREN & BORV20 & WDTDIS & WDTPS32K);
// Config word 3
__CONFIG(3, PBDIGITAL & LPT1DIS & MCLREN);
// Config word 4
__CONFIG(4, XINSTDIS & STVREN & LVPDIS & ICPORTDIS & DEBUGDIS);
// Config word 5, 6 and 7 (protection configuration)
__CONFIG(5, UNPROTECT);
__CONFIG(6, UNPROTECT);
__CONFIG(7, UNPROTECT);
unsigned char counter=0;//Overflow counter
void main()
{
//Setup Timer0
T0PS0=1; //Prescaler is divide by 256
T0PS1=1;
T0PS2=1;
PSA=0; //Timer Clock Source is from Prescaler
T0CS=0; //Prescaler gets clock from FCPU (5MHz)
T08BIT=1; //8 BIT MODE
TMR0IE=1; //Enable TIMER0 Interrupt
PEIE=1; //Enable Peripheral Interrupt
GIE=1; //Enable INTs globally
TMR0ON=1; //Now start the timer!
//Set RC1 as output because we have LED on it
TRISC=TRISC&0C11111101;
while(1);
}
void interrupt ISR()
{
//Check if it is TMR0 Overflow ISR
if(TMR0IE && TMR0IF)
{
//TMR0 Overflow ISR
counter++; //Increment Over Flow Counter
if(counter==76)
{
//Toggle RB1 (LED)
if(RC1==0)
RC1=1;
else
RC1=0;
counter=0; //Reset Counter
}
//Clear Flag
TMR0IF=0;
}
}
You can download Project Here