while

Descrição

Um loop while irá se repetir continuamente, e infinitamente, até a expressão dentro dos parênteses (), se torne falsa. Algo deve mudar a variável testada, ou o loop while nunca irá encerrar. Isso pode ser no seu código, por exemplo, uma variável incrementada, ou uma condição externa, como a leitura de um sensor.

Sintaxe

while (condição) { // código a ser executado repetidamente }

A condição é uma expressão booleana que resulta em true ou false.

Código de Exemplo

void setup() { Serial.begin(9600); Serial.println("====== TEST START ======"); int i = 0; while (i < 5) { // faz algo repetitivo 5 vezes 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:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
====== 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 ========
Ln 11, Col 1
Arduino Uno on COM15
2

※ Notas e Advertências:

  • 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.

Ver Também

Exemplo : Loop While (Em Inglês)

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