Chapter 6
If Statement with Arduino, Control the Execution of your Code
If conditional statements with Arduino are the most used in programming Maker projects. They serve to make your program do one thing or another, depending on each situation.
Imagine the loop () function of an Arduino code that is repeated indefinitely within our program. It is where things really happen. It repeats very fast, and the speed depends directly on the clock of the microcontroller CPU.
If we talk about Arduino UNO, its speed is 20 MHz, that is, 20,000,000 instructions per second. And on an ESP8266, the clock speed is 80 MHz (80,000,000 instructions per second).
Surely you are wondering if the same code that is inside the loop () function is repeated over and over again, why do we get different results?
Well, it is largely due to the conditional statements if with Arduino. In this lesson, you will learn the following concepts:
-
Syntax of the if-else and else if statement
-
Comparison operators (>,> =, <=, ==,! =)
-
Boolean operators (||, &&,!)
And of course, you will learn how to use the if statement with Arduino through a case study.
Take the plate out of the box, and let's start with this chapter.
What will you learn in this chapter?
-
if with Arduino necessary material
-
Syntax of the if statement with Arduino
-
Comparison operators in if statements with Arduino
-
Example if statement with Arduino
-
Boolean operators if with Arduino
-
if-else with Arduino
-
Example if-else statement with Arduino
-
else if with Arduino
-
Example else if statement with Arduino
If with Arduino - Necessary Material
Although we will see all this later, in this lesson with the if-else and Arduino statements, you will need the following material.
-
An Arduino UNO or derivative. Any compatible board can be worth even an ESP8266.
-
A protoboard to connect the components.
-
A potentiometer does not matter the value of the resistance.
-
And cables to connect everything.
The circuit we will use is very simple. It only requires a potentiometer connected to an analog pin of the Arduino board. The electrical scheme would be as follows.
Let's now see the syntax that is hidden behind the if-else statement with Arduino.
Syntax of the if Statement with Arduino
The syntax of the if statement with Arduino is very simple. We begin by writing the reserved word if (it is translated as conditional). Then in brackets, we put the condition and finally open and close the keys.
if (Condition) {
// Everything we put here will be executed
// only if the condition is met
}
The condition is what will cause the code between the keys to be executed. If it is true, the Arduino code flow will enter the keys and execute everything inside. But of course, what is a condition?
Imagine you tell your child, "If you pass all the subjects, I will give you a bicycle." That would be a condition. Within the parentheses will be the condition or conditional sentence. It is something that can be evaluated as true or false (in English, it is true or false).
If your child passes all subjects, it is true (true) and therefore has a bicycle. If your child does not pass all subjects is false (false) and therefore runs out of bicycle.
If you approve_all then
buy_bikes ()
End yes
These conditions are called Boolean due to the great English mathematician George Boole, creator of Boolean logic. With this logic, there are only two possible states 0 or 1 that are equivalent to false (false) and true (true).
Ok, we are clear that an if statement with Arduino allows us to execute code depending on a condition. Now let's see how we can make conditional with the comparison operators.
Comparison Operators in if Statements with Arduino
Really, for something to be true or false, we need to compare it with
something. Typically, the conditional statement if with Arduino with numbers is used, but other data can be used.
We can compare temperature, atmospheric pressure, ultraviolet radiation, time, intensity, voltage, water level, and any magnitude that can be measured.
Something that I think we all understand is temperature. For example, we can write a code where, depending on the temperature, a servo motor that activates a fan moves.
if (temperature > 25) {
Servo.move (30);
}
In this case, we are saying that whenever the temperature is greater than 25, move a servomotor. But we could also have programmed if the temperature is less than 30 or if it is greater than or equal to 25.
More or less I think you're getting where I want to go
All of the above are comparisons. All we do is compare two values and evaluate whether it is true or false. To compare, comparison operators are used.
With the if statement with Arduino, you can use six comparison operators:
I am sure that more than one comparison operator sounds to you. They are often used to express mathematical formulas.
The first 4 (greater than, less than, greater than or equal to or less
than or equal to) are quite explicit. However, the last two (equal to and different from) require a little explanation.
Let's see some examples of each of them.
Comparison operator greater than (>)
As long as the number on the left is greater than the number on the right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
50> 10 -> true
-
15> 80 -> false
Comparison operator less than (<)
As long as the number on the left is less than the number on the right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
10 <50 -> true
-
80 <15 -> false
Comparison operator greater than or equal to (> =)
As long as the number on the left is greater than or equal to the number on the right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
50> = 50 -> true
-
50> = 49 -> true
-
15> = 90 -> false
Comparison operator less than or equal to (<=)
As long as the number on the left is less than or equal to the number on the right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
50 <= 50 -> true
-
49 <= 50 -> true
-
90 <= 15 -> false
Comparison operator equal to (==)
As long as the number on the left is the same as the number on the
right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
20 == 20 -> true
-
15 == 20 -> false
Look at the operator symbol equal to (==), why do you use a double equal sign? Do you need to verify twice that they are equal? The answer is simpler than it seems.
The equal sign already has a function, that of the assignment. When we assign a value to a variable, for example. The double equal sign is used as an equality comparator so as not to confuse the compiler since otherwise, I would not know if we are comparing or assigning a value.
Comparison operator other than (! =)
As long as the number on the left is different than the number on the right, the condition of the if statement with Arduino is true. Otherwise, it is false.
-
20! = 10 -> true
-
10! = 10 -> false
This comparison operator is the opposite of equal to.
Although in the examples I am using numbers, in the conditions of the if statements with Arduino, you can also use variables as we will see in the examples that follow.
With this, we have everything we need to start using the if statement with Arduino. Let's see a very simple example.
Example if Statement with Arduino
In this example, we are going to use the if statement with Arduino using the electric scheme of the potentiometer that we have seen at the beginning of this chapter. The idea is to be able to show by the serial monitor when the analog value exceeds a value.
I remind you that the analog pin has a range of values that goes from 0 to 1023 in an Arduino UNO. When we have 0V at the input, analogRead returns 0. When we have 5V at the input, analogRead returns 1023.
The code must be able to display text on the serial monitor when it exceeds 300.
// Variable with analog pin
const byte Analogpin = A0;
void setup () {
// Start serial communication
Serial.begin (9600);
}
void loop () {
// Read analog pin
int value = analogRead (Analogpin);
// Show analog pin value
Serial.println (value);
// If statement with Arduino
if (value> 300) {
// Show text by serial monitor
Serial.println ("Value exceeded");
}
// 100 ms delay
delay (100);
}
The code begins by declaring a constant variable of the type byte called Analogicpin. This variable contains the analog pin where the potentiometer is connected.
In the setup () function, we initiate serial communication with Serial.begin ().
In the loop () function, the first thing to do is read the analog pin with the analogRead function. The result is stored in the value variable of type int. This value is shown by the serial monitor with the Serial.println () function.
Then begins the statement of the if statement with Arduino. As we have seen, you put the reserved word if and then open and close parentheses. Within the parentheses goes the condition.
If we want to know if the value of the analog pin is greater than 300, we use the comparison operator greater than (>). On the left, you have the value you want to evaluate, and on the right, the threshold value that determines the condition.
Then open and close keys and inside is the code that will be executed if the if condition with Arduino is true. In this case, use the Serial.println () statement to display a text on the serial monitor (no matter what).
Finally, put a delay of 100 milliseconds so that we can appreciate it when you write on the serial monitor and when not.
Now, if you load the code to the board, you will see how the analog pin value appears, and whenever it is above 300, it will show the text Value exceeded on the serial monitor.
It has been simple, right? Try different comparison operators and see when the text appears on the serial monitor.
Now think about how you would do it if you want the code to run when it is between two values. For example, if the value is between 300 and 500, it shows text on the serial monitor.
With only the if statement with Arduino, you won't be able to do it. For this, you need Boolean operators.
Boolean Operators if with Arduino
A Boolean operator allows us to make combinations between conditions within an if in Arduino. This programming tool is very powerful and is used in many cases.
There are 3 Boolean operators
-
|| or (0)
-
&& and (y)
-
! not (no)
As I said, they serve to combine conditions. For example, you can know if the value obtained from analogRead is between 300 and 500.
It's something like when you press two keys on your keyboard. If you press the c key, write that letter in a document, for example. But if you press the control key (Ctrl) and the c key, what you do is copy what you have selected. More or less, it is something similar.
We are going to see each of these Boolean operators with examples so that you understand it better.
Boolean Operator or (||)
It can be translated as "or this or that." It is represented with two vertical lines (||) that you find on key 1 of the keyboard. To use it, you must first press Alt Gr and then the 1 key.
This operator makes the if condition with Arduino true if either of the two or more conditions are met. For example, if we have this code:
if (value> 300 II value <200) {
// Show text by serial monitor
Serial.println ("Value exceeded");
}
We are saying that whenever the value is greater than 300 or that the value is less than 200, display a text on the serial monitor. This
means that whenever the value is between 201 and 299, it will not show any text.
In the rest of the cases, it will show the text on the serial monitor.
Boolean Operator and (&&)
It can be translated by "this and that." It is represented by two ampersands (&&) symbols found on key 6 of the keyboard. Pressing capital letters and 6, you can use it in your codes.
This operator makes the if condition with Arduino true only if both or several conditions are met. For example, if we have the code:
if (value> 300 && value <500) {
// Show text by serial monitor
Serial.println ("Value exceeded");
}
It means that it will only be true if the value is greater than 300, and the value is less than 500. This gives us a range of values between 301 and 499 (don't forget that the symbols> and <exclude the numbers on the right).
Therefore, only when you are in that range will you show the text on the serial monitor.
Boolean Operator not (!)
It translates as "no." It is represented by the final exclamation mark (!) Located on the 1 key. You can use it by pressing the uppercase key plus the 1 key.
What this operator does is something strange. If an expression is true, it returns false, and if it is false, it returns true.
To understand the following example, you also have to understand what is true and what is false. They are still two states, like the binary code of which I have spoken to you before. We can have a 0 (false) or a 1 (true).
But the reality is that there are more numbers. The question is, is 2 true or false? Boolean data types are always false as long as it is 0. Otherwise, it is true. Therefore 2 and any other numbers are true if evaluated in a condition. This is only a reminder.
In a digital pin, we also have two values, LOW and HIGH. If you enter the Arduino core code, you can verify that these two reserved words are actually two constants whose value is 0 for LOW and 1 for HIGH.
Therefore, if we have a digital pin connected to a button, and the input is 0V, the status will be LOW. If we store that value in a variable, we could evaluate its value if it is false or true in an if conditional statement with Arduino.
For example, it can help us to know if a button is not pressed. In normal use, when pressed, it will have a HIGH state that, as we have seen, is true. While when not pressed, it has a LOW status, false.
boolean button = digitalRead (Buttonpin),
// If the button is false (equal to 0) everything is true
if (! button1) {
// Turn on the LED
digitalWrite (led Warning, HIGH);
}
This would be the way we would detect if a button is not pressed. In this case, it will pass inside the if with Arduino and execute the code inside.
Other Considerations of Boolean Operators with an Arduino if
Finally, I want to add that you can join as many conditions as we want to an if with Arduino. It is convenient, as far as possible, not to add many conditionals as this would make our code unreadable.
Also, note the use of the not (!) Operator with other comparison operators. For example, the same expression can be expressed in different ways thanks to the not operator. If you want to know if a
number is between 300 and 500, you can use these two conditions:
These two expressions return the same value for the same number.
Now we will continue to see how you can execute different pieces of code depending on different conditions with if-else in Arduino.
if-else with Arduino
So far, what we have seen is that if it meets a condition, it executes the code inside an if with Arduino. But what if we have more than one condition? For example, if the temperature is greater than 25, it moves the servo motor 135º if it is less than 25, it moves the servo motor 45º.
With what we know so far, we could do two if with Arduino.
if (temperature> 25) {
Servo.move (135);
}
if (temperature <= 25) {
Servo.move (45);
}
It would not be bad, but there is a more optimal way to do it, using the else conditional statement with Arduino.
Else can be translated as "yes no." It is always linked to a conditional statement if Arduino can never go alone. Therefore if-else would be translated as if the condition is met, execute the code if you do not execute this other code.
It is logical to think that when we are evaluating the same variable, it cannot have two values. In this case, the temperature is either greater than 25 or less than or equal to 25, and there is no other.
The biggest advantage of using if-else with Arduino is that we will
make our code more efficient. In the first case (with two if), the two conditions will always be evaluated even if one of them is true.
If, for example, the temperature is 27º when it reaches the first if, since the temperature is greater than 25, it will execute the code inside. When finished, it will exit the if and go to the next if. Check if the temperature is less than or equal to 25, something absurd if nothing has changed within the first if.
This is where, if-else, comes into play.
if (temperature> 25) {
Servo.move (135);
} else {
Servo.move (45);
}
The second if is replaced with the condition by an else. This conditional statement does not have any condition. That is, if the previous condition or conditions are not met, it will always enter through the else.
The advantage is that if the first condition is met, you will stop checking the rest of the conditions. This programming structure is called nested if.
Be very careful with these types of structures since they can lead us to what is known as the spaghetti code. It is such an obfuscated code that it looks like a plate of spaghetti.
Let's see it with an example.
Example if-else statement with Arduino
We will continue with the same electric scheme of the potentiometer. The idea with this practical exercise is to turn on the LED integrated with the Arduino board (it is connected to pin 13) when the analog value exceeds 500. Otherwise, turn off the LED.
The code would be as follows.
// Variable with analog pin
const byte Analogicpin = A0;
// Variable LED pin
const byte Ledpin = 13;
void setup () {
// Start serial communication
Serial.begin (9600);
// Pin mode
pinMode (Ledpin, OUTPUT);
}
void loop () {
// Read analog pin
int value = analogRead (Analogicpin);
// Show analog pin value
Serial.println (value);
// If statement with Arduino
if (value> 500) {
// Turn on LED
digitalWrite (Ledpin, HIGH);
} else {
// Turn off LED
digitalWrite (Ledpin, LOW);
}
// 100 ms delay
delay (100);
}
The first part of the code is the declaration of variables. We need two to store the number of pins. They are constants of the byte type.
The Analogicpin variable stores the analog pin where the potentiometer is connected, pin A0.
The Ledpin variable stores the digital pin where the LED is connected, pin 13.
In the setup () function, we started the serial communication with Serial.begin () and put the LED pin in OUTPUT mode.
Within the loop () function, we read the analog pin with analogRead () and store it in the variable of the int value type. Then we show it by the serial monitor.
On the next line begins the conditional statement if-else with Arduino. As always, we put the word if and in brackets of the condition. In this case, it is if value (it is the value obtained from the analog pin) is greater than 500, then it enters inside the if.
Between braces, we put the code that we want to be executed when the condition is met. In this case, the LED is lit with the digitalWrite () statement.
Then we put the else and between braces the code that we want to be executed. In this case, the LED goes out with the digitalWrite () statement.
Finally, a delay of 100 ms so that we can follow what is shown by the serial monitor.
If you load the code to the board and play with the potentiometer, you will see how it turns on and off when you go over 500 or lower than 500.
The last thing that remains to be seen is if we want to have three or more conditional sentences if-else nested. We can do that with else-if, another way of writing an if with Arduino.
else if with Arduino
The else if conditional statement with Arduino will allow us to have two or more conditions within a nested if block.
The else conditional statement is very useful in cases where we only have two possibilities, but what happens if, for example, you want the LED to flash when the value of the potentiometer is greater than 800. When it is between 501 and 800, it stays on, and when it is less than or equal to 500, it turns off.
We can choose to put everything full of if without nesting, i.e., separate if statements. We have already seen that this is not a good idea when we are working with the same variable.
The else statement falls short because it does not allow a condition to be set.
But there is the else if statement which, as with the else statement, is always linked to an if with Arduino. It could be translated as if you have not fulfilled the above, check if this other is fulfilled.
It really is as if it were another if, but by putting the reserved word else in front, we are joining all the if. The syntax is very similar.
Else if (condition) {
// code to execute
}
First, we put the else, then if and in brackets the condition. Between the keys, the code we want to be executed when the condition is met.
For example, this would be the code if we want to control 3 ranges on an analog pin.
// If statement with Arduino
if (value> 800) {
// Flashing LED
digitalWrite (Ledpin, HIGH);
delay (500);
digitalWrite (Ledpin, LOW);
} else if (value <= 800 && value> 500) {
// Turn on LED
digitalWrite (Ledpin, HIGH);
} else {
// Turn off LED
digitalWrite (Ledpin, LOW);
}
The first if checks if the value of the analog pin is greater than 800. Since it only has the symbol greater than, it will start at 801. From 801 to 1023 it will execute the code inside, that is, it will flash the LED.
The second condition begins with else if and then in brackets of the condition. Whenever the analog value is less than or equal to 800 or greater than 500 (will start at 501), it will turn on the LED and leave it fixed.
Finally, if the two previous conditions are not met, it will enter the else and turn off the LED.
I repeat that when several if they are nested if one of them meets the condition, the rest of the if will not be executed. This will make our code more efficient.
Example else if statement with Arduino
To finish, we go with an example. You just have to replace the if we have seen in the previous example with this series of nested if.
// If statement with Arduino
if (value> 800) {
// Flashing LED
digitalWrite (Ledpin, HIGH);
delay (500);
digitalWrite (Ledpin, LOW);
} else if (value <= 800 && value> 500)
{
// Turn on LED
digitalWrite (Ledpin, HIGH);
} else {
// Turn off LED
digitalWrite (Ledpin, LOW);
}
The complete code would be as follows.
// Variable with analog pin
const byte Analogicpin = A0;
// Variable LED pin
const byte Ledpin = 13;
void setup () {
// Start serial communication
Serial.begin (9600);
// Pin mode
pinMode (Ledpin, OUTPUT);
}
void loop () {
// Read analog pin
int value = analogRead (Analogicpin);
// Motivate analog pin value
Serial.println (value);
// If statement with Arduino
if (value> 800) {
// Flashing LED
digitalWrite (Ledpin, HIGH);
delay (500);
digitalWrite (Ledpin, LOW)
;
} else if (value <= 800 && value> 500) {
// Turn on LED
digitalWrite (Ledpin, HIGH);
} else {
// Turn off LED
digitalWrite (Ledpin, LOW);
}
// 100 ms delay
delay (100);
}
Try charging and playing with the potentiometer. You will see how it goes from being off to on and finally flashing.
In this chapter, we have seen one of the most powerful tools that programming languages have, the else if-else statements with Arduino. You have been able to verify that, although the loop () function is repeated over and over again very quickly and indefinitely, we can change the result using the if-else conditional statements with Arduino.
It is another tool in programming, but it is not the only one. This can help you control the temperature or water level with Arduino. In addition, it works in the same way on either another Arduino board or on an ESP8266. Moreover, in all programming languages, there are the if, if-else, and else if statements. By mastering the conditional sentences in Arduino, you will master the execution of your program.