I'm having some trouble getting an interrupt to fire at exactly 60hz (delay of .016_ seconds between interrupts).
With a 1024 prescale, 60hz would require 260 timer ticks; so I'm using 130 ticks / 120hz and waiting for 2 interrupts at a time.
The frequency still isn't exact; I'm assuming part of this is rounding error (should actually be 16mhz / 1024 / 120 = 130.2083_ ticks ).
I've tried accounting for rounding error by putting in a manual additional delayMicroseconds(13) in the interrupt handler before reloading TCNT2, but no luck - still drops at least the equivalent of 1/60th every 2 seconds or so.
You can get a much more accurate count if you use timer1. Its a 16 bit counter and if you use a prescale of 8 your count can be within half a microsecond.
here is the code to set the mode and prescale
TCCR1A = 0x00; // Normal mode, => Disconnect Pin OC1 PWM Operation disabled
TCCR1B = 0x02; // 16MHz clock with prescaler, TCNT1 increments every .5 uS (cs11 bit set)
You will need to set the output compare register as requred for 60 hz.
OCR1A = 33333 // = 16666 microseconds (each count is .5 us)
and you will need to impliment the interrupt service routine for Timer1 output compare on register A
ISR(TIMER1_COMPA_vect) {
// your code here
}
and enable the interrupt:
TIMSK1 = ??? I can't remember the value for this, check the datasheet