while

Descripción

Los bucles while se ejecutan de forma continua, e infinitamente, hasta que la expresión dentro del paréntesis() se convierte en falsa. Algo debe cambiar la variable de prueba, o el bucle while nunca se terminará. Este cambio podría ser en el código, tal como que una variable sea incrementada, o una condición externa, tal como la comprobación de un sensor.

Sintaxis

while(expression){ //instrucción(s) }

Parámetros

  • expression: una instrucción (boolean) C que se evalúa como verdadera o falsa.

Ejemplo

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; while (i < 5) { // repite algo 5 veces Serial.print("Inside the WHILE loop: i = "); Serial.println(i); i++; // increase i by 1 } Serial.println("====== TEST END ========"); } void loop() { }

In the example above, the code in the loop will run, over and over again, as long as a variable (i) is less than 5.

The result on Serial Monitor:

COM6
Send
====== TEST START ====== Inside the WHILE loop: i = 0 Inside the WHILE loop: i = 1 Inside the WHILE loop: i = 2 Inside the WHILE loop: i = 3 Inside the WHILE loop: i = 4 ====== TEST END ========
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ Nota:

  • When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
  • The following while loop loops forever:
while (true) { // statement(s) }
  • There are three ways to escape the while loop:
    • The condition of the while loop becomes false.
    • The execution of the code reaches a break statement inside the loop.
    • The execution of the code reaches a goto statement inside the loop, which jumps to a label located outside of the loop.

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.

※ OUR MESSAGES