XXL Kit for Arduino · Programming

Part 3 Your first code: if, loops, switch

  • Beginner
  • Ages 8+
  • about 45 min

Before you connect your first LED in Part 4, it is worth writing a few programs in which nothing blinks or buzzes. Instead, the board “talks” to you in text. In this part you will meet the four building blocks that every program in this series is made of: if, for, while and switch. You do not need a single part from the kit: the R3 board, the USB cable and the FlashESP platform from Part 2 are enough.

Who is it for? For complete beginners in programming, aged 8 and up, and for teachers who want to keep learning the code itself apart from connecting wires. If you have programmed before, you can skip this part and go straight to Part 4.

01

The skeleton of a program and Serial

Every program for the R3 board looks the same on the inside. Two functions: one for the start, the other round and round.

  • setup() runs once, right after the power is turned on. This is where you get everything ready.
  • loop() runs without end, until you disconnect the power.

Both have to be in the program, even if one of them is empty.

void setup() {
  // code that runs once
}

void loop() {
  // code that repeats without end
}

To see anything at all, the program needs a way to talk to you. That is what Serial is for: a text channel between the board and the computer. You turn it on with one line in setup():

void setup() {
  Serial.begin(9600);                   // turn on the Serial channel, speed 9600
  Serial.println("The program has started");
}

void loop() {
}
  • Serial.begin(9600) starts the channel. The number 9600 is the speed. The Serial Monitor of FlashESP has to be set to the same speed.
  • Serial.println("...") prints text and moves to a new line.
  • Serial.print("...") prints text without moving to a new line. It comes in handy when you join a label to a number.

Now something that repeats. Every second the program adds 1 to a variable and prints its value:

int counter = 0;             // a "box" for a whole number, 0 at the start

void setup() {
  Serial.begin(9600);
}

void loop() {
  counter = counter + 1;     // take what is in the box, add 1, put it back
  Serial.print("Counter: ");
  Serial.println(counter);
  delay(1000);               // wait a second - without this, thousands of lines flood the monitor
}

int counter = 0; creates a variable: a named place for one number. int means “whole number”, with nothing after the decimal point. Writing counter = counter + 1 means: “work out counter + 1 and save the result back in counter”.

The rule for this whole part: code whose result you want to see once goes into setup(). Code that should repeat goes into loop(), always with some delay(), so that you can keep up with reading what the board prints.

02

if / else: decisions

The program stops doing the same thing every time. It starts to look at a value and choose.

void setup() {
  Serial.begin(9600);

  int temperature = 25;      // change this number and flash the program again

  if (temperature > 30) {
    Serial.println("Hot");
  } else if (temperature < 10) {
    Serial.println("Cold");
  } else {
    Serial.println("Just right");
  }
}

void loop() {
}

if (condition) { ... } runs the code in the curly braces only when the condition is true. else catches all the other cases, and else if lets you check another condition on the way.

A condition is a sentence that is either true or false. You read code like a sentence, from left to right, and every sign has its own word:

What you writeHow we read it aloud
a == b“a equals b”
a != b“a is not equal to b”
a > b“a is greater than b”
a < b“a is less than b”
a >= b“a is greater than or equal to b”
a <= b“a is less than or equal to b”
a && b“a and b” – both sides must be true
a || b“a or b” – one side is enough
!a“not a” – turns true into false and false into true

The most common mistake: == is a comparison, = is an assignment. if (x = 5) does not check whether x is 5. It puts 5 into x and always runs.

You join several comparisons into one sentence with the linking words && (“and”) and || (“or”):

  int hour = 14;

  if (hour >= 8 && hour <= 16) {
    Serial.println("Working hours");
  } else {
    Serial.println("After hours");
  }

Read this condition aloud. Go word by word, from left to right:

if (hour >= 8 && hour <= 16)

we read: “if hour is greater than or equal to 8 and hour is less than or equal to 16”. In plain words: if the hour is between 8 and 16. When the whole sentence is true, the code in { } under if runs. When it is false, the code after else runs.

You read || the same way: if (day == 6 || day == 7) is “if day equals 6 or day equals 7”, which means if it is Saturday or Sunday. Treat the parentheses ( ) as in math: first work out what is inside them.

03

for: a loop with a counter

For when you know in advance how many times something should repeat.

void setup() {
  Serial.begin(9600);

  for (int i = 1; i <= 10; i = i + 1) {
    Serial.print("Number ");
    Serial.print(i);
    Serial.print(" times 5 = ");
    Serial.println(i * 5);
  }

  Serial.println("End of the loop");
}

void loop() {
}

Inside the parentheses of for there are three parts separated by semicolons. First read the whole thing like a sentence:

for (int i = 1; i <= 10; i = i + 1)

we read: “start with i equal to 1; repeat while i is less than or equal to 10; after every round increase i by 1”.

And now each part on its own:

  1. 1int i = 1 is the start: you create the variable i and set it to 1.
  2. 2i <= 10 is the condition: the loop keeps going round as long as it is true.
  3. 3i = i + 1 is the step: it runs after every round. Here i grows by 1.

For every number from 1 to 10 this program prints the result of multiplying it by 5. That is the whole 5 times table. Change 10 to 20 and i * 5 to i * 7, and you get the 7 times table for numbers up to 20.

A shortcut: instead of i = i + 1 people almost always write i++. It means exactly the same thing.

04

while and do…while

For when you do not know in advance how many rounds there will be. You only know when to stop.

void setup() {
  Serial.begin(9600);

  int number = 1;

  while (number < 1000) {     // repeat WHILE number is less than 1000
    Serial.println(number);
    number = number * 2;      // double it - without this line the loop would never end
  }

  Serial.println("We have passed 1000");
}

void loop() {
}

while (condition) { ... } repeats the code as long as the condition is true. The most important thing: something inside the loop has to bring the condition closer to false. Here number doubles, so sooner or later it passes 1000 and the loop ends. If that line were missing, the program would be stuck forever and the Serial Monitor would fall silent. It is one of the most common ways to “hang” a board.

The variant do…while checks the condition at the end, so the code inside runs at least once:

  int x = 50;

  do {
    Serial.println("This runs at least once");
    x = x + 10;
  } while (x < 20);          // the condition is false right away, but the body still ran once

In practice do…while is rare. When in doubt, use while.

05

switch / case: choosing from a list

Instead of a long ladder of else if: one value and many ready answers.

main.ino
void setup() {
  Serial.begin(9600);

  int choice = 2;            // change it to 1, 2, 3 or something else and flash again

  switch (choice) {
    case 1:
      Serial.println("Option 1 chosen");
      break;
    case 2:
      Serial.println("Option 2 chosen");
      break;
    case 3:
      Serial.println("Option 3 chosen");
      break;
    default:
      Serial.println("Unknown option");
  }
}

void loop() {
}

Write this program in your browser

Tutorial on the left, editor on the right. Build your code and flash it to the board in one click, with nothing to install.

switch takes one value and jumps to the matching case. default catches everything that does not match any case. It works like else.

A trap: the break at the end of every case is a must. Without it, after running one case the program “falls through” to the next one and runs its code too. default does not need a break, because it comes last.

When switch, and when if? switch works well when you compare one variable with a few specific values. When the condition is complex (hour >= 8 && ...), stay with if.

The Serial Monitor of FlashESP can also send text to the board: you type it into the field “Type a message for the board” and click “Send”. So you can go further: Serial.read() reads the character you sent, and switch reacts to each one differently. Choose “No line ending” next to the field then: otherwise a newline character follows every character you send, and the second time round switch ends up in default.

06

Run it and see the result in the Serial Monitor

Code that has not been flashed is only text. Here is the full loop: paste, build, flash, read.

  1. 1Connect the R3 board to the computer with the USB cable and switch this part to Code mode, on a computer, in Chrome or Edge (Part 2).
  2. 2Paste or type one of the programs from this part into the editor. The editor saves the code on its own.
  3. 3Below the editor, open the Serial Monitor tab, check that the speed is 9600 baud, click Connect and choose the port of the board.
  4. 4Click Build & flash. The monitor pauses while the board is flashed, and when the green message “Done. Your program is running on the board.” appears, it connects again on its own.
  5. 5Go back to the Serial Monitor tab: from now on you see everything the program sends through Serial. To see once more what the program printed in setup(), click the button with a circular arrow (“Restart board”) in the monitor. It works like the reset button on the board.

If the Serial Monitor is empty, check that setup() contains Serial.begin(9600) and that the monitor is set to 9600 too. If you see “gibberish” instead of text, the speeds do not match. And if the program did not build, you see a list of errors below the editor: click an error to go to its line.

Build checklist

Tick them off one by one. Your progress is saved in this browser.

0 / 12

Before you flash
After flashing
If something is not right

Rules worth remembering

  1. 1

    = is not ==.

    One sign assigns a value, two compare. if (x = 5) always runs. It is the classic beginner's mistake.

  2. 2

    Every loop needs a way to end.

    In a while the condition has to become false in the end, otherwise the board gets stuck and the Serial Monitor falls silent.

  3. 3

    break after every case.

    Without it switch “falls through” to the next options and runs their code.

  4. 4

    Serial.begin(9600) and the same speed in the Serial Monitor.

    Otherwise: nothing, or gibberish.

Projects

None of them needs a part from the kit: the R3 board, USB and FlashESP are enough. They go from the easiest to the most ambitious.

  1. 1

    Even or odd

    Easy
    What you will use
    for + if
    What you will learn
    using the remainder of a division (number % 2) and making decisions inside a loop
  2. 2

    The full multiplication table

    Easy
    What you will use
    for inside for
    What you will learn
    using a nested loop: one loop counts the rows, the other the columns
  3. 3

    Countdown to launch

    Easy
    What you will use
    while + delay
    What you will learn
    writing a loop that ends after a known number of steps, and using time gaps
  4. 4

    A calculator for two numbers

    Medium
    What you will use
    switch + variables
    What you will learn
    choosing the operation (+, -, *, /) with a variable set in the code
  5. 5

    A mini quiz with points

    Challenging
    What you will use
    if + switch + variables
    What you will learn
    putting everything together: checking answers and counting the score

Summary

if, for, while and switch are the complete set. Every program in this series, from blinking an LED to the robot arm in Part 8, is these four building blocks arranged around readings from the pins. The rest is details. If these examples work in your Serial Monitor and you understand why, you are ready for Part 4 and your first real circuit.