0
0
AutocadHow-ToBeginner · 3 min read

How to Control Multiple LEDs in Arduino: Simple Guide

To control multiple LEDs in Arduino, connect each LED to a separate digital pin and use pinMode() to set pins as outputs. Then use digitalWrite() to turn each LED on or off individually or in a loop.
📐

Syntax

To control LEDs, you use these main commands:

  • pinMode(pin, OUTPUT); sets the pin as an output to control an LED.
  • digitalWrite(pin, HIGH); turns the LED on by sending voltage.
  • digitalWrite(pin, LOW); turns the LED off by stopping voltage.

You repeat these commands for each LED connected to different pins.

arduino
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH); // LED ON
digitalWrite(pin, LOW);  // LED OFF
💻

Example

This example controls three LEDs connected to pins 2, 3, and 4. It turns each LED on and off one by one in a loop.

arduino
const int ledPins[] = {2, 3, 4};
const int ledCount = 3;

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); // LED ON
    delay(500);                    // wait half a second
    digitalWrite(ledPins[i], LOW);  // LED OFF
  }
}
Output
LED on pin 2 lights up for 0.5 seconds, then off; then pin 3 LED lights up for 0.5 seconds, then off; then pin 4 LED lights up for 0.5 seconds, then off; repeats.
⚠️

Common Pitfalls

Common mistakes when controlling multiple LEDs include:

  • Not setting pins as OUTPUT with pinMode(), so LEDs won't light.
  • Connecting LEDs without resistors, which can damage LEDs or Arduino.
  • Using the same pin for multiple LEDs without proper wiring, causing unexpected behavior.
  • Forgetting to turn LEDs off (digitalWrite(pin, LOW)), leaving them always on.
arduino
/* Wrong: Missing pinMode setup */
void setup() {
  // pinMode not called
}

void loop() {
  digitalWrite(2, HIGH); // LED may not turn on
}

/* Right: Proper pinMode setup */
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, HIGH); // LED turns on
}
📊

Quick Reference

Tips for controlling multiple LEDs:

  • Use arrays to store LED pins for easy looping.
  • Always use a resistor (220Ω to 330Ω) with each LED.
  • Set each pin as OUTPUT in setup().
  • Use digitalWrite() to turn LEDs on/off.
  • Use delay() to add visible timing between LED changes.

Key Takeaways

Set each LED pin as OUTPUT using pinMode() before controlling it.
Use digitalWrite(pin, HIGH) to turn an LED on and LOW to turn it off.
Connect each LED with a resistor to protect the LED and Arduino.
Use arrays and loops to control many LEDs efficiently.
Always test your wiring and code step-by-step to avoid mistakes.