Tags: ,

The while instruction is the conditional structure that allows you to create a loop on a condition. It is found in all programming languages. It is used to execute a block of code in a loop as long as a condition is fulfilled.

Syntax of the while instruction

The instruction takes a condition in the form of a Boolean variable as input and executes a block of instructions in a loop as long as this condition is true. If the condition is still true, the code following the while block will never be executed. Be careful to update your condition.

  while(condition){
    <list of instruction while condition=true>;
    <update condition>;
  }

Example of a code that counts up to 10:

int val=0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  while(val<=10){
    Serial.println(val);
    val++;
  }
}

A boolean is a type of variable equal to true( 1) or false(0 ). In the C(Arduino) language, boolean variables are initialized using the keyword bool or boolean. A boolean can be obtained in different ways

  • The result of a logic test <,>,==,!=,!
 condition = variable == 10;    // variable égale à 10? 
 condition = temperature>30;   // temperature est supérieure à 30 
 condition = vitesse <= 100    // vitesse inférieure ou égale à 100 
 condition = !true // condition égale  non vraie (faux) 
   
  • The result of several conditions (&& or and, || or or)
condition=(temperature>30) && (vitesse<20);
  • The result of a function
bool test(int val){
  //retourne vraie si la valeur est supérieur à 200
  return val>200;
}

It should be noted that the input function is executed at each loop.

int val=0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  while(condition()){
    Serial.println(val);
  }
  delay(10);//sanity delay
}

bool condition(){
  val++;
  return val<=10;
}


Other syntaxes

Another version of the while instruction exists. The do..while instruction which is in fact a completely different instruction. The main difference is that it is executed at least once.

The following code counts up to 10. The do..while block must be set in the setup function, otherwise the variable val will increment to zero. Since the do..while block is executed at least once, val will increment once each time a loop() is executed.

int val = 0;
void setup() {
  Serial.begin(9600);
  do{
    Serial.println(val);
    val++;
  } while(val<=10);
}

void loop() {
  delay(10);//sanity delay
}

In conclusion, what should be remembered

  • the while statement takes as input a condition represented by a boolean variable
  • the while loop input instruction is executed on each loop
  • the condition is in brackets
  • the instruction block is between brackets {}
  • The do..while instruction is executed at least once, unlike the while instruction.

Sources