4 input compare help

Kind of new at this and I've run into a roadblock.

Anybody have any good ideas on how to check the status of 4 digital inputs and if 3 of them have gone high, then set a flag bit?

Basically i'm trying to check 4 reed switches, and if 3 of them have been tripped then set a bit that I can use to trigger the rest of my code in the loop. (I want 3 out of 4 for redundancy and fault tolerance.

I was thinking about checking the pins, and adding 1 to a bit if the result is true, and doing this for each input, then if the total is >3 then setting the flag, but that will just keep adding if only 1 switch is tripped.

Or maybe a large comparison statement?

Any ideas?


maybe you could try (in psuedo)

while((input1 + input2 + input3 + input4) < 3)
->do nothing

This is what happens when I stay up till 5:30am playing C&C against co-workers..... that's so much easier than I was thinking.

Now comes the really stupid question, can I do the test directly on the inputs, or should I have the input states read into variables first, then do the math on the variables. That's how I think i have it below. I used an if loop cause i'm going to want out of the loop weather or not it's true.

#define reed1 8    // Reed switch 1
#define reed2 9    // Reed switch 2
#define reed3 10   // Reed switch 3
#define reed4 11   // Reed switch 4

int trip = 0;      // Flag bit for tripped state
int sensor1 = 0;
int sensor2 = 0;
int sensor3 = 0;
int sensor4 = 0;

void setup()
  pinMode(reed1, INPUT);
  pinMode(reed2, INPUT);
  pinMode(reed3, INPUT);
  pinMode(reed4, INPUT);

void loop()
  sensor1 = digitalRead(reed1);  // Check for sensor trips
  sensor2 = digitalRead(reed2);  // Check for sensor trips
  sensor3 = digitalRead(reed3);  // Check for sensor trips
  sensor4 = digitalRead(reed4):  // Check for sensor trips
  if((sensor1 + sensor2 + sensor3 + sensor4) > 3){
    trip = 1;
Rest of my loop code here


wouldn't you want it to check if the value is greater than two?

yep. sure would... wonder how long i would have stared at it before I figured it out.

and i could streamline it by doing the following right?

if((digitalRead(reed1) + digitalRead(reed2) + digitalRead(reed3) + digitalRead(reed4)) > 2){
trip = 1;