0

I want to cause the external interrupt on digital pin 2 (PD2 on ATmega328). I have chosen any logic change mode. Here is my code:

void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}


ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

Here is how I connect things.

NOTE: I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

enter image description here

The problem is when I push the button no interrupt occurs. What am I doing wrong?

  • 2
    If the button isn't pressed, the pin is floating, reacting to all electrical things near it. You habe to usw the resistor as pullup or pulldown. That might be the problem. Google pullup resistor and find a tutorial about it – chrisl Feb 28 '18 at 8:24
  • As I know ATmega328 already has pull-up resistors. That is why I turn it on by specifying appropriate bit in PORTD register. – LRDPRDX Feb 28 '18 at 8:45
  • 2
    But your fritzing shows, that the button is connected to 3.3V, not to ground. And when you are using the internal pullup, you don't need another resistor – chrisl Feb 28 '18 at 8:50
  • And your code doesn't compile, because in the ISR you try writing to register PIND5, which is only a pin, not a register. You have to write to PIND. Also in your last statement you have an extra parenthesis. – chrisl Feb 28 '18 at 9:25
  • The setup function is only run once. You get no speed gain by writing directly to registers in the setup function. The gcc compiler has "_BV()" and Arduino has "bit()" to select a bit. You don't use both. The Arduino also enables the global interrupt. You can make it yourself easier with the Arduino functions, and only optimize the ISR if you have to. – Jot Feb 28 '18 at 9:27
1

Pin 2 is pulled up by internal R then pulled up when button is pressed? Connect button to GND.

  • OMG. I did not understand correctly what pull-up means. Thank you all. Now it works. – LRDPRDX Feb 28 '18 at 11:42

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.