Question

I'm writing code on Arduino (very similar to C, which I don't know, or very little), and I have a little issue concerning the switch/case statement.

I need my Arduino to do this or that depending on the values of a potentiometer (0 to 1023). However, I have no clue how to tell it case "0 to 200". For example, I tried

case 0..250:
  blablaSomeCode;
  break;

And so on... How can I do it?

I don't really want to write case 1 case 2 case 3...

Was it helpful?

Solution

You will have to use a cascade of if's (also/especially if your value is a floating point number)

int value= ...; 

if (value>=0 && value<=250 {
    // some code 0..250
}
else 
if (value>250 && value<=500) {
    // some code 251..500
}
else 
if (value>500 && value<=1000) {
    // etc.
}
else {
    // all other values (less than zero or 1001...)
} 

OTHER TIPS

switch(val)
{
    case 0 ... 250:
        inRange(val);
        break;

    default:
        outOfRange();
        break;
}

While the code in the previous answer is valid, I would just stick with the switch statement as it is very applicable for the problem to solve.

Please note that using ranges ('...') is not conforming with the ANSI C standard, but it works fine in the Arduino environment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top