Lesson 8
22 min
Data types, scope, if, for, while and switch to structure a program.
Definition
A variable is a location in the board's memory, identified by a name, that stores a value which can change while the program is running. Control structures(if,for,while,switch) are instructions that determine which lines of the program are executed and how many times, depending on the values of variables.
A variable is a location in the board's memory that stores a value. The Arduino programming language isstatically typed: you must specify the data type when declaring a variable. An Arduino Uno has very limited memory (2 KB of SRAM), so it is important to choose an appropriate type.
A declaration always follows the same pattern: the type, the name, optionally followed by the=sign and the initial value, and finally a semicolon. For example,int counter = 0;creates an integer variable namedcounterwhose initial value is 0.
true) or false (false).char letter = 'A';.String name = "Arduino";.int counter = 0;
float temperature = 21.5;
bool alarmActive = false;
const int ledPin = 13; // const: the value will never change
void setup() {
counter = counter + 1;
counter++; // equivalent to counter = counter + 1
counter += 5; // equivalent to counter = counter + 5
}
void loop() {
}You can choose your variable names freely, but there are a few rules to follow. A name can contain only letters, numbers, and underscores (_). It cannot begin with a number, and it cannot be a reserved keyword (such asintorfor). Also remember that the language is case-sensitive:counterandCounterare two different variables.
buttonPinis much clearer thanb.blinkDelay.const: the compiler will warn you if you accidentally try to modify them.Operators are used to perform calculations with variables and write conditions. There are three main categories:arithmetic, comparison, and logical operators.
+,-,*,/, and%(the remainder of integer division, called "modulo").==(equal to),!=(not equal to),<,>,<=, and>=.&&(AND),||(OR), and!(NOT).int a = 17;
int b = 5;
int sum = a + b; // 22
int remainder = a % b; // 2 (17 = 3 x 5 + 2)
int quotient = a / b; // 3 (integer division)
float exact = 17 / 5.0; // 3.4 (one number is a decimal)
bool test1 = (a > 10) && (b < 3); // false: b is not less than 3
bool test2 = (a > 10) || (b < 3); // true: only one condition needs to be true
bool test3 = !(a == b); // true: a and b are differentInteger Division
When dividing two integers, the result is also an integer: the decimal part is simply discarded.17 / 5gives 3, not 3.4. To obtain a decimal result, at least one of the two numbers must be afloat, as in17 / 5.0.
A variable declared outside functions is global: it exists throughout the program and retains its value from one iteration ofloop()to the next. A variable declared inside a function islocal: it is recreated each time the function is called.
int total = 0; // global: retains its value
void setup() {
Serial.begin(9600);
}
void loop() {
int currentIteration = 1; // local: recreated each iteration
total += currentIteration;
Serial.println(total); // 1, 2, 3, 4...
delay(1000);
}
loop()to the next (a counter or a state).static. A local variable declared withstaticretains its value between function calls while remaining inaccessible from other functions.Theif,else if, andelsestructures allow you to execute code depending on a particular situation. The condition is always written inside parentheses.
int level = 70;
if (level > 80) {
// high level
} else if (level > 40) {
// medium level
} else {
// low level
}The program tests the conditions in orderand executes only the first block whose condition is true. Here,levelequals 70: the first condition is false, while the second is true, so only the "medium level" block is executed. The finalelseblock is optional: it acts as a fallback when none of the conditions are true.
Logical operators allow you to test several things at once. With&&, both conditions must be true. With||, only one of the two conditions needs to be true.
int temperature = 28;
bool windowOpen = false;
// Both conditions must be true
if (temperature > 25 && windowOpen == false) {
Serial.println("It is hot: open the window!");
}
// Only one condition needs to be true
if (temperature < 10 || temperature > 35) {
Serial.println("Extreme temperature");
}A loop repeats a block of instructions. It avoids writing the same lines multiple times and allows the program to adapt to situations whose duration is not known in advance. There are two main types of loops.
// Blink 5 times
for (int i = 0; i < 5; i++) {
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
}
// Wait for a button press (pin 2 configured as INPUT_PULLUP)
while (digitalRead(2) == HIGH) {
// Do nothing until the button is pressed
}Inside the parentheses of aforloop, there are three parts separated by semicolons.
int i = 0, executed only once at the beginning.i < 5, checked before each iteration. As soon as it becomes false, the loop stops.i++, executed at the end of each iteration.In this example,itakes the values 0, 1, 2, 3, and 4, resulting in exactly 5 iterations. Starting at 0 is a very common programming convention.
Two keywords allow you to change how a loop behaves:breakimmediately exits the loop, whilecontinueskips the rest of the current iteration and moves directly to the next one.
void setup() {
Serial.begin(9600);
for (int i = 1; i <= 10; i++) {
if (i == 3) {
continue; // skip number 3
}
if (i == 7) {
break; // stop the loop at 7
}
Serial.println(i); // prints 1, 2, 4, 5, 6
}
}
void loop() {
}The Infinite Loop
If the condition of awhileloop never becomes false, the program remains inside the loop forever: the board may appear "frozen". Sometimes this is intentional (theloop()function itself runs repeatedly), but most of the time it is a mistake. Always make sure something can change the condition so that the loop can eventually stop.
When comparing the same variable against many specific values,switchis easier to read than a long series ofelse ifstatements. Remember to addbreakat the end of each case.
int mode = 2;
switch (mode) {
case 1:
// slow mode
break;
case 2:
// normal mode
break;
case 3:
// fast mode
break;
default:
// unexpected value
break;
}The keyworddefaultplays the same role aselse: it is executed when none of the cases match. Withoutbreak, the program continues into the next case instead of exiting theswitch. Remember that aswitchworks with integer values or characters, not withfloatorStringvalues.
The = vs. == Mistake
=assigns a value to a variable, while==compares two values. Writingif (a = 5)instead ofif (a == 5)is a classic mistake that may compile without an error but cause unexpected behavior.
Here is a small program that uses variables, a condition, and a loop together. A global variable counts the elapsed seconds. After 10 seconds, the LED on pin 13 blinks 3 times, and then the counter resets to zero.
const int ledPin = 13;
const int threshold = 10;
int seconds = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
delay(1000);
seconds++;
Serial.println(seconds);
if (seconds >= threshold) {
for (int i = 0; i < 3; i++) {
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
}
seconds = 0;
}
}
if /elseandswitchdetermine what to execute.forandwhiledetermine how many timesinstructions are repeated.=(assignment) with==(comparison).Exercise
forloop, then stops and waits for a button press before starting again.Exercise: Multiplication Table
forloop, display the multiplication table of 7 in the Serial Monitor, from7 x 1to7 x 10, only once insidesetup().Exercise: Mode Selection
modewith a value of 1, 2, or 3, and aswitchstatement to make an LED blink at three different speeds (slow, normal, fast). Each button press switches to the next mode, returning to mode 1 after mode 3.Go Further
%operator) and stops permanently usingbreakwhen the counter reaches 30.