In my project i have some input data, variable from 0 to 360 (compass)
And i need set servo position depending of input data.
Trouble is - to many IF condition in code.
I have table
Compass Servo
(0 to 10) and (350 to 0) 20
(11 to 20) and (349 to 340) 22
etc
And in program - this is big quality of IF condition. Working slow
May be exist some elegant way to obtain many IF checking in code?
Another way is to use a switch/case, which I think is easier to read:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
char buffer[5];
int charsRead;
int number;
int servo;
if (Serial.available() > 0) {
charsRead = Serial.readBytesUntil('\n', buffer, sizeof(buffer) - 1); // Leave room for null
buffer[charsRead] = '\0'; // Now it's a string
number = atoi(buffer);
Serial.print("Number is: ");
Serial.println(number);
if (number >= 0 || number < 360) {
switch (number) {
case 0 ... 10:
case 350 ... 359:
servo = 20;
break;
case 11 ... 20:
case 340 ... 349:
servo = 22;
break;
// More similar cases
default:
Serial.println("Should ever see this.");
servo = -1;
break;
}
Serial.print("Servo = ");
Serial.println(servo);
}
}
}
Note that you need to insert a space before and after the ellipsis operator (i.e., … )for it to work.
Also as you are treating opposite compass readings as equivalent (for instance 5 and 355 should produce the same servo position) you can easily eliminate half of the if-then checks using
If you have a series of tests do them from one end to the other and it will be much simpler
if (angle > 350) {
servoPos = 20;
}
else if (angle > 340) {
servoPos = 22;
}
else if (angle >
etc etc
However, I wonder what happens if you subtract 180 from the angle and take the abs value (because the upper and lower half seem to be the same) and then divide by 8 and add the answer to 20 - allways using integer arithmetic.