I've been experimenting with timers as well, but I couldn't get the above code to work. The reason: the code is for the Atmega8, while new Arduino boards come with a Arduino168. Slight difference.
To prevent other people who use the search to step into the same pitfall, here's the minimalistic code I came up with:
Code:#include <avr/interrupt.h>
#include <avr/io.h>
//Timer2 overflow interrupt vector handler, called (16,000,000/256)/256 times per second
ISR(TIMER2_OVF_vect) {
//let 10 indicates interrupt fired
digitalWrite(10,true);
};
void setup() {
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
//Timer2 Settings: Timer Prescaler /256, WGM mode 0
TCCR2A = 0;
TCCR2B = 1<<CS22 | 1<<CS21;
//Timer2 Overflow Interrupt Enable
TIMSK2 = 1<<TOIE2;
//reset timer
TCNT2 = 0;
//led 9 indicate ready
digitalWrite(9,true);
}
void loop() {
}
This is for the Atmega168-arduino's! And for the record: I'm using Arduino IDE v0008, and firmware v1.15.
When run, a led (or whatever) connected on pin 9 lights directly after initalisation. When the timer fires, led 10 lights up. The timer is repetitive, it keeps firing.
I'm aware of the FrequencyTimer2 lib, but this code is a bit more compact and doesn't use the PWM-mode. People who need to generate a pulse/clock on the output should definately have a look at the FT2-lib.