CONTROL STRUCTURES
Arduino includes keywords for controlling the logical flow of your sketch.
if … else
This structure makes decisions in your program. if must be followed by a question specified as an expression contained in parentheses. If the expression is true, whatever follows will be executed. If it's false, the block of code following else will be executed. It's possible to use just if without providing an else clause.
Example:
if (val == 1) {
digitalWrite(LED,HIGH);
}for
Lets you repeat a block of code a specified number of times.
Example:
for (int i = 0; i < 10; i++) {
Serial.print("ciao");
}switch case
The if statement is like a fork in the road for your program. switch case is like a massive roundabout. It lets your program take a variety of directions depending on the value of a variable. It's quite useful to keep your code tidy as it replaces long lists of if statements.
Example:
switch (sensorValue) {
case 23:
digitalWrite(13,HIGH);
break;
case 46:
digitalWrite(12,HIGH);
break;
default: // if nothing matches this is executed
digitalWrite(12,LOW);
digitalWrite(13,LOW);
}while
Similar to if, this executes a block of code while a certain condition is true.
Example:
// blink LED while sensor is below 512
sensorValue = analogRead(1);
while (sensorValue < 512) {
digitalWrite(13,HIGH);
delay(100);
digitalWrite(13,HIGH);
delay(100);
sensorValue = analogRead(1);
}do … while
Just like while, except that the code is run just before the the condition is evaluated. This structure is used when ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access