Setting up Timers

The first step in getting the AVR-MT-128 to do something useful Vespa-wize is to get a timer happening. Everything we want to do (for now) is time based and first on the agenda is measuring speed from a magnetic pick-up. So we want a timer that gives us seconds to start with.

A combination of reading the manual and the Newbie's Guide to AVR Timers gives me the following successful code. We are using CTC to enable us to check for the timeout via a timeout register (TIFR). We "prescale" down the timer 1 from 16Mhz to 16Mhz/1024 and set the compare value (OCR1A) to 1 second (15625 which is how many ticks per second in 16Mhz/1024)...

int main(void) {    

 //Ports

 InitPorts();

 TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode

 TCCR1B |= ((1 << CS22) | (1 << CS20)); // Start timer at Fcpu/1024 

 OCR1A   = 15625; // Set CTC compare value to 1Hz at 16MHz AVR clock, with a prescaler of 1024

...

 if (TIFR & (1 << OCF1A)) 

 { 

 // do some calc on second tick   

 TIFR = (1 << OCF1A); // clear the CTC flag (writing a logic one to the set flag clears it) 

 }