# How do I make a binary int pragmatically based on sensors?

I have an array of 5 sensors: sensor[0] through sensor[4].
Each of them read a value (they are IR sensors, but it really doesn’t matter). If the value is below a threshold, it is OFF, otherwise, it is ON.

I want to be able to do a case switch depending on the collective values of the sensors. I was thinking about putting the OFF/ON values into a binary variable, so then I could easily test for each condition.

for example
int b; // a binary variable to hold the status of each sensor
// b= B11000 would indicate that sensors 0 & 1 are on, and 2, 3, & 4 are off.

Then I think I can switch case like this (untested)

switch (b) {
case B11000:
// do something
break;
case B00100:
// do something else

So, how do I build the b value?

Using bitWrite() http://arduino.cc/en/Reference/BitWrite

Build the value by initialising the byte (no need to use an int) to zero, then bitwise OR it with 1 for sensor 1, 2 for sensor 2, 4 for sensor 3, 8 for sensor 4, 16 for sensor 5

I would use the bit positions from right to left to hold the sensor states rather than the way you suggest. If the Binary switch does not work you can simply use the normal decimal number held by the byte, of course.

I'd use a FOR loop to process each sensor in turn, convert the value to a bit and then use bitWrite() to write that bit to the corresponding bit number of a byte accumulator. Obviously the sensor array index and the bit number would be the same.

The code doing that would be a good candidate for putting into a function that returned the resulting byte.

These are all GREAT ideas! Thanks :) I have my robot up and running now.