Athul
Athul

Reputation: 449

AVR CTC mode: Output Compare B Match Interrupt Not working

I am learning AVR programming using a book named" Make: AVR programming". I was trying to understand Timer peripheral. What following program does is toggling a pin at a certain interval using interrupt

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

// initialize timer, interrupt and variable
void timer1_init()
{
    // set up timer with prescaler = 64 and CTC mode
    TCCR1B |= (1 << WGM12)|(1 << CS11)|(1 << CS10);

    TIMSK1 |= (1 << OCIE1B);        // Output Compare B Match Interrupt Enable
    // initialize counter
    TCNT1 = 0;

    // initialize compare value
    OCR1B = 7812;
    sei();
}


ISR(TIMER1_COMPB_vect) { 
    PORTC ^= (1 << 0);
}

int main(void)
{
    // connect led to pin PC0
    DDRC = 0XFF;

    // initialize timer
    timer1_init();

    // loop forever
    while(1)
    {

    }
}

But it's not toggling the pin, Why?

Upvotes: 0

Views: 1038

Answers (1)

vlad_tepesch
vlad_tepesch

Reputation: 6883

Which micro controller do you use?

One problem i can spot is the missing initialization of the OCR1A that sets the top of the counter so your counter does never count up to your compare value because by default OCR1A is zero.

So maybe you should write to OCR1A instead of OCR1B.

one tip:
the newer avr-cores support pin-toggeling by a simple write to the pin-register (look at data sheets the I/O-Ports section). this saves some cycles for the read and the xor. So PORTC ^= (1 << 0); is equivalent to PINC = (1<<0);

Upvotes: 1

Related Questions