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
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityyou 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.
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.
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
bit_is_clear()
andbit_is_set()
.