0
\$\begingroup\$

I am trying some simple programs to test my microcontroller, but I am having trouble with the first test program: blinking an LED using interrupts.

I'm using an Atmega168A-PU.

Here is my program:

#include <avr/io.h>

    #include <avr/delay.h>
    #include <avr/interrupt.h>

  //ISR(TIMER0_OVF) -> this syntax also not works
    ISR(TIMER0_OVF_vect)
    {
        PORTB ^= (1 << PB1);
    }

    int main(void)
    {
        DDRB |= (1 << PB1); // set PB1 as output
        PORTB |= (1 << PB1); // led on
        TIMSK0 |= (1 << TOIE0); // enable timer overflow interrupt
        TCCR0B |= (1 << CS00) | (1 << CS02);  //set prescaler to 1024

        sei();
        while(1)
        {

        }

        return 0;
    }

All of the connections are good, but the LED won't blink.

\$\endgroup\$
1
\$\begingroup\$

You are using 8-bit TC. It overflows at 255, which even with 1024 prescaler is too fast to see any blinking.

Also, check the generated code. I've seen reports of some older versions of compilers "optimizing" away infinite loops like that.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I can't agree with you. In my older version of atmega(16a), the same code worked good. Atmega168a has 8Mhz processor clock speed which can be divided by 8(CKDIV8). 1Mhz / 1024 = ~ 976. 1 / 976 = 0,00102 which is 1.02 ms per each counter update. Counter counts to 255, so each ovf interrupt occures every after 256ms. 256ms * 4 = 1024ms which is ~ 1 second. It gaves 4 state changes per second. I think it should can be seen by the human eye. \$\endgroup\$ – bielu000 Jul 1 '18 at 5:25
  • \$\begingroup\$ Does your LED stay ON all the time? \$\endgroup\$ – Maple Jul 1 '18 at 7:30
  • \$\begingroup\$ Yes. The same code adjusted to Atmega16 works good. \$\endgroup\$ – bielu000 Jul 1 '18 at 7:33
  • \$\begingroup\$ Try replacing |= with = for TIMSK0 and TCCR0B and set TCCR0A = 0 \$\endgroup\$ – Maple Jul 1 '18 at 7:34
  • \$\begingroup\$ I changed, but nothing happen. I can make led blinking but using delay_ms(...) in main loop but it doesn't satisfy me. \$\endgroup\$ – bielu000 Jul 1 '18 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.