Timer 0 of PIC16F877A could operate in timer mode, or counter mode. In timer mode, it can create timing delay, measuring the period of external event, etc. In counter mode, it can store the number of pulse enter its clock in pin.
Experiment on breadboard |
In this example, I will use this timer 0 to operate in timer mode. It's use to create a timing delay that generate an output frequency of 1
Hz, blinking an output LED. The LED toggles for every 500 mS.
I clear the TMR0 Clock Source Select bit (T0CS), allowing it to operate in timer mode. The Prescaler Assignment bit (PSA) is clear, forcing the prescaler to TMR0 rate at maximum delay. Then the Prescaler Rate Select bits are assigned to "111". So the prescaler is 1:256.
The micro-controller clock frequency is 20 MHz. The instruction frequency is 1/20 MHz = 5 MHz. Hence the final period is 1/5 MHz = 200 nano-seconds.
With the prescaler of 1:256, then the timer 0 clock rate is 256 * 200 nano-seconds = 51.2 micro-seconds.
I will need to create a variable that count the timer rate up to 10 micro-seconds. Because the TMR0 is only 8-bit (256 values in total).
cnt = (10 milliseconds)/(51.2 micro-seconds) = (10 milliseconds)/(0.0512 milliseconds)
cnt = 195 counts.
So, the cnt is needed to increase 50 times more to make a 500 mS delay time.
Source Code:
/* * PIC16F887 Timer 0 programming */ #include <xc.h> #include "config.h" #define LED RB0 int main(void){ unsigned int cnt=0; PORTB=0x00; TRISB0=0; //select internal instruction cycle clock T0CS=0; //Select timer 0 prescaler PSA=0; //select 1:256 prescaler OPTION_REGbits.PS=0x07; TMR0=0; while(1){ if(TMR0>=200){ cnt++; TMR0=0; } if(cnt>=50){ LED^=1; cnt=0; } } }
Schematic: