Become a subscriber (Free)

Join 29,000 other subscribers to receive subscriber sale discounts and other free resources.
:
:
Don't worry -- youre-mail address is totally secure. I promise to use it only to send you MicroZine.

The Arduino For Loop

The Arduino for loop is one of those bread-and butter functions that you will use all the time in your code. Microcontrollers are good at repetitive tasks but instead of you writing out the same code many times the for-loop repeats a section of code a specific number of times.


Where to use for-loops

You can use for loops anywhere inside a function, so you can use them in the standard Arduino setup(), and loop() functions, and within your own functions.

The following example shows a for-loop that loops round printing the numbers 0 to 9. It is placed into the setup() function since you only want to perform the for-loop action one time - otherwise if you place it within the loop() function it repeatedly outputs information - making you head spin (try it and see)!

Copy the code into the Arduino IDE. Compile and run the program. Start the serial monitor to see the output.

This code shows an Arduino for loop example with the for loop itself within the setup() function. This is not the place you should normally use a for loop (you can though) - its only here to stop multiple output.

void setup (void) {

   Serial.begin(9600);

   Serial.println("Arduino for loop");
   for (int i=0; i<10; i++) Serial.println(i);
}

void loop(void) {
}

How the Arduino for loop works

The Arduino for loop provides a mechanism to repeat a section of code depending on the value of a variable. So you set the initial value of the variable, the condition to exit the loop (testing the variable), and the action on the variable each time around the loop.

Initialiser section: The initial value of the control variable.
Condition Section: The condition to stop the loop.
Iterator Section:
The loop variable action (increment or decrement).

These three elements are parameters to the for loop and are separated by semicolons:

for ( <initialiser code> ; <condition test expression> ; <iterator expression> ) {
   <body code>
}

Arduino Loop Counter Control Variable

The other important point about for-loops is that they need a loop control variable - in the example this is the variable i. This is used as a loop counter and is used to decide when to exit the loop.

The code shown previously is the standard way to write a for-loop in which the loop variable starts at zero and is incremented 10 times.
for (int i=0; i<10; i++) Serial.println(i);
Note The value of i goes from 0 to 9 which is 10 times round the loop.

Parameters of the Arduino for loop

Initialise

int i = 0;

First of all the variable i is created (if it does not already exist) and set to zero.

This section of the for-loop is only executed once at the beginning.

Test

i < 10;

Next the loop variable is tested. Here, if it is smaller than 10 then carry on - otherwise the loop is exited.

This is executed every time around the loop.

Iterator

i++;

The loop control variable (loop counter) is increased by one.

This is executed every time around the loop.

Arduino For loop Output

So the for-loop executes the code "Serial.print(i)" 10 times with value of i going through 0 to 9.

And this is the output:

Arduino for loop
0
1
2
3
4
5
6
7
8
9
To see why you start the control variable from zero you should look at the section on arrays and for-loops.

For a different way of doing a similar action you could write allow the control variable to change going through 1 to 10.
for (int i=1; i<=10 ; i++) Serial.println(i);
This would print out 1 through 10. It is still 10 iterations but starting from 1.

Arduino for-loop body code

The body of the for loop can either be a single statement of a block of code between curly braces. So you could write the loop as follows:

void setup (void) {

   Serial.begin(9600);

   Serial.println("Arduino for loop");
   for (int i=0; i<10; i++) {
      Serial.print("i is : ");
      Serial.println(i);
   }
}

void loop(void) {
}

Notice how there are two statements - ending in semicolons and both are enclosed by curly braces. Compare this to the previous example that used only one statement ending in a semi-colon.

In this case the output is:
Arduino for loop
i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
i is : 5
i is : 6
i is : 7
i is : 8
i is : 9

Test Yourself

Q: Here's a question for you. What is the value of i after the loop has finished executing?

The value of i is (click to find out) I has the value 10 since to stay in the loop i had to be smaller than 10. When i equals 10 the condition is met to exit the loop.

Q: Another question. Can you use i later on in the program?

Can I use the variable i later? (click to find out) Yes you can.

How to setup a count down for loop

You can create a for loop that counts down by changing all three parameters in the for loop. Lets say you want to count down from 10 to 1 (ten iterations round the loop).

void setup (void) {

   Serial.begin(9600);

   Serial.println("Arduino count down for loop");
   for (int i=10; i>=1; i--) {
      Serial.print("i is : ");
      Serial.println(i);
   }
}

void loop(void) {
}
Here's the count down output:
Arduino count down for loop
i is : 10
i is : 9
i is : 8
i is : 7
i is : 6
i is : 5
i is : 4
i is : 3
i is : 2
i is : 1

Test Yourself

Q: Here's the same question for you. What is the value of i after the loop has finished executing?

The value of i is (click to find out) I has the value 0 since i had to be greater than or equal to 1 to stay in the loop.

Arduino For loop Array Example

The reason that you start with the control loop variable at zero is that arrays are defined starting from index zero. If you don't use zero as an initial starting point then you can get an off by one error - meaning you can write to a array location that does not exist. For an array of 10 values only indices 0..9 are valid.

Here's an example of setting up an array initialising each element with a random number. Then printing out the array values in turn.

int myarray[10];

void setup (void) {

   Serial.begin(9600);

   for (int i=0; i<10; i++) myarray[i]= random(100);

   Serial.println("Arduino for loop");
   for (int i=0; i<10; i++) {
      Serial.print("i is : ");
      Serial.print(i);
      Serial.print(" array value is ");
      Serial.println(myarray[i]);
   }
}

void loop(void) {
}
Note: The random number output is not truly random unless you supply a seed value - that should also be from a random source - such as a button press capturing the millis() timer value - a truly random seed.

This is because the random data is created from an algorithm and if it starts from the same seed number all the values will repeat. If you run the program again you will see the same set of numbers. For this code it does not matter.

The randomness of the function is in the unpredictability of the number sequence.

Standard form of a for loop

The standard form of the for loop initialises the control variable to 0. For exiting the loop the condition tests whether the variable is smaller than the number of loops needed. You don't have to use this but it makes life easier when dealing with arrays.

TIP: it is best to use the standard form of the Arduino for-loop so that you never access an array value incorrectly. The standard form is this:
   for (int i=0; i<10; i++) {
      <block of code to execute>
   }


New! Comments

Have your say about what you just read! Leave me a comment in the box below.




Privacy Policy | Contact | About Me

Site Map | Terms of Use



Visit our Facebook Page:
To Visit Click Here


Recent Articles

  1. Arduino Interrupt : There are Some You May Never Have Heard About!

    Arduino Interrupt Tutorial: Find out how many external there are on an Arduino Uno - The answer is more than two!

    Read more

  2. Easy Switch Debounce

    Switch debounce: Three different ways to debounce input push switches with one amazing method that you can't miss.

    Read more

  3. How to use the ADS1115

    A tutorial on using the ADS1115 precision 16 bit ADC for low power use.

    Read more

  4. How to use the ADXL345 for movement sensing and more.

    With the ADXL345 acellerometer you can detect up to 16g! You can also find out how to use it for tap detection and more.

    Read more

  5. ESP8266 Webserver in Lua

    ESP8266 Webserver: This code shows you how to use lua to create a webserver using html button inputs to contrtol an LED on the ESP module.

    Read more

  6. ESP8266 NodeMCU Firmware: ESP8266 flash

    How to flash nodemcu firmware into a ESP8266 so you can use the LUA scripting language.

    Read more

Readers Comments

"I wanted to thank
you so so so much
for all the information
you have provided in
your site it's

SUPERB and FANTASTIC."

- Ranish Pottath

"This site really is
the best and my favorite.
I find here many useful
projects and tips."

- Milan

bursach<at>gmail.com<

"Awesome site,
very, very easy and nice
to navigate!"


- Matt
matt_tr<at>
wolf359.cjb.net


Learn Microcontrollers

"Interested in
Microcontrollers?"

Sign up for The
Free 7 day guide:

FREE GUIDE : CLICK HERE


"I am a newbie to PIC
and I wanted to say
 how great your
site has been for me."


- Dave

de_scott<at>bellsouth.net

"Your site is a great
and perfect work.
congratulations."


- Suresh

integratredinfosys<at>
yahoo.com

"I couldn't find the correct
words to define
yourweb site.

Very useful, uncovered,
honest and clear.

Thanks so much for
your time and works.
Regards."


- Anon

Back to Top