# Checking the condition of multiple switches

What is an efficient way of checking the condition of 4 switches. At the moment it doesnt matter whether they are pb or toggle. we just need to know which switch.
There are 16 obviously conditions to be met. I could use if else if but that would be clumsy.
Is there a better way than if else if.
Thank you

If you need to evaluate them as 16 possible combinations...

``````int value = 0;
if (digitalRead(pinA)) value |= 1;
if (digitalRead(pinB)) value |= 2;
if (digitalRead(pinC)) value |= 4;
if (digitalRead(pinD)) value |= 8;
switch (value)
{
case 0:
.....
case 1:
.....
.....
.....
case 15:
.....
}
``````

If they are all on the same port of the Arduino and in adjacent bits, I suspect it is also possible to bypass the digitalRead and get all 4 pins in a single read of the port.

Depends what you mean by clumsy. Do you just less code and easier to maintain in the IDE; or are you looking for raw speed efficiency?

There are 16 obviously conditions to be met.

Using an array of pin numbers read in a for loop and setting/clearing a corresponding bit in a byte variable would give you a number between 0 and 15. Is it that number you want so that you can act on certain combinations or do you want to do something else ?

currently using following code. updtMenu() uses 4 buttons. Just knowing is a button is pressed is used to break out of loops() (e.g. connecting to WiFI)

``````#define  TA            2
#define  TB            4
#define  TC            5
#define  TD            12
#define  TE            13

#define  TF            14
#define  TG            15

#define  TH            26
#define  TI            27
#define  TJ            23

#define  ADC_REV       32   // Wiper of 10K Speed Pot Ends=GND & +3.3V
#define  ADC_THR       39   // Wiper of 10K Speed Pot Ends=GND & +3.3V
#define  ADC_MAX       4095

byte pinPullups [] = { TA, TB, TC, TD, TE, TF, TG, TH, TI, TJ };

#define N_BUTTONS   sizeof(pinPullups)

enum {
BUT_LAMP, BUT_UP, BUT_DN, BUT_MENU, BUT_SEL, BUT_HORN,
BUT_G, BUT_H, BUT_I, BUT_J
};

byte butState   [N_BUTTONS] = {};
byte butPress   [N_BUTTONS] = {};

// ---------------------------------------------------------
// check for button presses
static bool
chkButtons (void)
{
bool  any = HIGH;

for (int i=0; i < N_BUTTONS-0; i++)  {
byte  but = digitalRead (pinPullups [i]);

// clear butPress state and set if change & LOW
// butPress will only be true for one cycle
butPress [i] = 0;
if (butState [i] != but)  {
butPress [i] = ! but;
butState [i] = but;
}

any &= but;
}

return any;
}

// ---------------------------------------------------------
// update menu
static MenuStim_t
updtMenu (void)
{
MenuStim_t stim = M_NULL;

if (butPress [BUT_MENU])
stim = M_MENU;
else if (butPress [BUT_SEL])
stim = M_SEL;
else if (butPress [BUT_UP])
stim = M_UP;
else if (butPress [BUT_DN])
stim = M_DN;

menu (stim);
return stim;
}
``````