accurate interrupt timer at 60hz

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.

I've also tried several different manual load values for TCNT2 ( 257 - 130 or 256 - 130 ) as suggested by the uC hobby article on interrupt timers, http://www.uchobby.com/index.php/2007/11/24/arduino-interrupts/ again with no luck.

Any tips appreciated, sample code (including shameless hacks from uC hobby ) is here:

http://code.google.com/p/vf-inputs/source/browse/trunk/hardware/libraries/VF_int/VF_int.cpp

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

Thanks! For some reason I had thought all of the timers were 8-bit. It’s rock solid 60hz now.

For others who may happen across this post,

http://www.arduino.cc/playground/Code/PCMAudio

has good sample code for timer1