Arduino - Loops
Arduino - Control Structures: Loops
Section titled “Arduino - Control Structures: Loops”In programming, a loop is a control structure that allows you to execute a block of code repeatedly. This is fundamental for tasks like reading a sensor multiple times, blinking an LED, or processing items in a list. Arduino, using C++, provides several powerful loop types.
The ‘for’ Loop
Section titled “The ‘for’ Loop”Use a for loop when you know in advance how many times you want to execute the code block. It combines initialization, condition checking, and an increment/decrement expression into one compact line.
Syntax:
for (initialization; condition; increment) { // code to execute}Example: Blink an LED 5 times.
const int ledPin = 13; // Use LED_BUILTIN for modern boards
void setup() { pinMode(ledPin, OUTPUT);
// Loop 5 times. 'i' goes from 0 to 4. for (int i = 0; i < 5; i++) { digitalWrite(ledPin, HIGH); // Turn LED on delay(200); digitalWrite(ledPin, LOW); // Turn LED off delay(200); }}
void loop() { // The main loop is empty as the action happens in setup()}The ‘while’ Loop
Section titled “The ‘while’ Loop”A while loop executes a block of code as long as a specified condition is true. The condition is checked before the loop body is executed. If the condition is initially false, the loop will never run.
Syntax:
while (condition) { // code to execute}Example: Wait until an analog sensor on pin A0 reads a value above 500.
const int sensorPin = A0;const int ledPin = 13;
void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT);
Serial.println("Waiting for sensor value to exceed 500...");
// Loop continuously while the sensor reading is below the threshold while (analogRead(sensorPin) <= 500) { // This is a good place for a small delay to prevent spamming the Serial monitor // or to allow the processor to handle other tasks in more complex code. delay(50); }
Serial.println("Threshold reached! Lighting up the LED."); digitalWrite(ledPin, HIGH); // Light the LED once the condition is met}
void loop() {}The ‘do-while’ Loop
Section titled “The ‘do-while’ Loop”The do-while loop is similar to a while loop, but the condition is checked after the loop body is executed. This guarantees that the code block will run at least once.
Syntax:
do { // code to execute} while (condition);Example: Read a character from the serial port and echo it back, until the character ‘q’ is received.
char receivedChar;
void setup() { Serial.begin(9600); Serial.println("Enter characters. Type 'q' to quit.");}
void loop() { do { // Wait for data to become available while (Serial.available() == 0) { // do nothing, just wait } // Read the character and print it receivedChar = Serial.read(); Serial.print("You typed: "); Serial.println(receivedChar); } while (receivedChar != 'q');
Serial.println("--- Program Halted ---"); while(true) { // Infinite loop to stop further execution }}Modern C++: Range-Based ‘for’ Loop
Section titled “Modern C++: Range-Based ‘for’ Loop”Modern C++ (supported by the Arduino toolchain) introduces a simpler for loop for iterating over all elements of an array or other collection. It’s less error-prone and easier to read.
Example: Activate a sequence of LEDs.
// An array of LED pin numbersconst int ledPins[] = {2, 3, 4, 5};
void setup() { // Use a range-based for loop to set each pin as an OUTPUT // 'int pin' declares a temporary variable to hold each element for (int pin : ledPins) { pinMode(pin, OUTPUT); }}
void loop() { // Turn on each LED in sequence for (int pin : ledPins) { digitalWrite(pin, HIGH); delay(250); digitalWrite(pin, LOW); }}Loop Control: ‘break’ and ‘continue’
Section titled “Loop Control: ‘break’ and ‘continue’”break: Immediately exits the current loop (for,while,do-while) and continues execution at the statement following the loop.continue: Skips the rest of the current iteration of the loop and proceeds to the next iteration.
Example: Sum numbers from 1 to 20, but skip the number 13 and stop if the sum exceeds 100.
void setup() { Serial.begin(9600); int sum = 0;
for (int i = 1; i <= 20; i++) { if (i == 13) { Serial.println("Skipping unlucky 13!"); continue; // Skip to the next iteration }
sum += i; Serial.print("Current number: "); Serial.print(i); Serial.print(", Current sum: "); Serial.println(sum);
if (sum > 100) { Serial.println("Sum exceeded 100. Breaking loop."); break; // Exit the for loop entirely } }
Serial.print("Final Sum: "); Serial.println(sum);}
void loop() {}Common Pitfalls
Section titled “Common Pitfalls”- Infinite Loops: Forgetting to update the variable in a
whileloop’s condition will cause your program to get stuck forever. - Off-by-One Errors: In a
forloop, using<vs<=can mean the loop runs one too many or one too few times. For an array of size N, the valid indices are 0 to N-1, so the condition is typicallyi < N. - Blocking with
delay(): While used in these simple examples, extensive use ofdelay()in loops prevents your Arduino from doing anything else. For responsive projects, learn to use themillis()function to manage timing without blocking. (See the ‘Time’ chapter for more).