Skip to content

Instantly share code, notes, and snippets.

@mkleemann
Created January 2, 2012 20:49
Show Gist options
  • Save mkleemann/1552057 to your computer and use it in GitHub Desktop.
Save mkleemann/1552057 to your computer and use it in GitHub Desktop.
atmega8 timer2 - use CTC/output compare interrupt w/o usage of OC2 pin
// All values/comments are valid with ATmega8 running at Fosc = 4.000MHz
#include <avr/io.h>
#include <avr/interrupt.h>
// TIMER2 with prescaler clkT2S/1024
#define TIMER2_PRESCALER (1 << CS22) | (1 << CS21) | (1 << CS20)
// TIMER2 output compare value
// --> value 98 is 25.088ms (4MHz@1024 prescale factor)
#define TIMER2_COMPARE_VALUE 98
void main()
{
// ... do something ...
// init Timer2
TIMSK |= (1 << OCIE2); // set output compare interrupt enable
TCCR2 |= (1 << WGM21) | TIMER2_PRESCALER; // set CTC mode
OCR2 = TIMER2_COMPARE_VALUE; // set compare value for interrupt
sei(); // global interrupt enable
// ... do something ...
while (1)
{
// ... do something ...
} /* end of while(1) */
}
// *** Interrupt Service Routine *****************************************
// Timer2 compare match interrupt handler
// --> set as 25ms
ISR(TIMER2_COMP_vect)
{
// handle interrupt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment