Welcome back to our programming tutorial using the Arduino IDE. Today we will cover the conditional if construct.
You can take a look at the previous chapters of the course here:
- Arduino IDE: arithmetic and logical operators #3
- Arduino IDE: variables, constants and macros #2
- How can I use Arduino IDE to write a program? #1
- Arduino IDE: what it is and how it works #0
The instructions for the problem solving procedure (algorithm) are organized according to schemes that can be classified into three fundamental constructs. Today we will analyze the the control structures.
The instructions are executed one after the other following the same order they were written.
The if structure is basically a binary alternative selection that allows you to choose between two possible program paths.You use the if statement whenever you need to execute an instruction following the occurrence of a certain condition.
The syntax is as follows:
1 2 3 4 5 |
If (condition) { instruction1 } else { instruction2 } |
If the condition is true, instruction1 is executed, otherwise (if the condition is false) instruction2 is executed.
Instruction1 and instruction2 can indicate, as happens in most cases, not just a single instruction but a group (block) of instructions.
The condition is a Boolean expression whose truth is assessed, the comparison and logical operators are then used (read Arduino IDE: arithmetic and logical operators #3 if the previous sentence does not make sense for you).
The ELSE attribute is an optional attribute of the IF statement. The ELSE attribute defines either one instruction, or or a block of instructions delimited by two braces.
Conditional if statements can be nested to create more refined control structures. Here is an example:
1 2 3 4 5 6 7 8 |
if (condition1){ if(condition2){ instruction1 } } else { if(condition3){ instruction2 } |
Each nested if block can be accompanied by the corresponding else if and else blocks. The Arduino IDE programming language standard recommends a theoretical limit of 256 nesting levels for flow control structures, which goes well beyond the limit imposed by common sense.
Here is a sample program template using a complete if structure taken from the Arduino page:
1 2 3 4 5 6 7 8 9 |
if (temperature >= 70) { // Danger! Shut down the system. } else if (temperature >= 60) { // 60 <= temperature < 70 // Warning! User attention required. } else { // temperature < 60 // Safe! Continue usual tasks. } |
In our next article we will explain you how to turn on a LED with a button, using the conditional if structure.
Previous articles:
- Arduino IDE: arithmetic and logical operators #3
- Arduino IDE: variables, constants and macros #2
- Arduino IDE: how can I use Arduino IDE to write a program? #1
- Arduino IDE: what it is and how it works #0
Follow us to keep yourself updated with the news!