Logic: For Next Loop

Understanding the Arduino For Loop

Hey there, makers! 👋

If you’ve started tinkering with Arduino, you’ve probably noticed how often things repeat — blinking LEDs, reading sensors, or cycling through displays. That’s where one of the handiest tools in Arduino programming comes in: the for loop.

What’s a For Loop?

A for loop is just a simple way to repeat a block of code a certain number of times. Instead of copying and pasting the same commands over and over, you let the loop handle it automatically.

Think of it like saying:

“Do this thing 5 times.”

It’s cleaner, faster, and way easier to read later — especially as your projects get bigger.

How It Works

A for loop has three parts:

for (int i = 0; i < 5; i++) {
  // Code that repeats
}

Let’s break it down:

  • int i = 0 → start counting at zero.
  • i < 5 → keep going as long as i is less than 5.
  • i++ → add one to i each time the loop runs.

So this loop runs five times total (i = 0, 1, 2, 3, 4).

Example: Blinking an LED with a For Loop

int ledPin = 13; // Built-in LED pin

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  for (int i = 0; i < 5; i++) {
    digitalWrite(ledPin, HIGH);
    delay(500);
    digitalWrite(ledPin, LOW);
    delay(500);
  }
  delay(2000); // Wait before starting again
}

This little sketch blinks your LED five times, pauses for two seconds, then does it all again. You can change the number 5 to anything you like to make it blink more or less.

Why It’s So Useful

  • Keeps your code neat and organized.
  • Great for repeating actions — blinking, counting, cycling through pins or data.
  • Helps avoid mistakes from copying the same code multiple times.

Once you get comfortable with loops, you’ll start using them everywhere — controlling multiple LEDs, reading arrays of sensors, or stepping through animations.

So go ahead, give the for loop a try and watch your Arduino projects become cleaner, smarter, and easier to manage! 🚀