loading

Atmega168 Interrupt help

I'm trying to write code so I get an interrupt on an atmega168 when timer0 overflows. Right now I've got it set up so it blinks an LED every 8th interrupt(~1 second @16mHz /w div 8 prescaler I think), but it doesn't work, so this is where I came. Here's the code:

#include <avr/io.h>
#include <avr/interrupt.h>
volatile int flag=0;

ISR(TIMER0_OVF_vect)
{
flag+=1;
if(flag>=8){
flag=0;
PORTB = (1<<0);
}
}

int main(void){
TCCR0A=0b00000000;
TCCR0B=0b00000010;
TIMSK0 |= (1<<OCIE0A);
TCNT0=0;
sei();
DDRC=0b00111100;
DDRB |= (1<<0);
PORTB |= (1<<0);
while(1){

} //End while loop
return 0;
} //End Main

First of all, if you are running the ATmega68 at 16Mhz with the default configuration fuse settings, the clock to the Timer0 prescaler will be 2Mhz and with a prescaler value of 8 will give you a 250Khz rate into Timer0 and an overflow interrupt rate of 976.5625Hz (it overflows every 256 clocks). Therefore, to get an about 1 second rate, you'll have to use 976 for your 'flag' counter in the ISR. (<em>If you have cleared the CLKDIV8 fuse in the Fuse Low configuration fuses, everything will be running 8 times faster.</em>)<br /><br />Secondly, to enable the Timer0 overflow interrupt, you need to <strong>set </strong>the <strong>TOIE0 </strong>bit in the TIMSK0 register, <strong>NOT </strong>the OCIE0A bit.<br /><br />Finally, and more importantly, you appear to have your LED connected to PB0, but in your ISR, you are always <strong>only setting that pin</strong>, when I think you want to be toggling it (or alternately setting and clearing it)! There's more than one way to toggle a port pin, but the easiest is to do: <br /><strong> PINB |= (1 << 0);</strong><br />Note the use of <strong>PINB </strong>instead of <strong>PORTB </strong>- see the section in the datasheet under I/O-Ports / Ports as General Digital I/O / Toggling the Pin. (<em>It's section <strong>11.2.2 </strong>in the manual I have</em>.)<br />
Not my processor family, but do AVRs reset the interrupt service flag on entry to the ISR ? COMMENT your code !
geeklord (author)  steveastrouk7 years ago
i don't know if they do, but it doesn't sound like anything ive had to deal with..
Get the handbook for the chip. The AVRs are descendants of the 8052, and there are circumstances when their timers need flags manually resetting in ISRs