I'd like to turn on the board's LED (PB5) when I press its button (PB7).
DDRB = 0xFF; // set all B-ports as output
DDRB &= ~(1<<7); // change PB7 to input
while (1)
{
if (PINB & (1<<7))
PORTB |= (1<<5); // when button is pressed, turn on the LED
else
PORTB &= ~(1<<5); // when button is not pressed, turn off the LED
}
However, PINB & (1<<7)
returns 1 when I except 0, and 0 when I press the button. I could add a not operator and it'd be fine, but I'd like to know what I missunderstand. Why is the 8th bit of PINB
read as 0 when I press the button?
!(PINB & (1<<7))
. Now you get a 1 when the button is pressed and a 0 when released. \$\endgroup\$ – Tom Carpenter May 21 '16 at 17:24