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 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.
Note: The value of 'i' after the loop is completed is 10. A little bit counter intuitive, but to stay in the loop, 'i' can only range from 0 to 9, at 10 it exits. You can use the 'i' variable in later code as well.

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 allow the control variable to change from 1 through 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.

Note: Here 'i' ranges from 1 to 10.

Note: At the end of the loop 'i' has the value 10 - the same as before.

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<7; 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

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 7 since to stay in the loop 'i' had to be smaller than 7. When i equals 7the 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.

Note: Note: Even if the array position does not exist, the loop will still write data to that location - meaning you are overwriting other variables - an extremely bad idea!

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) {
}
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>
   }

Initialising the For Loop

In the examples above the for-loop initialisation code is used as follows:
int i=0;
This is a C++ way of both declaring a loop variable and initialising it.

In C code you will find the following code:

This is because you can't initialise variables anywhere but at the beginning of a function. So this is the type of code you will find:

void myFunction(void) {
int i;

   for(i=0;i<10;i++) {
      Serial.println(i);
   }

   for(i=10;i>0;i++) {
      Serial.println(i);
   }
}


Note: You can use either form in C++ code.


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. Digispark Attiny85 Easy IDE install and setup

    Digispark ATtiny85: Essential information on setting up and using this tiny, but powerful, chip

    Read more

  2. Magnetometer tilt compensation

    How to make magnetometer tilt compensation work for a magnetometer such as a QMC5883L using an ADXl345 accelerometer.

    Read more

  3. How the HMC5883L 3-axis digital magentomter works

    HMC5883L - How make a digital compass, Find out the differences between the HMC5883L and the QMC5883L and whether they are compatible.

    Read more

  4. Arduino absolute value - abs() - secrets revealed...

    Secrets of Arduino absolute value abs() - Why it might fail, Why it may cause problems...and how to fix it.

    Read more

  5. Arduino Analog Output...Easy analog output generation

    Arduino Analog Output: How to create the most accurate PWM analog ouput and how to create analog PWM sine waves.

    Read more

  6. ACS758 secrets...

    Using the ACS758 to measure very high current

    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