Actions

AVR timer interrupts

From Just in Time

Summary "howto" setup timer interrupts on AVR

Registers

TCNTx
is the timer counter itself. It's both readable and writeable. The counter starts as soon as prescale value is written to the CSxn (e.g. CS10 to CS12) bits, which are located in TCCRxB. Possible prescale values are:
CS12 CS11 CS10 description
0 0 0 No clock source (Timer/Counter stopped).
0 0 1 clk/1 (No prescaling)
0 1 0 clk/8 (From prescaler)
0 1 1 clk/64 (From prescaler)
1 0 0 clk/256 (From prescaler)
1 0 1 clk/1024 (From prescaler)
1 1 0 External clock source on T1 pin. Clock on falling edge.
1 1 1 External clock source on T1 pin. Clock on rising edge.
OCRxA
(output compare register). As soon as the timer reaches a value that is in this register, the appropriate bit in TIFR is set. This bit is set if the timer runs in CTC-mode, which can be switched on by setting WGMx0-WGMx3 to 0100 (setting WGMx2 to 1).
TIMSK
Set the appropriate bit (OCIExA) to enable timer interrupts.

Interrupt vector

The interrupt vector for timer 1 A is TIMER1_COMPA_vect.

Example

<source lang="c"> int main(void) {

   ioinit();
   OCR1A = 499;
   // Set up timer, prescaler = 8 (CS)
   // and set the timer in CTC mode (WGM)
   TCCR1B |= _BV(CS11) | _BV(WGM12); 
   // enable the timer interrupt
   TIMSK |= _BV(OCIE1A);
   // enable interrupts in general
   sei();
   // do other stuff...
   return 0;

}

ISR( TIMER1_COMPA_vect) {

  // do stuff

}

</source>