2

Is the a way to check the status of a bit in an arduino Uno?

Like how in Atmel AVR, there is bit_is_clear or bit_is_set

Glorfindel
  • 578
  • 1
  • 7
  • 18
JoeyB
  • 119
  • 3

3 Answers3

5

you can do it in a single line:

bool isSet = (var & (1 << bitNumber)) != 0;

1 << bitNumber is a bit shift in this case it means that the 1 will be multiplied with the power of 2

& is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.

ratchet freak
  • 3,267
  • 1
  • 13
  • 12
2

Let's say there is a register called r1, and you want to do something if its 6th bit is set to 1.

Here are two equivalent if statements, both doing the same thing:

if(r1&64){Do something;}
if(r1&(1<<6)){Do something;}

Tiny extra code information:

Let's say you want to do something if r1 = 01XX10XX00 where X means you don't care.

Here are three if statements, all doing the same thing:

if((r1&0b11001100)==(0b01001000)){Do something;}
if((r1&0b11001100)==((1<<6) | (1<<3))){Do something;}
if((r1|0b00110011)==(0b01111011)){Do something;}

If you & (logic and) a 0 somewhere, then you are setting that bit to 0
If you | (logic or) a 1 somewhere, then you are setting that bit to 1


Best of luck on your future ventures.

0

Arduino defines the function bit(), which makes it easy to do an if:

if (val & bit(5)) { // Is bit 5 set?
    // Do something
} // if

Note that you need to use the bit-and (&) operator, not the Boolean-and (&&) operator.

If you want to check if the bit is clear, you can use the not (!) operator - but then you need parentheses:

if (!(val & bit(5))) { // Is bit 5 not-set (clear)?
    // Do something
} // if
John Burger
  • 1,885
  • 1
  • 14
  • 23