Arduino While loop: How you can use this loop in Two Different Ways. There are two forms of this loop construct which make it easier than using the for-loop. Plus, how you can create an infinite while loop.

The Arduino While loop:

  • Is an alternative looping syntax to the for-loop syntax.

  • Is simpler than the for-loop syntax.

  • Has an alternate form: the do...while loop.

The while loop is another loop control structure that lets you conditionally repeat a block of code. It is different from the for loop discussed here in that it does not have the initialiser or incrementer sections - you set these up outside the while loop using normal variable intialisation and you increment the varible anywhere within the loop block.

The most useful aspect of this loop construct is that it provides implementation of two easy concepts that you may want to use when writing code:

  1. Execute code until a variable reaches a set value.
  2. Always execute code first then test a variable for the exit condition.

It is true that you can use the for-loop to do both of these actions - but it is far easier to use the while loop construct because you don't have to think about "how to do it"! The structure of the code i.e. order of the words "while" and "do" defines these concepts.

The While loop

The while keyword uses the expression (within the parentheses following the the while keyword) as a control. If the expression is true (not zero) then the block of code that follows the expression is repeated.

    while ( <conditional expression> )
    {
       < Block of code to execute>
    }

Note: When the expression is true, the code block repeats indefinitely.

The only way to exit the loop is if the conditional expression changes - that means you have to use a variable or input pin value that allows the expression to become zero at some point. Otherwise you stay in the loop!

The do while loop

There is an alternative form of the while loop called the do-while loop and this is different to the while loop, only in the fact that it always executes the block of code at least once regardless of the conditional expression.

    do
    {
       < Block of code to execute>
    } while ( <conditional expression> )

Note: The do while loop is always run at least once.

This is often useful when you must perform some code but then want to test to see if you should carry on repeating it.

Arduino While loop examples

While loop example 0 to 9

In the for loop tutorial a variable was incremented 10 times and the value printed out. You can do the same operation using the while loop.

Here's the code from the for loop example

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

Here's the new sketch for using the while keyword:

void setup (void) {
int i=0;

   Serial.begin(9600);

   Serial.println("Arduino while loop 0~9");

   while(i<10) {
      Serial.println(i);
      i++;
   }
}

void loop(void) {
}

Here is the output from the sketch

Arduino while loop
0
1
2
3
4
5
6
7
8
9

You can see that the same operation is achieved and you can also see that the same elements are used in the for loop:

Parameter
Example
Difference to for loop code.
Initialiser: int i=0;Placed before the while keyword.
Condition: i<10;Placed in parenthesis after the while keyword.
Iterator:
i++;Placed within the body code.

They are just spaced out differently within the code.


Arduino While loop example 1 to 10

By moving the iterator (i++) you can change the output as a sequence from 1 to 10 - this is easier than the for loop logic as you don't need to think of the conditional i.e. should it be >=10, <11 etc. In fact the for loop for iterating 1 through 10 would be:

for (int i=1; i<=10; i++) Serial.println(i);

But you have to think about it when you use a for-loop!

Here's the while loop Sketch for values 1 through 10:

void setup (void) {
int i=0;

   Serial.begin(9600);

   Serial.println("Arduino while loop 1~10");

   while(i<10) {
      i++;
      Serial.println(i);
   }
}

void loop(void) {
}

The only change from the 1st example (0~9) is to move the line i++ before the body code (here Serial.println).

While loop 1-10 output

Arduino while loop
1
2
3
4
5
6
7
8
9
10

Arduino While loop example 9 to 0

To output a sequence from 9 down to 0 you must initiailise the loop value to the 1st output value you want before reaching the while statement; in this case variable 'i' is initialised to 9.

You also need to change the conditional in the while statement to check for "greater than or equal to zero" so zero is included in the output.

Note at the end the variable 'i' will have the value -1 which also means the loop variable 'i' must be signed and not unsigned.

Note also how the decrement statement is moved after the print statement.

void setup (void) {
int i=0;

   Serial.begin(9600);

   Serial.println("Arduino while loop 9~0");
   i = 9;
   while(i>=0) {      
      Serial.println(i);
i--;  } } void loop(void) { }
While loop 1-10 output
Arduino while loop 9~0
9
8
7
6
5
4
3
2
1
0

Arduino example of the Do while loop

Here the condition is tested at the end so the main body of code is always executed once.

void setup (void) {
int i=0;

   Serial.begin(9600);

   Serial.println("Arduino do while loop");

   do {
      i++;
      Serial.println(i);
   } while(i<10);
}

void loop(void) {
}

Here's the output of the above code

Arduino do while loop
1
2
3
4
5
6
7
8
9
10

Difference between for loop and a while loop

The difference between the for loop and a while loop is that the for loop uses a specific variable in the initialiser and no other. The while loop can use any variable that has been defined before the while keyword.

The other difference is that using the do-while loop makes it easy to perform the action always once (regardless of the conditional expression) and you can not do that with the for loop.

You will come across situations where you want to perform the action always once, so remember to use the do while loop instead of trying to write out complicated flag conditions using other variables.

Test Yourself

Q: There is no difference between while and for loops (T/F) ?

True or false (click to find out) False: You can use a do while loop to execute a block always once which is not possible with a for loop.

This is only true in trivial form - you can write code to detect the initialiser variable and break out of the loop but it is far more effort that its worth -it is just easier to use the while loop.

Q: While loops and for loops can never perform the same way (T/F)?

True or false (click to find out) False: You can make a while loop do the same job as a for loop.

The infinite while loop

The one unusual thing you can do with the while construct is to create a never ending loop. This may sound ridiculous but processors don't know how to find the start and end of memory.

The processor just increments the program counter (this just points to code stored in flash memory). If there is no instruction not to stop (or jump somewhere else) it just keeps going until it runs out of memory.

In Arduino code, the loop() construct contains an infinite while loop.

An infinite while loop is just a while loop with the conditional set to true. As with the normal loop code begins again when the program reaches the last closing brace and jumps to the start brace. The difference here is that the conditional is always true so the program counter never exits from the loop.

Of course the reset button (or power on/ off) is the exit mechanism!


void setup (void) {

while
(1) {
// Do something forever
}
}
void loop(void) { //This is now redundant!!! }

The other looping syntax that you may be interested in is the Arduino for loop.


Comments

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

Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.




Privacy Policy | Contact | About Me

Site Map | Terms of Use