3

I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte PINB & (1 << PB5) equals 32, or 0b00100000.

However, if I try to use

if( PINB &(1<<PB5) == 32){

or

if( PINB &(1<<PB5) == 0b00100000){

the LED doesn't respond.

Here's the full code:

void setup() {
  DDRB |= 0b00011111; 
  Serial.begin(9600);
  }

void loop() {
  Serial.print("PINB &(1<<PB5)");
  Serial.println(PINB &(1<<PB5));

  if( PINB &(1<<PB5) ){
    PORTB |= (1<<PB0);
    }
  else{
    PORTB &= ~(1<<PB0);    
    }
  }

What am I missing?

2
  • Are you saying the full code you've posted works, but it fails if you add == ...? Mar 17, 2015 at 15:45
  • That's right , it fails with == . Mar 17, 2015 at 15:48

1 Answer 1

5

== has higher precedence than &, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a specific value, just if the appropriate bit is set.

7
  • You are right. If I use my_byte = PINB &(1<<PB5) and if( my_byte = 0b00100000 ){ it works fine. Nevertheless, could you explain how the comparison with == and & works? Thank you. Mar 17, 2015 at 15:55
  • 4
    Not really sure what needs to be explained. a & b == c is equivalent to a & (b == c). Mar 17, 2015 at 15:57
  • That's what I wanted to know. Thank you again. Mar 17, 2015 at 16:00
  • 1
    I found another solution based on your last remark. if( (PINB &(1<<PB5) ) == 0b00100000){ works too Mar 17, 2015 at 16:06
  • Eh. Like I said, you don't need to care about the exact value. Mar 17, 2015 at 16:08

Your Answer

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

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