Implementation of loops in Arduino programming

Share

In programming, a loop is a fundamental control structure that allows a set of instructions to be repeatedly executed based on a specified condition. Loops are used to perform tasks iteratively, making it possible to automate repetitive actions and efficiently process large amounts of data.

It helps in keeping the code user-friendly and easy to understand. In Arduino programming, loops are essential to repeat instructions or code blocks multiple times. Loops play a crucial role in controlling the behavior of your microcontroller. The basic logic of the loop structure is given as follows:

loop structure
loop structure

In the loop, a condition and a conditional code are written inside the loop structure. If the condition evaluates to true, the conditional code is executed. As soon as the condition evaluates to false, the loop is terminated.

As we've got the idea of the loop construct, let's dive into the types of loops available.

The While loop

In Arduino programming, we prefer to use a loop when we don't know the number of iterations required. The While loop basic syntax is given as:

while (condition) {
conditional code (body);
}
Syntax of while loop

The number of iterations of the loop is dependent on the condition. The loop continues to execute the statements written in the body of the loop as long as the condition remains true.

The condition could be anything like while (x<5), in this case, the loop with terminate when the value of x is equal to or greater than 5. The central concept here is as long as the condition for the while loop is true, the loop will execute.

Example

Here, the given illustration shows the working of the while loop.

void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
int x = 0; // Define and initialize the variable x to 0
// Use a while loop to repeat the print statement 5 times
while (x < 5) {
Serial.println("Hello, welcome to Educative");
x++; // Increment the value of x by 1 in each iteration
delay(1000); // Add a delay of 1 second between each print statement
}
}
void loop() {
//your code is written here
}
Implementation of while loop

In this code, we set up serial communication with the Serial.begin(9600) line in the setup() function. Then, we define and initialize the variable x to 0. The while loop prints "Hello, welcome to Educative" on the serial monitor five times. The loop runs as long as the condition x < 5 remains true. Within the loop, we increment the value of x by 1 in each iteration using x++, and a delay of 1 second (delay(1000)) is added between each print statement to create a visible time gap between the messages.

It is to note that if the conditional variable is not incremented inside the while loop, the value of the conditional variable stays the same, which leads to the execution of the loop infinitely. The loop never ends (terminates).

The do while loop

This is similar to while loop, except for one thing. The conditional code is executed first, and then the condition is checked. The conditional code is written in the do block. The critical thing to remember is the conditional code written in the do block is executed at least once even though the condition fails.

Syntax of do while is given as:

do {
coditional code (body);
} while (condition)
do-while sytax

Example

Here, the given illustration shows the working of the do while loop.

void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
int x = 0; // Define and initialize the variable x to 0
do {
Serial.println(x);
delay(1000);
x ++;
} while (x < 5) ;
}
void loop() {
}
Implementation of do-while loop

In this code, we set up serial communication with the Serial.begin(9600) line in the setup() function. Then, we define and initialize the variable x to 0. The while loop prints the value of x on the serial monitor five times. The loop runs as long as the condition x < 5 remains true. Within the loop, we increment the value of x by 1 in each iteration using x++, and a delay of 1 second (delay(1000)) is added between each print statement to create a visible time gap between the messages.

Another implementation is shown to explain the working of the do while loop in a better way.

void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
int x = 10; // Define and initialize the variable x to 0
do {
Serial.println(x);
delay(1000);
x ++;
} while (x < 5) ;
}
void loop() {
}
Another implementation of do-while loop

In this code, it can be seen that the condition will eventually return false. The emphasis point is that the value of x is printed. This is because in the do while the conditional block is executed before the condition is checked.

The for loop

This loop executes the conditional code a predetermined number of times. In this loop, the variable is initialized, the condition is written, and the incrementation of the condition variable is done. The syntax of for loop is given as:

for(initialization; condition; iteration) {
conditional code (body);
}
Syntax of for loop

Example

Here, the given illustration shows the working of the for loop.

const int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}
void loop() {
// Using a for loop to blink the LED 5 times
for (int i = 0; i < 5; i++) {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(500); // Wait for 0.5 seconds
digitalWrite(ledPin, LOW); // Turn the LED off
delay(500); // Wait for 0.5 seconds
}
}
Implementation of for loop

In this example, the for loop will run five times, blinking the LED on and off five times with a 0.5-second interval between each cycle.

Nested loop

A loop within a loop is called a nested loop. For nesting, we can have:

  • Nested while loop

  • Nested for loop

  • Mixed nested loop

Example

Implementing mixed nested loops is shown to understand better how nested loops work.

void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
int numRows = 5; // Number of rows in the star pattern
int currentRow = 1; // Initialize the current row
// Mixed nested loop to create the star pattern
for (currentRow = 1; currentRow <= numRows; currentRow++) {
int numStars = currentRow; // Number of stars in the current row
while (numStars > 0) {
Serial.print("*");
numStars--;
}
delay(1000); // Add a delay of 1 second before printing the pattern again
Serial.println(); // Move to the next line after printing each row
}
}
void loop() {
}
Implementation of nested loop (mixed)

This Arduino code uses mixed nested loops to create a star pattern and print it on the serial monitor. Let’s break down the code step by step:

  1. void setup(): This is the setup function, which runs once when the Arduino starts. It initializes the serial communication at a baud rate of 9600 bps (bits per second) using Serial.begin(9600).

  2. Variable initialization: Inside the setup function, two integer variables are declared and initialized:

    1. int numRows = 5;: This variable numRows is set to 5, indicating that we want to create a star pattern with five rows.

    2. int currentRow = 1;: This variable currentRow is initialized to 1, representing the current row of the star pattern being processed.

  3. Nested loop: The code utilizes a mixed nested loop structure to create the star pattern. The outer for loop is used to control the number of rows in the pattern. It runs from currentRow = 1 to currentRow <= numRows, where currentRow is incremented by one in each iteration.

  4. Inner while loop: Within the for loop, there is a nested while loop. The while loop runs as long as numStars > 0. In each iteration of the while loop, it prints a * character using Serial.print("*") and decrements the numStars variable by one using numStars--. This nested while loop ensures that the number of * characters printed in each row correspond to the value of currentRow, resulting in a right-angled triangle pattern.

  5. Delay: After printing each row, a delay(1000) is added, creating a 1-second pause before printing the next row. This delay lets you observe the pattern more clearly on the serial monitor.

  6. Serial.println(): After printing the * characters for a row and adding the delay, Serial.println() is used to move the cursor to the following line on the serial monitor, ensuring that each row is printed on a new line.

  7. void loop(): The loop function is empty and does not contain any code. In Arduino, the loop function runs continuously after the setup function, but since there is no code inside the loop function, it remains idle and does nothing.

This code uses mixed nested loops to generate a right-angled triangle star pattern with five rows. The pattern is printed on the serial monitor, with each row containing an increasing number of * characters. The program continuously runs this pattern, with a 1-second delay between each row.

Conclusion

Loops are indispensable in Arduino programming, enabling efficient repetition and code optimization. The for and while loops offer versatility to control iterations, making projects more functional and concise.

Additionally, for a comprehensive understanding of control structures, you can find an Answer with examples and explanations in this link: If-Else and Switch-Case in Arduino. Combining these control structures with loops empowers Arduino developers to create versatile projects with enhanced decision-making capabilities and optimized performance.

Copyright ©2024 Educative, Inc. All rights reserved