We see that the if function takes as parameter a condition which is boolean: either false or true.
We will see an example of a true condition:
By writing that 7 is greater than 5, the condition is true so the lines of code inside the brackets will be executed. By returning the condition, i.e. 7<5, the condition becomes false and therefore what is inside the brackets will not be executed.
The condition for the if can be hard to write, especially with all the operators that exist. We recommend our course on mathematical functions to have a complete table of all the operators that can be used on arduino!
The else is used when the if condition is false. It is an alternative to the if, if this one is not executed then the else will be.
Here is an example for the else:
Here is an example where the if condition is false so that the program executes the else:
As you have seen, the else has no condition, so it will always be executed if the if is false. You may want to make another if to test a second condition. For that there is the “else if”.
The “else if” allows to test a second condition after the first if. The “else if” like the simple if will be executed only if the condition is true. You can put as many “else if” as you want:
Here is an example:
Here as we can see, it is the second “else if” that will be executed because the conditions before it are false.
However, if you have a lot of “else if” to put, an alternative is the switch case.
The switch case allows to test several conditions, making a cleaner code instead of using several if or else if. The switch case doesn’t replace in all cases the if and else if.
It uses a variable that contains an integer, a string or a boolean. Each cases is used to differentiate what the program must do if the variable is equal to the condition 1, or 2. If the variable does not correspond to any case, then the code in default will be executed.
Here is an example:
In this example your variable will be compared to each case to know which code to execute. Here the value of “your_variable” is 1 so the executed code will be case 1.