Switch case syntax help needed

Hello all,

I've only recently discovered the Arduino stuff and am having a ton of fun with it. Once I receive my board and run some tests, I'll post my project in case anyone is interested.

I'm having trouble establishing a switch case structure and need to know if something like the following is valid. I've read the switch case doc, but either the doc doesn't cover this or I'm trying to do something switch case can't handle. Please let me know if this is possible and what the syntax would look like for real.

voltsIn = analogRead(15)
switch (voltsIn) {
case voltsIn < 12:
// do something
break;

case 12 < voltsIn <= 18:
// do something else
break;

case voltsIn > 18:
// do the third thing
break;
}

Cheers!

You're trying to do something that the C "case" statement doesn't support; use some nested ifs instead:

if (voltsin < 12) then {
  //Something
} else if (voltsin <=18) then {
  //Something else
} else if (voltsin > 18) then {
  //A third thing
}

You do realize that you have some work to do to an analogIn value before it will accurately corrospond to a unit like 'volts' ?

This should be a FAQ , I wanted to know to do the same.

You can only have a single value !!

eg switch ( input )
case 5:

You can have multiple values, but you must list all of them, e.g.:

switch (ivar) {
case 0:
case 1:
case 2:
  // Do something for 0, 1 or 2
  break;
case 7:
case 8:
case 42:
  // Do something else for 7, 8, 42
  break;
default:
  // Catch-all for all other values
  break;
}

Darn, I was afraid that was going to be the response. Kinda makes switch case a not-quite-as-useful tool. So I'll use a long if else statement instead. Accounting for all 1024 values of an analogRead() would be painful at best. :o

Thanks for the help!

You probably won't be able to use all 1024 cases anyway, due to noise. I've tried this sort of thing with an analog voltage divider, and the analog-in value is never completely stable. It'll also vary with the temperature of the resistors, for instance!

If you want to make a really long if-else chain, you might find it easier to make an array of threshold values and loop though them, comparing as you go.

you might find it easier to make an array of threshold values and loop though them

Hmmm, I'll have to see what I can do with that. Thanks for the suggestion.

Fortunately I don't need tight accuracy and the ranges I am looking at are something like 0-6V, 6,-12V 12-18V, 18-25V and 25V or more scaled down 1:10 with a voltage divider (I haven't really decided yet). Based on which of those ranges the value is in, the program does something different.

Cheers!

Not std. C but this works with integers

   switch (key) {                     // a case for each key 
    case 0 ... 9:                     // digits 0-9