I have written some code to calculate the time/frequency of a series of evenly space pulses received in pin RB4. I am using the EasyPic5 dev board with a 16F887 chip.
Every time a pulse is received the current value of the 16bit timer1 is displayed across PORTC and PORTD LEDs (PORTC displaying the highest 8 bits, PORTD displaying the lowest 8 bits)
I am using a burst generator to produce 4 square waves at a frequency of 100Hz.
When I convert the value of timer1 into a frequency I get a result of 50Hz.
Here is my code:
Code: Select all
unsigned short temp;
void interrupt()
{
if (INTCON.RBIF==1)
{
temp = PORTB; //clear mismatch
INTCON.RBIF = 0; // clear flag
if (Button(&PORTB, 4, 20, 1))
{
PORTD = TMR1L;
PORTC = TMR1H;
}
}
PIR1.TMR1IF = 0; // clear TMR1IF
TMR1H = 0;
TMR1L = 0;
}
void main()
{
ANSEL = 0; // Configure AN pins as digital I/O
ANSELH = 0;
PORTD = 0;
TRISD =0;
PORTC = 0;
TRISC = 0;
PORTB = 0;
T1CON = 1; // Timer1 settings
PIR1.TMR1IF = 0; // clear TMR1IF
TMR1H = 0; // Initialize Timer1 register
TMR1L = 0;
PIE1.TMR1IE = 1; // enable Timer1 interrupt
TRISB = 0b00110000;
IOCB = 0b00110000;
INTCON = 0xC8;
T1CON = 0x45;
do
{
}
} while (1);
}
1001110111001000 which equals 40392
The chip runs at 8Mhz, divided by 4 = 2Mhz
1 / 2000000 = 0.0000005 seconds per count
40392 * 0.0000005 = 0.020196
Freq = 1 / 0.02 = 50Hz
Where am I going wrong?
After writing this I notice that I am using the Button function to pick up on the pin interrupt and have a debounce of 20 - maybe this is affecting it?
Thanks for any guidance,
Jimbo