Skip to content

Instantly share code, notes, and snippets.

@mkleemann
Created January 2, 2012 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkleemann/1552059 to your computer and use it in GitHub Desktop.
Save mkleemann/1552059 to your computer and use it in GitHub Desktop.
atmega8 timer1 - use 16-bit compare with ICR (input capture interrupt) for long periods of time
// All values/comments are valid with ATmega8 running at Fosc = 4.000MHz
#include <avr/io.h>
#include <avr/interrupt.h>
// TIMER1 with prescaler clkI/O/1024
#define TIMER1_PRESCALER (1 << CS12) | (1 << CS10)
// ~15s (4MHz@1024 prescale value)
#define TIMER1_COMPARE_VALUE 0xE4E1
void main()
{
// ... do something ...
// init Timer1
// use Fast PWM and ICR for compare mode (14) to get long periods
TIMSK |= (1 << TICIE1); // set input capture interrupt enable
TCCR1A |= (1 << WGM11); // set Fast PWM mode with ICR1 as compare register
TCCR1B |= (1 << WGM13) | (1 << WGM12) | TIMER1_PRESCALER; // set Fast PWM mode with ICR1 as compare register
ICR1H = (TIMER1_COMPARE_VALUE >> 8); // set compare value for interrupt
ICR1L = (TIMER1_COMPARE_VALUE & 0xFF); // set compare value for interrupt
sei(); // global interrupt enable
// ... do something ...
while (1)
{
// ... do something ...
} /* end of while(1) */
}
// *** Interrupt Service Routine *****************************************
// Timer1 input capture interrupt (~15s 4MHz@1024 prescale factor)
ISR(TIMER1_CAPT_vect)
{
// handle interrupt
}
@vahidn2
Copy link

vahidn2 commented Dec 31, 2020

Thankful
that was perfect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment