Search code examples
interruptavravr-gcc

AVR C won't run interrupt


I'm fiddling with my MEGA-1284p kit and avr studio and I'm in need of some help solving a problem. I need it to toggle LED3 on button press SW0.

Here is the AVR C code:

#define F_CPU 11059200UL // The Xplained kit runs at 11.0592 MHz

#include <stdio.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

int ex37() {

    DDRB = 0x04;// LED3 as output
    PORTB = 0x04; //LED3 off    

    EIMSK |= (1<<INT0) | (0<<INT1) | (0<<INT2); // Enable external interrupt 0 (SW0)
    MCUCR |= (1<<ISC01) | (1<<ISC00); // INT0 on rising edge.

    sei(); // Start interrupts

    _delay_ms(1000); //wait 1000 ms = 1 sec
    PORTB = 0x00; //LED3 on
    _delay_ms(1000); //wait 1000 ms = 1 sec
    PORTB = 0x04; //LED3 off

    while(1) {  
    };
    return 0;
}
ISR(INT0_vect) {
    _delay_ms(1000); //wait 1000 ms = 1 sec
    if (PORTB == 0x04){
        PORTB = 0x00;
    } else {
        PORTB = 0x04;
    }
}

But the function to change the LED3 never gets called for as far as I can tell.


Solution

  • SW0 is connected to PB0, which is not the pin that any of the external interrupts are active on.

    Instead, you need to use a pin change interrupt, PCIE1 and configure it properly. See datasheet for the register descriptions.