The following lines which works exactly opposite to what i'm expecting, would appreciate correcting my understaing:

Button connected with Pin D2 & Led B2:

    if (PIND & (1 << PD2) ) 
        (PORTB ^= (1 << PB2));
        PORTB |= (1 << PB2);

As far as i understand so far: when Button pressed [PD2 will high value (1)] which when and'd with the mask (wich is another 1 in location of PD2) then we should get true for the if condition and the LED will keep switching based on the delay value specified. HOWEVER, what i get is the exact opposite: as lonh as i'm pressing the button Led goes constantly one, when no button pressed the switching behavior occurs.

i'm kind of lost where i'm wrong

  • 4
    \$\begingroup\$ Welcome to EE.SE Mo - can you put up a schematic as well? It could be as simple as reversed connection, or something similar. Also, could you post the setup code for your PORT (DDR etc). \$\endgroup\$
    – awjlogan
    Commented Oct 28, 2018 at 13:39
  • 1
    \$\begingroup\$ How is your switch and led are connected? \$\endgroup\$
    – G36
    Commented Oct 28, 2018 at 13:42
  • \$\begingroup\$ Have a look here: stackoverflow.com/questions/50774540/… \$\endgroup\$
    – Oldfart
    Commented Oct 28, 2018 at 13:48

1 Answer 1


The behavior you describe most likely indicates that the switch closure is causing the port bit to read low, not high.

This would be quite normal, as it is fairly traditional to use a pull-up resistor to put a deterministic state on an input when the connected switch is open, and have the switch closure override this by connecting to ground.

While some other microcontrollers can be configured with either an internal pull-up or an internal pull-down, the AVR offers only internal pull-up resistors. To do things the other way around, with a button that signalled high when the contacts were closed, you would need to use an external pull-down resistor.

  • \$\begingroup\$ That's exactly what i was missing. Thanks a lor for your clear answer, \$\endgroup\$
    – Mo Tahoon
    Commented Oct 30, 2018 at 6:19

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.