Take the 2-minute tour ×
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

I'm trying to manipulate the ports of Arduino using C code. I have attached an LED in Pin8 and a tact switch in Pin13 (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 to 32, or else 0b00100000.

But 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?

Thank you

share
    
Are you saying the full code you've posted works, but it fails if you add == ...? –  Peter R. Bloomfield yesterday
    
That's right , it fails with == . –  user3060854 yesterday

1 Answer 1

up vote 4 down vote accepted

== 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.

share|improve this answer
    
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. –  user3060854 yesterday
3  
Not really sure what needs to be explained. a & b == c is equivalent to a & (b == c). –  Ignacio Vazquez-Abrams yesterday
    
That's what I wanted to know. Thank you again. –  user3060854 yesterday
1  
I found another solution based on your last remark. if( (PINB &(1<<PB5) ) == 0b00100000){ works too –  user3060854 yesterday
    
Eh. Like I said, you don't need to care about the exact value. –  Ignacio Vazquez-Abrams yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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