# Ho i can fight with many IF condition?

Hello!

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?

Thanks.

You might try the switch case with the gcc ... extension.

You could create a lookup table with 360 entries and put the servo step there:

byte servo_pos = {
20,20,20,20,20,20,....22,22,22,22....20,20};

You can either use a bunch of if statements, or you can use math. Look at your input and output values there and see if you notice a pattern.

``````if((compass > 10 && compass <= 20) || (compass < 350 && compass >= 340))
{
Servo = 22; //whatever your servo code is
}
else if (compass <= 10 || compass >=350)
{
Servo = 20; //again, your code
}
else
{
//whatever you need it do when the compass reads 21-339
}
``````

Post your code so we can help analyze.

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;
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.

Edit: Sorry, Keith…didn’t see your post in time.

Also, note that this is not standard C, but a gcc extension, which is fine if this is only going to be used on the arduino.

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

{
}

Meaning in this example 360-355 = 5

Meaning your range will always be 0-180.

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.

servoPos = abs(angle - 180) / 8 + 20;

...R