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

migrated from electronics.stackexchange.com Jan 5 '18 at 3:00

This question came from our site for electronics and electrical engineering professionals, students, and enthusiasts.

  • If it's an AVR-based Arduino, you can use bit_is_clear() and bit_is_set(). – Edgar Bonet Jan 5 '18 at 10:36
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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