I am using at ATMEGA8 with a 12 MHz external crystal oscillator.
The fuses were programmed as follows:
LFUSE 0xEF 1110 1111
HFUSE 0xC9 1100 1001
I was starting to set up a very basic timer application and I noticed that I was getting an unexpected frequency with the timer counter. (exactly half the expected frequency)
Here is the formula and example I am using to calculate for a 50 ms period (20Hz).
Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock Frequency) - 1
= (1 / 20) / (1 / 12000000) - 1
= .05 / 0.00000008333333333 - 1
= 600000 - 1
= 599999
/64 (using /64 prescaler to accomodate the 16-bit timer range)
= 9374.984375
So if I use 9374 as the count in a simple program like this:
Code:
#include <avr/io.h>
int main(void)
{
DDRC |= (1 << PC4); // PC4 is digital output
TCCR1B |= (1 << CS10) | (1 << CS11); // Set up 16-bit timer1 (CS10=1, CS11=1, CS12=0) /64 prescaler
while (1)
{
if (TCNT1 >= 9374) // max count is 65535 for 16-bit timer
{
PORTC ^= (1 << PC4); // toggle output pin
TCNT1 = 0; // Reset timer value
}
}
return (0);
}
The resulting output frequency is 10Hz (100ms period) instead of the expected 20Hz (50ms period).
If I use 4687 (half 9374), I get my 20Hz but I am not sure why the timer is running at half the CPU frequency.
Am I wrong to expect the ATMEGA8 to provide a CPU CLOCK / 64 Frequency to Timer1 the way I have it configured?
- - - Updated - - -
Oops.
It was a misread on the oscilloscope. It was indicating total period and not positive pulse width.
That means it is working as expected.
Thank you and sorry for the interruption.