Arduino – Loops

Loops allow certain parts of a program to be executed more than once. The loops can be used to make the code more concise in certain situations. Take them in order.

while loop

The while loop will run continuously as long as the condition in parentheses is true. Something needs to change the value of the variable in parentheses, otherwise the while loop will never exit. This can be in the code block, such as an incremental variable, or in an external state, such as a state change of an input pin.

while(condition)
{
  // statement
}

In the following example, the while loop runs as long as the value of the variable is less than 10.

int myVariable = 0;

while (myVariable < 10)
{
  myVariable++;
}

while infinite loop:

while(true)
{
  // runs forever...
}

do… while loops

The do… while loop works the same as the while loop, except that the condition is tested at the end of the loop, so the do… while loop always runs at least once. The do… while loop is also called a back test loop. The do… while loop in the following example is executed 10 times because when the condition becomes false the code block is already run.

int myVariable = 0;

do 
{
  myVariable++;
} while(myVariable < 10);

for loop

The for loop has three expressions. These determine how it works. The three expressions in parentheses for the for loop argument are separated by semicolons. In the first expression, we initialize the cycle variable. The second expression is a loop condition as long as it is true for the loop run. In the third expression, we change the value of the cycle variable.

for(int index = 0; index <= 10; index++) 
{    
  // your code
}

The for infinite loop:

for( ; ; )
{
  // runs forever...

}

The for loop is often used with arrays, for example to extract data or populate arrays.

int myIntArray[] = {1,2,3,4};

for ( int i = 0; i < 4; ++i)
{
  Serial.print(myIntArray[i]);
  Serial.print (", ") ;
}
int myIntArray[4];

for ( int i = 0; i < 4; ++i)
{
  myIntArray[i] = i + 1;
}

for loops can be nested.

char myCharArray[4][5] = {"row1","row2","row3","row4" };

for ( int i = 0; i < 4; ++i )
{
  for (int j = 0; j < 4; j++)
  {
    Serial.print(myCharArray[i][j]);
  }
}

break

The break statement is used to exit loops for, while, or do… while, or to exit a switch case statement.

In the following example, if the value of the variable i becomes 5, the loop ends. the last character printed will be 4.

for (int i = 0; i < 10; i++) 
{
  if (i == 5) 
  {
    break;
  }
  Serial.println(i);
}

continue

The continue statement aborts an iteration in the loop if a specified condition occurs and continues with the next iteration of the loop.

This example omits the value of 5:

for(int i = 0; i < 10; i++) 
{
  if (i == 5)
  {
    continue;
  }
  Serial.println(i);
}

In the next section, we review the functions.

advertising – ESP boards from amazon.com