Lesson 8 / 1267%

Lesson 8

Variables, Conditions and Loops

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.

Variables and Their Types

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.

  • int: an integer ranging from -32,768 to 32,767.
  • long: a large integer (approximately plus or minus 2 billion), useful for durations expressed in milliseconds.
  • float: a decimal number written using a decimal point (3.14).
  • bool: true (true) or false (false).
  • byte: a small integer ranging from 0 to 255.
  • char: a single character enclosed in single quotes, for examplechar letter = 'A';.
  • String: text, for exampleString name = "Arduino";.
variables.ino
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() {
}

Choosing a Good Variable Name

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.

  • Choose a name that describes the variable's purpose:buttonPinis much clearer thanb.
  • The camelCase convention means writing the first word in lowercase and capitalizing the first letter of each following word:blinkDelay.
  • For values that never change (pin numbers, fixed durations), useconst: the compiler will warn you if you accidentally try to modify them.

Operators

Operators are used to perform calculations with variables and write conditions. There are three main categories:arithmetic, comparison, and logical operators.

  • Arithmetic:+,-,*,/, and%(the remainder of integer division, called "modulo").
  • Comparison:==(equal to),!=(not equal to),<,>,<=, and>=.
  • Logical:&&(AND),||(OR), and!(NOT).
operators.ino
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 different

Integer 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.

Scope: Local and Global Variables

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.

scope.ino
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);
}
Diagram: a global variable (permanent shelf) compared with a local variable (object discarded at the end of the function).
  • Use a global variable when a value needs to be remembered from one iteration ofloop()to the next (a counter or a state).
  • Use a local variable for intermediate calculations: it does not clutter the rest of the program and releases its memory when the function finishes.
  • Useful keyword:static. A local variable declared withstaticretains its value between function calls while remaining inaccessible from other functions.

Conditional Statements

Theif,else if, andelsestructures allow you to execute code depending on a particular situation. The condition is always written inside parentheses.

conditions.ino
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.

Combining Multiple Conditions

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.

combined_conditions.ino
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");
}

Loops

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.

  • for: repeats a block a known number of times.
  • while: repeats a block as long as a condition remains true.
loops.ino
// 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
}

Anatomy of a for Loop

Inside the parentheses of aforloop, there are three parts separated by semicolons.

  • Initialization:int i = 0, executed only once at the beginning.
  • Condition:i < 5, checked before each iteration. As soon as it becomes false, the loop stops.
  • Increment: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.

Stopping or Skipping an Iteration

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.

break_continue.ino
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.

Using switch for Multiple Cases

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.

switch.ino
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.

Putting It All Together: A Threshold Counter

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.

threshold_counter.ino
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;
  }
}
Screenshot: the Serial Monitor displaying the counter from 1 to 10, with the LED blinking three times at the end.

Key Takeaways

  • A variable has a type, a name, and a value. Choose the smallest suitable type because memory is limited.
  • A global variable retains its value throughout the program, while a localvariable disappears when its function finishes.
  • if /elseandswitchdetermine what to execute.
  • forandwhiledetermine how many timesinstructions are repeated.
  • Never confuse=(assignment) with==(comparison).

Exercise

Write a program that makes an LED blink exactly 10 times using aforloop, then stops and waits for a button press before starting again.

Exercise: Multiplication Table

Using aforloop, display the multiplication table of 7 in the Serial Monitor, from7 x 1to7 x 10, only once insidesetup().

Exercise: Mode Selection

Use a global variablemodewith 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

Write a program that turns on the LED only when a counter's value is a multiple of 3 (hint: use the%operator) and stops permanently usingbreakwhen the counter reaches 30.