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.

Arduino While loop

The Arduino while loop is another loop control structure that lets you conditionally repeat a block of code. It is different from the for loop discussed in the previous part of this programming course in that it does not have the initialiser or incrementer parts - you set these up outside the while loop.

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

   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 acheived and you can also see that there are the same elements that 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.

Arduino While loop example 1 through 10

By moving the iterator (i++) you can change the output as a squence 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!

Heres the while loop Sketch for values 1 through 10:

void setup (void) {
int i=0;

   Serial.begin(9600);

   Serial.println("Arduino while loop");

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

void loop(void) {
}

The only change 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 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.

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.


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. How to use the ADS1115

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

    Read more

  2. The TP4056: Lithium Ion/polymer Battery Charger IC

    Learn how to use the TP4056 properly. There's a right, and a wrong way, to use it to safely charge Lithium Ion batteries.

    Read more

  3. DW01A Battery Protector IC

    The DW01A chip is a Lithium Ion battery protector commonly used on TP4056 boards.  Find out Exactly how it works and how to use it the correct way.

    Read more

  4. Arduino String: How to read commands from the serial port.

    For Arduino string operations you can use Object Class Strings or C style strings but which should you use? Also find out how to decode commands and control variables in your programs using strings.

    Read more

  5. A Real Time Clock design (DS1307) with a PIC microcontroller

    Real Time Clock Design (FREE): A Free and Complete RTC design using the DS1307 and a PIC micro (16F88) also re-targetable. This PIC project uses an I2C Clock chip and 7-segment display to create a fou…

    Read more

  6. 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

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