 # Switch case help

Hello, first time writing here. I have a problem with this “switch case” example. I’ve been trying to modify it in order to accept digital input instead of analog.

So far, I haven’t found a solution.

What I want to do is: If digital input 3 is “high” it goes to case 1. If digital input 4 is “high” it goes to case 2. If digital input 5 is “high” it goes to case 3 and so on.

``````const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
// initialize serial communication:
Serial.begin(9600);
}

void loop() {
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

// do something different depending on the
// range value:
switch (range) {
case 0:    // your hand is on the sensor
Serial.println("dark");
break;
case 1:    // your hand is close to the sensor
Serial.println("dim");
break;
case 2:    // your hand is a few inches from the sensor
Serial.println("medium");
break;
case 3:    // your hand is nowhere near the sensor
Serial.println("bright");
break;
}
delay(1);        // delay in between reads for stability
}
``````

It is a bit ridiculous to use a switch statement to process an input that can only have one of two states. A simple if-else is far more appropriate.

Regards,
Ray L.

What I want to do is: If digital input 3 is "high" it goes to case 1. If digital input 4 is "high" it goes to case 2. If digital input 5 is "high" it goes to case 3 and so on.

I'm not sure if more than one pin can be high at a time and if you need to respond to multiple situations, but if so, you can make a switch case on the binary values of the combination

Example three switches can have eight states, and you switch case on that value

000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7

cattledog:
Example three switches can have eight states, and you switch case on that value

000 = 0
001 = 1
010 = 2
011 = 3
100 = 4
101 = 5
110 = 6
111 = 7

That’s a good idea, this will also give cases available for more than one input being high at the same time (which, if the inputs are physical switches on a control panel, is a common scenario).