Coding

Arduino For Loop: Syntax and Examples (LED, Arrays, Fade)

An Arduino for loop repeats a block of code a set number of times: for (initialization; condition; increment) { ... }. Arduino sketches are C++, so the syntax is the same as in C, and the loop is most often used to step through pin numbers, array elements or PWM brightness values.

void setup() {
  Serial.begin(9600);
  for (int i = 1; i <= 5; i++) {
    Serial.println(i);
  }
}

void loop() {
}

Example output in the Serial Monitor, one number per line: 1, 2, 3, 4, 5. The loop sits in setup() here so that it runs once. Put it in loop() and the whole sketch repeats forever, with the for loop running its full cycle on every pass.

How the Arduino for loop works

The Arduino reference describes three parts in the loop header, separated by semicolons:

  • Initialization runs first, exactly once.
  • Condition is tested each time through the loop. When it becomes false, the loop ends.
  • Increment runs each time through the loop while the condition is true.

The order is: initialize, test the condition, run the body, run the increment, test again. The condition is checked before the body, so a loop whose condition is false from the start never runs its body.

The reference also says that any or all of the three header elements may be omitted, but the semicolons are required. The statements can be any valid C++, with unrelated variables and any data type, floats included. That is more freedom than most beginners expect. You can count down, step by 5, or multiply instead of add.

Blink several LEDs with a for loop

The most common Arduino use of the loop is to avoid repeating the same two lines for every pin. Suppose LEDs are wired through resistors to pins 2 to 7. Instead of six pinMode() calls and twelve digitalWrite() calls, loop over the pin numbers:

const int firstPin = 2;
const int lastPin = 7;

void setup() {
  for (int pin = firstPin; pin <= lastPin; pin++) {
    pinMode(pin, OUTPUT);
  }
}

void loop() {
  for (int pin = firstPin; pin <= lastPin; pin++) {
    digitalWrite(pin, HIGH);
    delay(100);
    digitalWrite(pin, LOW);
  }
}

This lights each LED for 100 ms in turn, producing a light that runs along the row. Changing the number of LEDs means changing lastPin only. The loop works because the LEDs sit on consecutive pins. If your wiring is not consecutive, use an array, covered below.

Fade an LED with a for loop and analogWrite

The Arduino reference's own example for for is a fade. A loop counts from 0 to 255 and writes each value to a PWM pin with analogWrite(), pausing between steps:

const int ledPin = 10;   // must be a PWM-capable pin

void setup() {
}

void loop() {
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
}

The first loop brightens the LED over about 2.6 seconds (256 steps of 10 ms plus the time the calls take), and the second dims it back. The reference notes that one loop can also do both by reversing the step direction at the peak value of 255, but two loops are easier to read.

Three facts from the analogWrite() reference matter here:

  • The value is a duty cycle from 0 (always off) to 255 (always on), so the loop limits of 0 and 255 are the full range.
  • On the Uno, PWM works on pins 3, 5, 6, 9, 10 and 11. Calling analogWrite() on another pin will not fade it.
  • You do not need to call pinMode() before analogWrite().

The same page warns that pins 5 and 6 share a timer with millis() and delay(), so low values (roughly 0 to 10) can give higher duty cycles than expected, and a value of 0 may not fully turn the output off. If a fade looks wrong at the dark end on those pins, move the LED to another PWM pin.

Loop through an array in Arduino

When pins are not consecutive, or when you want to process sensor readings, store the values in an array and index it with the loop counter:

const int ledPins[] = {3, 5, 9, 11};
const int ledCount = sizeof(ledPins) / sizeof(ledPins[0]);

void setup() {
  for (int i = 0; i < ledCount; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < ledCount; i++) {
    digitalWrite(ledPins[i], HIGH);
    delay(200);
    digitalWrite(ledPins[i], LOW);
  }
}

The expression sizeof(ledPins) / sizeof(ledPins[0]) divides the array's size in bytes by the size of one element, so the compiler computes the count and adding a pin to the list needs no other edit. It only works where the array itself is in scope. Inside a function that receives the array as a parameter, you get the size of a pointer, so pass the length as a second argument.

Array indexes start at 0, so for ledCount elements the valid indexes are 0 to ledCount - 1. That is why the condition is i < ledCount and not i <= ledCount.

Print values with a for loop and Serial.println

To see what a loop does, print inside it. Serial.println(val) sends the value as readable ASCII text followed by a carriage return and a newline, so each call starts a new line. The optional second argument sets the number base for integers, for example Serial.println(i, BIN).

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < 4; i++) {
    Serial.print("pin index ");
    Serial.println(i);
  }
}

void loop() {
}

Example output:

pin index 0
pin index 1
pin index 2
pin index 3

Serial output is slow compared with the processor, so a loop that prints on every pass can dominate the run time. Remove the prints once the logic works.

break and continue in an Arduino for loop

break ends a loop early and skips its normal condition. The Arduino reference lists for, while and do...while loops, and says it also exits a switch case. Its example raises a PWM value in a loop, reads a sensor on each pass, and stops the loop once the reading passes a threshold of 40.

continue ends only the current pass. The loop then checks its condition and moves on. In the reference example, values of x between 41 and 119 trigger continue, so those values are never written to the pin. A compact version of the same idea:

for (int x = 0; x <= 255; x++) {
  if (x > 40 && x < 120) {
    continue;          // skip 41 to 119
  }
  analogWrite(10, x);
  delay(50);
}

In a for loop, continue still runs the increment, so the counter advances and the loop cannot get stuck. In a while loop with a hand-written increment, a continue placed before that increment can skip it and loop forever.

Nested for loops on Arduino

A loop inside a loop runs its full cycle once for each pass of the outer loop. On Arduino this is common for LED matrices and for scanning a grid of buttons: the outer loop picks a row and the inner loop picks a column. The inner body runs rows times columns. For a 4 by 4 grid that is 16 passes. The general idea is covered in nested for loops explained.

Common mistakes with the Arduino for loop

  • A stray semicolon. for (int i = 0; i < 3; i++); makes the semicolon the loop body. The loop counts to 3 doing nothing, and the block after it runs once.
  • Off by one. With i <= ledCount the last pass reads one element past the end of the array. The value is garbage, and a garbage pin number can switch the wrong pin.
  • Using a non-PWM pin for a fade. The loop runs correctly but the LED only jumps between off and on. Check the pin against the PWM list for your board.
  • Long delays inside loops. Every delay() blocks the whole sketch. A loop of 256 steps with delay(10) keeps the board busy for more than 2.5 seconds, during which it cannot read buttons. For responsive sketches, replace the for loop with a counter that advances once per loop() pass and a time check using millis().
  • Floating-point counters. A step like 0.1 cannot be stored exactly, so a condition like x != 1.0 may never be true. Count with an integer and compute the float from it.

For loop versus while loop in Arduino

Use for when you know the start, the end and the step, as with pin numbers, array indexes and brightness values. Use while when the loop should run until something changes, such as waiting for a button press or for serial data to arrive. The two can express the same loops, so the choice is about readability.

The syntax is shared with other C-family languages. If you know one, the others are close: compare the for loop in C and the JavaScript for loop.

Frequently asked questions

Can I leave parts of an Arduino for loop empty?
Yes. The Arduino reference says any or all of the three header elements may be omitted, but the semicolons are required. for (;;) with no condition runs until a break or until the board is reset or powered off.
Does an Arduino for loop have to count by one?
No. The increment can be any valid C++ expression. i += 5 counts in steps of 5, and x = x * 1.5 gives a multiplicative, roughly logarithmic progression. The loop variable can also be a float, though integers are safer for exact comparisons.
Do I need pinMode() before analogWrite() in a for loop?
No. The analogWrite() reference says you do not need to call pinMode() to set the pin as an output first. You still need pinMode() for digitalWrite() on that pin, and the pin must support PWM.
What is the difference between break and continue in a for loop?
break ends the whole loop immediately. continue ends only the current pass, and the loop then moves on to the next iteration. Both work in for, while and do...while loops.

Sources