Bench NotesUno handbook

For Loops: Fades and Repeats

Use for loops to fade an LED in and out and to repeat a blink a set number of times.

BeginnerLEDResistor

Overview

A for loop has three parts: a start, a condition checked before each pass, and a step applied after each pass. for (int i = 0; i < 5; i++) runs with i = 0, 1, 2, 3, 4.

You will need

  • Arduino Uno R3
  • LED and 330 Ω resistor
  • Breadboard

Wiring

Uno pinConnects toNotes
9330 Ω → LED anodePWM pin
GNDLED cathode
Wiring for For Loops: Fades and RepeatsArduino Uno D9 (~PWM) to LED anode through 330 Ω; Arduino Uno GND to LED cathode.Connections (each line is one wire)Arduino UnoLEDD9 (~PWM)anode330 ΩGNDcathode
Original wiring diagram. Each line is one jumper wire; boxes on a line are series resistors.

The sketch

for_loop_breathing.ino
const int LED_PIN = 9;   // PWM pin

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

void loop() {
  // Fade in: 0, 5, 10 ... 255
  for (int level = 0; level <= 255; level += 5) {
    analogWrite(LED_PIN, level);
    delay(20);
  }
  // Fade out
  for (int level = 255; level >= 0; level -= 5) {
    analogWrite(LED_PIN, level);
    delay(20);
  }
  delay(400);

  // Three quick blinks
  for (int blink = 0; blink < 3; blink++) {
    digitalWrite(LED_PIN, HIGH);
    delay(100);
    digitalWrite(LED_PIN, LOW);
    delay(150);
  }
  delay(600);
}

How the code works

Watch the loop bounds: <= 255 includes 255; < 255 would stop at 250. Counting down needs >= 0 and -=. Use int, not byte, for the counter: a byte can never exceed 255, so level <= 255 would always be true and the loop would never end.

What you should observe

  • The LED breathes in and out over about two seconds, then blinks three times.