3

Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).

For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "X - Don't Care".)

I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.

Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.

Thanks! -Mike

asked Dec 12, 2018 at 13:24

2 Answers 2

7

You need to use boolean arithmetic. Use the AND operator (&) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:

byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111
if ((wanted & incoming) == wanted) {
 // whatever
}

The AND operator compares each bit of the bytes in turn. If they are BOTH 1 then the result is 1. Otherwise the result is 0. So the above gives:

wanted: 11001110
incoming: 11011111
AND: 11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:

wanted: 11001110
incoming: 01011011
AND: 01001010

And you can see that the result doesn't match.

answered Dec 12, 2018 at 13:34
2
  • AH! Okay, that makes sense - I would want my 'mask' value to have bits set to '1' I care about, and '0' I don't. This would effectively force the 'don't care' bits to 0. Commented Dec 12, 2018 at 16:17
  • 1
    That is correct. Commented Dec 12, 2018 at 17:48
2

There are ways to mask off the don't care bits. Say your example, 0b11xx1111. Then

incomingByte = Serial.read();
incomingByte = incomingByte || 0b00110000; // make 4, 5 high
if (incomingByte == 0b11111111){ 
// got all 1s, do something 
}
else {
 // some 0s received, do something else
}
Juraj
18.3k4 gold badges31 silver badges49 bronze badges
answered Dec 12, 2018 at 15:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.