Loop Arduino
The loop provides a mechanism to repeat a section of code depending on the value of a variable. So you set the initial value of the variable, the condition to exit the loop, and the action on the variable each time around the loop. A loop statement also will allow to execute a statement or group of statements several times and following is the general form of a loop statement in most of the programming language.
while loop
while loops will loop continuously, and infinitely until the expression inside the () becomes false.
Syntax:
while (loop test expression goes here) { Statements that run in the loop go here Statement 1 Statement 2 ... }
Example:
In the example sketch below, the while loop is used to count up to a hundred in tens by adding ten to a variable each time through the loop.
void setup() {
int time = 0;
Serial.begin(9600);
// count up to 100 in 10s
while (time < 100) {
time = time + 10;
Serial.print("time = ");
Serial.println(time);
delay(10000); // 1000ms delay
}
}
void loop() {
}
do…while loop
The do-while loop is similar as it waits for the event, but there are certain differences: the while loop is executed while the condition is being fulfilled, whereas the do-while is executed at least once after the condition has been fulfilled.
Syntax:
do { Statements that run in the loop go here Statement 1 Statement 2 ... } while (test expression goes here);
Example (Sketch)
void setup() { int time= 0; Serial.begin(9600); // count up to 100 in 10s do { time= time+ 10; Serial.print("time= "); Serial.println(time); delay(1000); // 1000ms delay } while (sum < 100); } void loop() { }
for loop
A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses.
You can create a for loop that counts down by changing all three parameters in the for loop. Lets say you want to count down from 10 to 1 (ten iterations round the loop).
Sketch
void setup() { int i; Serial.begin(9600); for (i = 0; i < 10; i++) { Serial.print("i = "); Serial.println(i); } } void loop() { }
Nested loop
allows you to use loop statement inside another loop
Comments
Post a Comment