The Arduino UNO has three timers
Timer0 - An 8 bit timer used by Arduino functions delay(), millis() and micros().
Timer1 - A 16 bit timer used by the Servo() library
Timer2 - An 8 bit timer used by the Tone() library
Timer interrupt driven program
This interrupt example is like the basic LED flash program, but instead of using delays it uses an interrupt every half second to turn the LED on and then off, so the LED flashes once per second.
/*
Example Timer1 Interrupt
Flash LED every second
*/
#define ledPin 13
int timer1_counter;
void setup()
{
pinMode(ledPin, OUTPUT);
// initialize timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
// Set timer1_counter to the correct value for our interrupt interval
//timer1_counter = 64911; // preload timer 65536-16MHz/256/100Hz
//timer1_counter = 64286; // preload timer 65536-16MHz/256/50Hz
timer1_counter = 34286; // preload timer 65536-16MHz/256/2Hz
TCNT1 = timer1_counter; // preload timer
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER1_OVF_vect) // interrupt service routine
{
TCNT1 = timer1_counter; // preload timer
digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
}
void loop()
{
// your main program goes here...
}