Adventures in Science: Arduino Loops

Time for the ever-popular loops discussion! We look at the three basic loops you can use in Arduino.

This week, we examine loops in Arduino. Specifically, we look at while, do while, and for loops.

The while loop is intended to run code inside the curly braces { } as long as the condition specified behind the while statement is true. For example, the following code would print "Hi" three times before exiting the loop:

int i = 0;
while ( i < 3 ) {
    Serial.println("Hi");
    i++;
}

Note that the condition (the part in between the parentheses ( )) can include any of the relational operators we discussed in the conditional statements video or the compound conditional statements we talked about in the logic operators episode.

The do while loop is similar, but it guarantees at least one execution of the code between the curly braces, as the condition check occurs after the code. For example, the following code prints "Hi" once, even though i fails the condition check the first time through.

int i = 0;
do {
    Serial.println("Hi");
    i++;
} while ( i < 0 );

Finally, the for loop is intended to run a piece of code a specified number of times (although you can make it do other things). We can make the while loop example above cleaner by condensing it into a for loop:

int i;
for ( i = 0; i < 3; i++ ) {
    Serial.println("Hi");
}

Note that in C++ and modern implementations of C, you can declare the i variable inside the for loop's initialization: for ( int i = 0; i < 3; i++ ) {...}, but I left it out of the video, as I plan to cover that in a future episode dealing with scope.

Any tips or tricks you'd like to share when it comes to loop? Let us know in the comments!