Avr Timer Interrupts in C
Avr Timer Interrupts in C
Timer interrupts are an excellent way of having your AVR do something at a given interval. They
can fire off and interrupt what ever else the AVR is doing making for very precise timing. They
are one of the best ways to implement custom waveforms for things such as positioning robot
servos, dimming LEDs, and driving speakers at different frequencies.
#include <avr/interrupt.h>
// ********************************************************************************
// Interrupt Routines
// ********************************************************************************
// timer1 overflow
ISR(TIMER1_OVF_vect) {
// XOR PORTA with 0x02 to toggle the LSB
PORTA=PORTA ^ 0x01;
TCNT1=65536-7813;
}
// timer0 overflow
ISR(TIMER0_OVF_vect) {
// XOR PORTA with 0x01 to toggle the second bit up
PORTA=PORTA ^ 0x04;
TCNT0=256-78;
// ********************************************************************************
// Main
// ********************************************************************************
int main( void ) {
// Configure PORTA as output
DDRA = 0xFF;
PORTA = 0xFF;
// enable timer overflow interrupt for both Timer0 and Timer1
TIMSK=(1<<TOIE0) | (1<<TOIE1);
// set timer0 counter initial value to 0
TCNT1=65536-(7813);
TCNT0=256-78;
TIFR= (1<<TOV0)|(1<<TOV1);
// start timer0 with /1024 prescaler
TCCR0 = (1<<CS02) | (1<<CS00);
// lets turn on 16 bit timer1 also with /1024
TCCR1B = (1 << CS10) | (1 << CS12);
// enable interrupts
sei();
while(1) {
}
}