Page 1 of 1

Arduino Programming for Beginners – Part 5: Going in Loops

Arduino Programming for Beginners – Part 5: Going in Loops
   4

In this article we will talk about loops. Loops are used for going through programming instructions for a defined or undefined number of times, so that we do not have to write the same statement over and over again. We will look at “for”-loops, “while”-loops and “do … while …”-loops.

This is the fifth part of a series of articles I’ve written to get beginners started with Arduino Programming in the programming language C, which I’ve written with the intend to teach my 13 year old nephew (Bram) to get started with the Arduino. After all, he wants to build a robot, but without some basic knowledge about programming, he won’t get far ….

Besides an introduction into the language C, the default language used for Arduino Programming, “Arduino Programming for Beginners” will also touch topics like how to setup an Arduino, get a developers environment running, and look at a few basic electronic parts which we connect to our Arduino.




Overview of this Chapter

  A complete overview of this course can be found here: Course Overview.

The purpose of Loops

Before we start working with loops, we should probably understand when and where we would be using loops.

The most common application is when we have to repeat a certain set of instructions repeatedly, either based on conditions or based on counting.

Say we have 5 lights, each with their own switch. To turn all light ON, we have to:

Switch light 1 ON,
Switch light 2 ON,
Switch light 3 ON,
Switch light 4 ON,
Switch light 5 ON.

So we repeat the same instruction (switch light ON), for each of the 5 lights.
We could also write this as:

Count from 1 to 5, and for each of the numbers, Switch Light ON.

Tada! We’ve just made a loop, which saves us writing down the (almost) same sentence over and over again.

Can you imagine how much typing that would save us if we would have to count to 1,000 ?
It’s not just for our typing that this saves space – your source code will be shorter and easier to read, but also the compiled program for the Arduino will be much smaller, and maybe even faster. A bonus is that when we have to change our code to more or less lights, we simply modify one single number.

Loops are used to repeat certain instructions repeatedly

Quite often, variables are used for counting, so our previous statement could be:

Count for A = 1 to 5
   switch light A on

Writing program code like that is also called “Pseudocode“.
Pseudocode is basically writing a program (on paper for example) is a more human like language, yet using “constructs” that look like the ones we use in our programming language of choice. We cannot use this pseudocode in our program, but it helps writing down the steps we want to take in our program, or to explain code in a more human readable way.
If you’d like, you can forget about the lingo right away though.

The “for” loop

The “for” statement is one of those statements that we can use to create a loop. We “count” and counting is done with whole numbers!
Without knowing it, you already kind-a encountered it just now.

Count for A = 1 to 5
   switch light A on

If we write this down in a more complex way:

for A = 1, and A should be less than or equal to 5, increase A by one each time
   switch light A on

This is how a for-loop works in the C language that we use for Arduino Programming, and in code this could look like this:


for(A=1; A<=5; A++) {
  Serial.print("Switch lights on for light ");
  Serial.println(A);
}

Let’s take a closer look at this.

Obviously we use the statement “for”. The parameters we need to give the “for” statement are:

  • Start with “A = 1”
  • Keep in mind that “A <= 5”
  • For each time we go through the loop, increase A by one (A++)

 

Counting in a “for” loop can only be done with whole numbers (byte, int. long, etc),

or in other words: a data type than can be enumerated (counted in whole numbers and with fixed increments).

Since we just called those parameters, we need to put round brackets around them, as we have seen with other functions that get parameters (like for example Serial.print() ).

The next thing you will see is that we create an accolade enclosed code block – the same way we have seen it with the “if” statement.

Anything in that code block will be repeated as long as the conditions are being met for the “for” loop.

You will have to keep in mind that the “A++” is one of those confusing Compound Operators as we have seen in Part 3.
“A++” means: “increase the value of A by 1 and return the old value of A“.
This effectively means that we work with the “old” value of “A” in the code block, but once the code block has been completed, A will assume the new (increased) value.
Now you know why I am not a fan of using these compound operators – especially in the beginning they can be very confusing.

Stick with the rule that the compound operators
++” (counting UP) or
––” (counting DOWN)
are always placed behind the variable in a “for” loop.

Did we just say “counting down”? Yes we did!
A “for” loop can also count down, by using the “––” compound operator. If we would take our previous example, but instead of counting from 1 to 5, we now want to count down from 5 to 1, then our code would look like this:


for(A=5; A>=1; A--) {
  Serial.print("Switch lights on for light ");
  Serial.println(A);
}

Note that we now start with “A = 5”, and want A to be greater than or equal to 1. After all, we’re counting down in this example.

Now one thing we have overlooked so far … the definition of our variable A.

One way we can define “A”, is our usual variable definition (before the loop): int A;


int A;

for(A=1; A<=5; A++) {
  Serial.print("Switch lights on for light ");
  Serial.println(A);
}

The other way is defining “A” in the “for” statement, which is ideal if we only use “A” in the loop and would not need it anywhere else – remember that topic about “scope”? This is done as such in code:


for(int A=1; A<=5; A++) {
  Serial.print("Switch lights on for light ");
  Serial.println(A);
}

Notice that we typed “int A” inside the for parameters?
This is a relatively common method, but you have to keep in mind that if we define our variable in the “for”-statement, that it will only be known in the code block of the “for” statement. This is the “scope” principle we talked about earlier.

If we would try the following code, your Arduino compiler will give you an error message “error: ‘A’ was not declared in this scope“.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  for(int A=1; A<=5; A++) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
  }

  Serial.println(A); // this is the line that produces an error!
}

void loop() {
  // leave empty for now
}

Remember the “Scope” of a variable, as discussed in Part 3?
The “scope” of “A” will be the “for”-loop’s code block. So “A” is an unknown variable in line 10, meaning it’s undefined (declared).

The variable for our “for”-loop can be defined in the “for” statement,

however it’s scope will be limited to the code block of the “for”-loop!

If the variable of a “for”-loop was not defined, the Arduino will define it
anyway, as if it was defined in the “for”-loop. It is however good practice to properly define the variable either before the loop, or in the “for” statement.

So pay attention if the variable was defined up front, and/or if the variable is needed outside of the loop!

Let’s put all of this in a working example that we can run on our Arduino.
I’ve included both counting up and a counting down in this example:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  Serial.println("Counting:");
 
  for(int A=1; A<=5; A++) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
  }

  Serial.println("Count down:");

  for(int A=5; A>=1; A--) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
  }
}

void loop() {
  // leave empty for now
}

The output would look something like this:

Counting:
Switch lights on for light 1
Switch lights on for light 2
Switch lights on for light 3
Switch lights on for light 4
Switch lights on for light 5
Count down:
Switch lights on for light 5
Switch lights on for light 4
Switch lights on for light 3
Switch lights on for light 2
Switch lights on for light 1

In the code block, we can read and use the variable we’ve used for the “for”-loop (A). We can, unlike some other programming languages, even change the value of A in this loop – although I would not recommend that, unless you have some more experience with the “for” loop and know what you’re doing.

Let’s say we would assign a new value for A in the loop for the regular counting, by changing the loop to:


1
2
3
4
5
  for(int A=1; A<=5; A++) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
    A = 7;
  }

Then our output would become:

Counting:
Switch lights on for light 1
Count down:
Switch lights on for light 5
Switch lights on for light 4
Switch lights on for light 3
Switch lights on for light 2
Switch lights on for light 1

Going through the code, we start a loop, where we start with A being 1. We execute the code block, but in this code block we set A to 7, which is greater than 5. So when we go through the next step (iteration) of the loop. The “for”-loop will now see that A = 7 and therefor no longer <=5 and will consider the loop “to be done” and will exit.
That’s why we see only one line for the regular counting loop.

Every single time we go through the loop, is called an “iteration“,
so our example has 2 “for” loops, each with 5 “iterations“.

Now can you image what would happen if you’d make a mistake, and instead of “A = 7”, you would have typed “A = 1”?
The loop will continue for ever – an effect that we might not want to see in our program, as it will never exit the loop and all the following code will be ignored.

Changing the variable of a loop, in the loop, is a bad idea !

If you’d like to stop a “for”-loop in the middle of running, you can use the “break” statement.
“break” is used for exiting out of a loop, just as we have seen with “switch”. It will work for “for”-, “while”- and “do … while …”-loops.

You can exit a loop with the “break” statement.

For example:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  for(int A=1; A<=5; A++) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
    if(A==3) {
      break;
    }
  }
}

void loop() {
  // leave empty for now
}

 

Now we have seen a simple example, counting 1 to 5 and 5 down to 1. We do not have to start with 1 though. It’s quite common to actually start with zero (0), but you can start with any number you’d like.

The “conditions” in the “for”-loop do not need to be fixed numbers either. Remember that variables can be used to replace a value in your code. So the following would work as well:


 int Start = 1;
 int Stop  = 5;

 for(int A=Start; A<=Stop; A++) {
   Serial.print("Switch lights on for light ");
   Serial.println(A);
 }

This would be a good time to do a little experimenting with your code. Change some values, make some mistakes, and get more familiar with those “for”-loops.

“while” loops

Now we have seen the “for”-loop with predefined “ranges” in which we “count”. But we can also create loops where counting is not used at all. Think about something like this:

While it’s Dark outside, lights to ON.

There is no counting involved here, so we can’t really solve this with a “for”-loop (naturally, there are tricks to accomplish this with a “for”-loop anyway, but if you’d like to program well, then that should not be the way to do it). This is where the “while” loop comes in play, I’m sure you already guessed that based on how I wrote down the example.

While DarkOutSide
  LightsOn

So this loop will first check if it’s dark outside. If that is the case (the condition results in true) then we execute the code block (LightsOn). Once executed, we repeat these steps again and again and again, until the condition results in a false which causes the loop to be exited.

A “while” loop will first check if the condition is true
and if so, executes the code block and repeats the loop,
until the condition is false and the loop is exited.

You could see it as an endless repeating “if” check. It keeps repeating, as long as the condition is true, versus the “if” statement, which runs through the code only once if the condition is being met.

When doing Arduino Programming in the C language, this would look something like this:


while (DarkOutside==true) {
  Serial.println("Lights ON");
}

As long as DarkOutside” == true, your Arduino will keep printing “Lights ON”.

We could also rewrite this as seen below. After all, the variable “DarkOutside” knows only 2 values, true or false, which makes it a boolean.


while (DarkOutside) {
  Serial.println("Lights ON");
}

That trick will not work when you’re working with numbers or text of course as they will have more possible values.

There is however a little thing we should pay attention to …
When (in this code) will the value of DarkOutside change?
After all, if “DarkOutside” never changes, the “while”-loop will continue for ever …

There are 2 possible ways to change the value of “DarkOutside” …

The first way is because we change a value in the code block. For example a calculation. This way we can actually mimic the “for”-loop. Here is an example:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  // define our variable
  int A = 1;

  while(A<=5) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
    A = A + 1;
  }
}

void loop() {
  // leave empty for now
}

This will do the same thing as (and you can see that the “for”-loop seems more efficient):


1
2
3
4
5
6
7
8
9
10
11
12
13
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  for(int A=1; A<=5; A++) {
    Serial.print("Switch lights on for light ");
    Serial.println(A);
  }
}

void loop() {
  // leave empty for now
}

The other way of changing the value is by influence from outside – for example by reading a sensor, or a switch.

Now, we haven’t done anything with those yet, and since reading a switch requires a little bit more work, we will save that for a later time.

Keep in mind that when the condition of the “while” loop is NOT met,
the loop will be exited! Don’t forget!

“do … while …” loops

The “do … while …” loop is another loop we can use, which is basically the same as the “while” loop, we just swap the order in which things are done. We first do something and then check a condition. If the condition is met, we will go through it again. If the condition is not met, then we’re done with the loop.

A “do … while …” loop will first execute the instructions in the code block
and after that check if the condition is true.
If true, the loop will be repeated.
If false then we exit the loop.

The notation is a little different from the “while” loop:


  do {
    // do something
  } while (condition);

We see that we start with the “do” statement, followed by the code block, and finished with a “while” statement.

An application for this type of loop is for example if we need to calculate something, and repeat the calculation until the condition of “while” is no longer met.

Here an example of both a “while”-loop and a “do … while …”-loop doing the same thing:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void setup() {
  // set the speed for the serial monitor:
  Serial.begin(9600);
 
  int A = 1;

  while(A<=5) {
    Serial.println("WHILE: A is still <= 5");
    A = A + 1;
  }

  A = 1;

  do {
    Serial.println("DO WHILE: A is still <= 5");
    A = A + 1;    
  } while (A<=5);
}

void loop() {
  // leave empty for now
}

The output will look like this:

WHILE: A is still <= 5
WHILE: A is still <= 5
WHILE: A is still <= 5
WHILE: A is still <= 5
WHILE: A is still <= 5
DO WHILE: A is still <= 5
DO WHILE: A is still <= 5
DO WHILE: A is still <= 5
DO WHILE: A is still <= 5
DO WHILE: A is still <= 5

Things can go horribly wrong with the “do … while …”-loop, mostly because we check the condition after we executed our code block. Can you imagine what would happen if we changed lines 5 and 12 to: A = 10; ?

The “while”-loop will not execute. Which is good.
The “do … while …”-loop however WILL execute the first iteration and display (wrongfully): “DO WHILE: A is still <= 5”.

Using either of these loops, be careful that it does what your expect it to do!

  • Check first and do later?  (while-loop)
  • Do first and check later? (do-while-loop)

 

This means that we have to watch it when to use “while” or “do … while …”, I suspect that the “while”-loop is the most common used.

 

If you have questions, just ask them below in the comment section, and keep in mind: There are no stupid questions! We all had to start at some point!

Next chapter: Arduino Programming for Beginners – Part 6: Functions

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are 4 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Feb 10, 2017 - 4:48 PM - Stan Comment Link

    Wow… fortunatelly we have come to code ;

    for(A=1; A<=5; A++) {

      Serial.print(“Switch lights on for light “);

      Serial.println(A);

    }

    Thats my golden code for my arduino project..wow i cant believe i m in this chapter. I m so happy. My friend i m planing to print ur all chapters like a book and read them everyday and keep as my No1 source.. my friend you are Golden!

    Reply

    Stan

    • Feb 11, 2017 - 11:56 AM - hans - Author: Comment Link

      Hi Stan!

      I’m very happy that you’re enjoying these articles – at least it gives me a good feeling that I didn’t write it for nothing 
      Keep it up!

      Reply

      hans

  • Dec 7, 2018 - 9:36 PM - DANIEL Comment Link

    This is just as if i was reading a novel.

    very easy to comprehend.

    now i have a site to visit if i encountered any problem

    thank you.

    Reply

    DANIEL

    • Dec 8, 2018 - 7:40 AM - hans - Author: Comment Link

      Hi Daniel,

      I never considered myself a write, but I’m very happy with your compliment! 
      Thanks for the motivation! 

      Reply

      hans



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.