Lesson 7: Mastering Loops in Arduino programming
Hello and welcome to Electro Nerds Academy! In today’s tutorial, we’re diving into one of the most powerful features of programming — loops. Whether you’re just getting started with programming or you’re looking to write cleaner, more efficient code, understanding how loops work can significantly enhance your coding skills.
What are Loops ??
Imagine you’re using an Arduino UNO and you’ve been asked to configure all 20 pins (14 digital and 6 analog) as output. Manually writing pinMode()
statement twenty times is not only boring but also prone to error. Now, imagine doing the same with an Arduino Mega that has 78 pins — nightmare, right?
This is where loops save the day! With just a few lines of code, loops allow you to repeat tasks automatically, making your programs cleaner, shorter, and easier to maintain.
A loop is a programming construct that repeats a set of instructions or code until a particular condition is true. In programming we have three types of loops:
1️⃣while loop
2️⃣do while loop
3️⃣for loop
Each has its use case, and we’ll go through all of them with examples one by one.
1️⃣The while Loop
The while
loop checks a condition before executing code. If the condition is true, the loop runs; otherwise, it skips the loop entirely.
Syntax:
The common way of writing a while loop is shown below,
while (condition)
{
// code to run
}
We will first write the while identifier then in the parenthesis we write the condition which we want to evaluate each time when the loop is iterated. If the condition is true only then the code written inside the loops body that is in between the pair of curly brackets will be executed.
Example 1:
In this example we will assign all 20 pins of the Arduino UNO as output. The code looks something like this,
int count = 0;
void setup()
{
while (count < 20)
{
pinMode(count, OUTPUT);
count++;
}
}
void loop()
{}
We first declare a variable named count
to store the number of times the loop has run. Then we have the while
keyword followed by a pair of round brackets. Inside these brackets, we have written our condition — that the count
variable should be less than 20. If this condition is true, then the code inside the loop’s body will be executed; otherwise, it will be ignored.
The code in the loop’s body first assigns the pin as an output using the pinMode
function. Note that we haven’t directly mentioned the pin number; instead, we have used the count
variable as the first parameter. After that, we increment the count
variable.
So, when the loop runs for the first time, the value of the count
variable will be 0. Since 0 is less than 20, the condition is satisfied and the code in the loop’s body will be executed. First, the pinMode
statement is executed, setting pin 0 as an output pin. This is because the value of the count
variable is zero. After this, the count
variable is incremented, making its value 1.
The condition is checked again, and since 1 is still less than 20, the condition is true. Therefore, the code in the loop’s body runs again — but this time, since the count
variable’s value is 1, pin 1 is set as an output pin. After that, the count
variable is incremented again, and its new value becomes 2. The condition is checked once more, and the code is executed again.
This process continues until the value of the count
variable becomes 20. At that point, the condition becomes false, and the program execution moves forward to execute the statements written after the loop, completely ignoring the code in the loop’s body.
We can utilize this same code for declaring all 78 pins of Arduino Mega as output. We just have to change the value in the loop’s condition from 20 to 78 as shown below.
int count = 0;
while (count < 78)
{
pinMode(count, OUTPUT);
count = count + 1;
}
Example 2:
An interesting application you will encounter a lot is the infinite loop using while loops. An infinite loop is a loop that runs forever kind of like the void loop function of the sketch. So if we want to blink an LED. It will blink for ever. But what if we want to blink the LED only five times and then halt further execution of the code. This is where an infinite loop comes in handy. The way an infinite loop is written is shown below,
while(true)
{}
Here while(true) creates an infinite loop because the condition is always true. Hence the program execution will be halted. Now lets see this infinite loop in action. Suppose we want to blink an LED 10 times and then just stop we don’t want to do anything. the code will look something like the one shown below,
int count = 0;
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
while(count < 10)
{
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
count++;
}
while()
{}
}
Lets breakdown how this code works, First we declare an integer variable named count to store the number of iterations the loop has run. Then in the setup function we set pin 13 as an output pin using the pin mode statement. Now moving on to the loop function we have two while loops the first one is responsible for blinking the LED 10 times and the second one is responsible for halting the program so that the void loop section is not executed any more. And it will remain halted until you reset the Arduino Board either by restarting the board or pressing the restart button on the board.
one thing we want to highlight here is that both ( count++ ) and (count = count + 1) perform the same task of incrementing the count variable by one. Similarly both ( count– ) and (count = count – 1) perform the same task of decrementing the count variable by one.
2️⃣The do-while Loop
Unlike while
loops, the do-while
loop will always run at least once, even if the condition is false. These loops are used when we need to run the code at least once such as prompting for input or performing an initial setup that must always happen.
Syntax:
Its syntax resembles with the while loop but it has some changes. As shown below,
do
{
// code to run
} while (condition);
We first have the “do” identifier followed by a pair of curly brackets within these brackets we will write the code that we want to run at least once. then we write the “while” identifier followed by the pair of round brackets in between which we write the condition which we want to evaluate and finally terminating the statement with a semi colon.
Example:
Let’s revisit Example 2 that we discussed earlier, but this time we’ll implement it using a do-while loop
as shown below:
int count = 0;
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
do
{
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
count++;
} while(count < 10);
while()
{}
}
Now, when you upload this program to your Arduino, you won’t notice any difference from the previous time. However, let’s see what happens if we change the initial value of the count
variable from 0
to 10
, as shown below:
int count = 10; // <--- changed from 0 to 10
void setup()
{
pinMode(13, OUTPUT);
}
void loop()
{
do
{
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
count++;
} while(count < 10);
while()
{}
}
If we were using a while loop, nothing would happen because the condition would be false from the start because 10 is not less than 10, and the loop’s body would never execute. However, with a do-while loop, the code inside the loop’s body runs at least once before the condition is even checked—so the LED blinks at least once before the program halted.
3️⃣The for Loop
The next type of loop of loop we are going to discuss today is the for loop. The advantage of this loop over the two types is that this loop keeps the count variable localized hence reducing the number of global variables. If you don’t know about local and global variables then don’t worry we will discuss them in detail in one of the future lessons.
Syntax:
the syntax of a for
loop is shown below,
for (initialization; condition; increment)
{
// Code to repeat
}
Each part of the for
loop has a specific role:
🔸Initialization: Sets the starting point of the loop. Usually declares and initializes a counter variable.
🔸Condition: The loop runs as long as this condition is true.
🔸Increment/Decrement: Updates the counter variable each time the loop runs.
Example :
Lets see how we can declare all 20 pins of Arduino UNO as Output pins using a for-loop. The code is shown below,
void setup()
{
for(int i = 0; i < 20; i++)
{
pinMode(i, OUTPUT);
}
}
void loop()
{}
each part of the above for loop is shown below:
🔸Initialization: ( int i = 0; )
🔸Condition: ( i < 20; )
🔸Increment/Decrement: ( i++ )
So, when the loop runs for the first time, a counter variable i
is initialized. This variable exists for the duration of the loop’s execution. The loop then checks the condition: whether i
is less than 20. Since 0 < 20
, the condition evaluates as true, and the code inside the loop’s body executes, setting pin 0 as an output. Once the end of the loop is reached, the counter is incremented, and the condition is checked again. Now, since 1 < 20
, the loop runs again, setting pin 1 as an output. This process repeats—incrementing the counter and setting the corresponding pin as output—until all 20 pins of the Arduino Uno are configured as output.