/*
For Loop Iteration
Demonstrates the use of a for() loop.
Lights multiple LEDs in sequence, then in reverse.
The circuit:
- LEDs from pins 2 through 7 to ground
created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
https://docs.arduino.cc/built-in-examples/control-structures/ForLoopIteration/
*/
int timer = 100; // The higher the number, the slower the timing.
void setup() {
// use a for loop to initialize each pin as an output:
for (int thisPin = 2; thisPin < 8; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
}
While Loops
An Arduino while loop continuously executes a block of code inside curly braces as long as the condition inside the parentheses evaluates to true. It is ideal for situations where you do not know the exact number of loop iterations beforehand, such as waiting for a sensor value to change or a button to be pressed. [1, 2, 3, 4, 5]
const int buttonPin = 2;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// Pause code execution here AS LONG AS the button is held down (LOW state)
while (digitalRead(buttonPin) == LOW) {
// Do nothing, just wait, or run a temporary task like a calibration routine
}
// The program only reaches here once the button is released
}