1
\$\begingroup\$

I want to toggle the LED3 of the microcontroller when the button SW0 is pressed. I developed this code but it is not working and I dont know what is wrong. I search in the documentation and many foros trying to find the error but I still dont know what is wrong. I think the problem is in the confguration of the interrupt, but I am not sure about this.Can someone help me? Thank you.

int main(){
    EIMSK = 1<<INT0;                    // Enable INT0
    EIFR = (1 << INT0);
    MCUCR |= 1<<ISC01 | 1<<ISC00;   // Trigger INT0 on rising edge
    DDRB = 0x04;//Set port B LED3 as output the other pins as input
    PORTB = 0x04; //Pin3 that is output/led turn off, input pull up

    DDRD &= ~(1<<PIND2); // Set PD2 as output (Used for interrupt INT0)
    PORTD = 1<<PIND2; // Enable PD2 pull-up resistor

    sei();  //Set global interrupt flag, to allow SW0 interrupts

    while(1) {}; //Infinite loop to wait for the interrupt
    return 0; 
}

ISR(INT0_vect) {
    PORTB ^= 1 << 3; //toggle LED3
}
\$\endgroup\$
2
  • \$\begingroup\$ If the LED is on pin 3 of PORTB according to PORTB ^= 1 << 3, which is 0x8 then DDRB = 0x04; is wrong. \$\endgroup\$ Commented Nov 17, 2016 at 19:14
  • \$\begingroup\$ That it is true, should be PORTB ^= 1 << 2 \$\endgroup\$ Commented Nov 23, 2016 at 12:47

3 Answers 3

1
\$\begingroup\$

main() configures bit 2, but the ISR frobs bit 3. Be consistent.

DDRB |= _BV(PB3);
PORTB |= _BV(PB3);
 ...
PORTB ^= _BV(PB3); // or PINB |= _BV(PB3);
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I must have missed Frobs in education during my working days in silicon valley, nice term for random manipulation as opposed to tweak, which is careful \$\endgroup\$
    – D.A.S.
    Commented Nov 17, 2016 at 19:18
1
\$\begingroup\$

I suggest to define your pins like:

#define LED3      PB3

#define SW0       PD2

and in the rest of your code, use them whenever you handle anything related to those pins.

DDRB |= (1<<LED3);        
PORTB |= (1<<LED3); 

ISR(INT0_vect) {
    PORTB ^= (1<<LED3);
}
\$\endgroup\$
1
\$\begingroup\$

I found the solution, the problem was that it is not possible to use an external interrupt to now when button SW0 is pressed in atmega1284P. It is necessary to use the pin change interrupt PCINT1_vect.

\$\endgroup\$

Your Answer

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

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