What is wrong with this code and how else should it be done? I can do this in VB:
switch (distance) {
case <= 10:
Serial.println("far away");
break;
case 11-50:
Serial.println("within sight");
break;
case 51-100:
Serial.println("slow down");
break;
case 101-200:
Serial.println("almost there");
break;
case > 201:
Serial.println("stop!");
break;
default:
// if nothing else matches, do the default
// default is optional
}
with that set the distance value being 201 will cause the string to be "within sight" then "slow down" then "almost there" then "stop!" and finally "stop!" will print.
This may not matter at all depending on what else is going on in the code though.....
BTW, the reason for using if..else rather than just straight if is that execution will stop as soon as the correct range is found. Using just if will mean every single condition will be tested even if the first if was executed as the correct case.
This strikes me as the most elegant solution, mainly because it avoids needing to duplicate the boundary values and precludes any possibility of gaps or overlaps between the ranges. Using the switch/case range approach involves some repetition (which is always a bad idea) and would make it very easy to introduce bugs if you wanted to adjust any of the thresholds.
using if every single time means if distance < 10 its still going to check all 5 every single loop, now if distance == 60 its going to check two conditionals and exit