I've just started learning with my Arduino, and one of my first projects was a combination of the excellent CIRC-02 tutorial from oomlout and the potentiometer tutorial from arduino.cc.
I realized that I wanted to have the pot not provide such fine adjustments, so knowing that there are 1023 different "steps", I wrote the following:
Everything works exactly as I hoped it would, and I'm very happy with it, but my question is this: Is there a more efficient way of writing that? It seemed like a lot of repetitive typing, and I've noticed that in programming, there are usually ways around having to do that. As a side note, in the future I'd have definitely used shorter variables, as I suppose that was definitely part of the problem too.
I really like both of those solutions! Since I'm not especially mathematically inclined, it looks like the map() function will be what I make more use of.
Thanks for taking the time to point me in new directions!
All of the solutions above worked for your specific situation. That's because what you were doing inside each if ... else if ... was a simple assignment and nothing else.
One problem with that, and it applies to your situation here, is that the case statement can only test for equality. In your example, you want to test for a range of values.
So a combination of the map() function and the switch / case structure can be a generalized solution to replace a series of if ... else if ... structures.
int var = map(actualPotValue, 0, 1023, 1, 10);
switch (var) {
case 1:
//do something when var equals 1
break;
case 2:
//do something when var equals 2
break;
. . .
default:
// if nothing else matches, do the default
// default is optional
}
However, in many cases you will get compiled code that is very similar to what you'd get with an extended chain of if/else if statements. And in the "if" case, you can organize the order of evaluation to check the "most likely" candidates first, while a switch will leave it up to the compiler...