How to Program Timer-1 as Counter in PIC16F877A
The following code demonstrate how to use timer-1 as counter. The counting pulses are applied on T1CKl pin. 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.
Note: According to datasheet, if T1CKl is default high, then counting start from first rising edge else if T1CKl is default low then counting start from second rising edge.
Code in mikroC
// function pro-type
void T1CounterConfig(void);
void main(void)
{
TRISB = 0x00; // make as output
TRISD = 0x00; // make as output
PORTB = 0x00; // init 0x00
PORTD = 0x00; // init 0x00
// timer1 as counter configration
T1CounterConfig();
while(1)
{
PORTD = TMR1H;
PORTB = TMR1L;
}
}
void T1CounterConfig(void)
{
TMR1H = 0x00; // init higher byte
TMR1L = 0x00; // init lower byte
T1CON.T1CKPS1 = 0; // 1:1 prescale value
T1CON.T1CKPS0 = 0; // 1:1 prescale value
T1CON.T1OSCEN = 0; // Oscillator is shut-off
T1CON.T1SYNC = 1; // Do not synchronize external clock input
T1CON.TMR1CS = 1; // External clock from pin T1CKI (on the rising edge)
T1CON.TMR1ON = 1; // Enables Timer1
}
void T1CounterConfig(void);
void main(void)
{
TRISB = 0x00; // make as output
TRISD = 0x00; // make as output
PORTB = 0x00; // init 0x00
PORTD = 0x00; // init 0x00
// timer1 as counter configration
T1CounterConfig();
while(1)
{
PORTD = TMR1H;
PORTB = TMR1L;
}
}
void T1CounterConfig(void)
{
TMR1H = 0x00; // init higher byte
TMR1L = 0x00; // init lower byte
T1CON.T1CKPS1 = 0; // 1:1 prescale value
T1CON.T1CKPS0 = 0; // 1:1 prescale value
T1CON.T1OSCEN = 0; // Oscillator is shut-off
T1CON.T1SYNC = 1; // Do not synchronize external clock input
T1CON.TMR1CS = 1; // External clock from pin T1CKI (on the rising edge)
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