0
\$\begingroup\$

Hey I'm trying to do blinking led using interrupts on 16 bit timer. My atmega model is Atmega168A. Chip clock rate is 12Mhz.

Here is my code:

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

ISR(TIMER1_COMPA_vect)
{
    PORTC ^= (1 << PC5);
}

int main()
{

    DDRC |= (1 << PC5);

    PORTC |= (1 << PC5); //led on

    sei();

    TIMSK1 |= (1 <<  OCIE1A); // cmp interruupt enable
    TCCR1B |= (1 << CS12) | (1 << CS10); //prescalser 64
    OCR1A = 11718; // value to compare
    TCCR1A |= (1 << WGM12); // set ctc mode



    while(1)
    {

    }

    return 0;
}

When the program startup led turn on. After compare match it should turn off. And it works, but with one strange problem.

If I change OCR1A, only the first peroid of time before led on and off changes.

When I set OCR1A e.g 0x100 the led turns off very quickly.

When I set OCR1A e.g 0xfffa the led turns off slowly.

But only the first state change.

Another led blinks do not take over about changes of OCR1A.

Whats wrong?

Do I need reset some flags or something like this?

\$\endgroup\$
2
  • \$\begingroup\$ You're assuming the timer resets to zero when it reaches the compare value. It doesn't. \$\endgroup\$
    – brhans
    Jul 2, 2018 at 22:48
  • \$\begingroup\$ @brahans Hmmm I added TCNT1 = 0x00 in ISR and it works. But why? Does the TCNT1 shouldn't be cleared automaticly/ As the doc says: "The counter value (TCNT1) increases until a compare match occurs with either OCR1A or ICR1, and then TCNT1 is cleared." \$\endgroup\$
    – bielu000
    Jul 3, 2018 at 4:06

1 Answer 1

1
\$\begingroup\$

You did not set CTC mode, WGM12 is in TCCR1B

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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