while loops

Arduino – While Loop

While there are a few choices for loops to do while coding in Arduino(Puns intended), you will find a lot of different situations to use each of these loops. We took a look at the for loop in this post, and discovered some of the uses for that. Now we’re going to take a look at the while loop, which is a little different, and I’ll explain to you why and when to use this loop.

while loops

What is it?

The while loop is a block of code that is run while the condition between the parenthesis is true. This is useful when you’re waiting for something, or you have to send a serial command somewhere repeatedly until the desired outcome is returned. It will stay in this loop until the pre-determined requirements are met. This is different from the for loop, because the for loop loops through and increments a variable until it hits a certain number. The while loop can also be written to do this, but that’s not what it’s designed to do.

Uses

One of our examples is going to be a listener, we’ll have the while loop wait until it sees that there is serial data available to read, then it will take action on the serial data that is received.

Another example is a temperature monitor. You can have it sit in the while loop and only do a temperature reading until it changes, then when it changes you can have it send a text message, write to a database, or do any other task imaginable(except split atoms, Arduino is not designed to perform that).

Usage

The following is they syntax from Arduino.cc:

while(condition){
  // statement(s)
}

Let’s break that down, it’s a very simple piece of code, right? In the first line we tell the compiler that we’re using a while statement, by stating “while”. Immediately after that we have a set of parenthesis, inside these parenthesis will be the condition that you are testing. If the condition immediately returns false, your code will never be run, otherwise it runs continuously until it returns false.

You can also use “break” to break out of the loop. This would effectively add a second condition to the while loop, if you use it inside an if statement. For example your while loop tests for sensor a to change, and your if statement tests for sensor b to change. When sensor a changes you have it return false to break out of the loop, when sensor b changes you have it return true to break out of the loop(because an if statement only reads the code inside the curly braces if the condition is true).

 

You can run forever loops by doing while(true). This is not recommended, but it can be done. An example of a forever loop is the “loop()” function that Arduino uses to loop the code you write. This is a loop that is always run, unless you use a break somewhere to remove it from the loop. You can get stuck in this loop indefinitely, so it’s not recommended to use forever loops. Just mentioning it today, so you do know that it’s possible, and that it’s also a risk.

Examples

A great example for this loop, is the post I did about serial communication via the serial monitor. The following is the code from that post:

String data;//initialize string variable

void setup() {
 Serial.begin(9600);//initialize serial
}

void loop() {
 while (Serial.available()){//loop while data is available
 Serial.print("You typed: ");
 data = Serial.readString();//read the data
 Serial.println(data);//print the data to serial monitor
 }
}

If you look through this code, you’ll see in the first line we set up a string named data. In the setup function we instantiate serial at 9600 baud rate. In this case the loop will not run until serial data is available, which would mean that something was sent from the serial monitor to the Arduino. To trigger this, you just have to type something in the serial monitor. Then it does the loop until no more serial data is available, and waits until next time it is available. You can learn more about this process in this post.

for loops

Arduino – For Loop

Arduino’s language is packed full of goodies that make things quite a bit easier to accomplish. Without loops, we would rewrite code over and over again, and it would be the ugliest code you’ve ever seen.

It takes a while before some people even start using loops, you’re in the right place if that’s you. Using loops will change the way you structure your sketches completely. You’ll find this is a huge time saver. Some times a little effort goes a long way!

for loops

What is it?

A for loop is a loop that runs a set amount of times. It loops until a predetermined condition is met, you set this condition at the beginning of the loop. Once the condition is met, it breaks out of the loop, and continues on with the code.

Most of the time, it’s good practice to keep the loops in a function or an if statement. Doing this avoids slowing down your sketch, by running through the loop every single time your main loop starts over.

Uses

One of my favorite uses, is using for loops to cycle through each value in an array. One example of a for loop that I used recently, was in a weather station. I designed a weather station that had 16 underground sensors. Instead of running a function 16 times, I ran a for loop that counted up to 16, and ran the function to read from each one individually. This took much less code than it would have otherwise.

Usage

This is the syntax from Arduino.cc:

for (initialization; condition; increment) {
 //statement(s);
}

Let’s pick that apart.

You of course state that you’re using the for loop by starting with “for”. The arguments to the for loop can be tricky at first, but they are fairly easy to understand. You start with initialization. I prefer to start with “int i”. You initialize an int here generally, because you’re going to use that int to count with. This is the variable that you’ll use to determine when the loop is done.

The condition that you’re setting here is what needs to be true for this loop to be done. You could put i<=10 and it will run until it is equal to 10.

The last portion here is increment. Normally I’d simply put i++ here. This is where you’ll add to the int that was defined.

An important note: If you use this to count things in an array, arrays start with an index of 0. So if you programmatically have your sketch determining the length of an array, you need to make sure you’re calling array[i-1]. This would start your index at 0, and make sure you don’t go over the amount of values that’s in the array.

Example

This example will count to 10, waiting 1 second in between each number. You can speed this up by changing the delay at the end of the loop:

void setup() {
Serial.begin(9600); //Initialize serial output
}

void loop() {
Serial.println("For loop starting");

for (int i=0; i <= 10; i++) { //initialize the for loop, it will count i up to 10, then be done
 Serial.print("Counting:");//Write the text counting
 Serial.println(i);//Print out the value of i and start a new line after
 delay(1000);//Wait 1 second
}

Serial.println("For loop complete");

}

Let’s see what the output gives us on the serial monitor.

There you have it! Now we can count to 10, without having to use our brain!