do...while
O loop do...while funciona da mesma forma que o loop while, com a exceção de a condição ser testada no final do loop, tal que o loop será executado pelo menos uma vez.
do {
} while (condição);
A condição é uma expressão booleana que é avaliada como verdadeiro ou falso, respectivamente true ou false na linguagem Arduino.
void setup() {
Serial.begin(9600);
Serial.println("====== TEST START ======");
int i = 0;
do {
Serial.print("Inside the DO WHILE loop: i = ");
Serial.println(i);
i++;
} while (i < 5);
Serial.println("====== TEST END ========");
}
void loop() {
}
The result on Serial Monitor:
====== TEST START ======
Inside the DO WHILE loop: i = 0
Inside the DO WHILE loop: i = 1
Inside the DO WHILE loop: i = 2
Inside the DO WHILE loop: i = 3
Inside the DO WHILE loop: i = 4
====== TEST END ========
int x = 0;
do {
delay(50);
x = readSensors();
} while (x < 100);
The while loop checks the condition before executing the block of code; conversely, the do while loop checks the condition after executing the block of code. Therefore, the do while loop will always be executed at least once, even if the condition is false at the beginning.
The do...while and while loop are the same, except for the case in which the condition is false at the beginning.
For example:
void setup() {
Serial.begin(9600);
Serial.println("====== TEST START ======");
int i = 10;
do {
Serial.print("Inside the DO WHILE loop: i = ");
Serial.println(i);
i++;
} while (i < 5);
Serial.println("====== TEST END ========");
}
void loop() {
}
====== TEST START ======
Inside the DO WHILE loop: i = 10
====== TEST END ========
void setup() {
Serial.begin(9600);
Serial.println("====== TEST START ======");
int i = 10;
while (i < 5) {
Serial.print("Inside the DO WHILE loop: i = ");
Serial.println(i);
i++;
}
Serial.println("====== TEST END ========");
}
void loop() {
}
====== TEST START ======
====== TEST END ========
※ Notas e Advertências:
There are three ways to escape the do while loop:
※ ARDUINO BUY RECOMMENDATION
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.