DEV Community

Hedy
Hedy

Posted on

How to code LED lights on Arduino?

Here are the most common ways to “code LED lights” on Arduino, with working examples. (Assuming Arduino Nano/Uno.)

1) Blink one LED (basic)

Wiring: LED anode → D13 (or any digital pin) through 220–330Ω resistor, LED cathode → GND
(Or use the built-in LED on D13.)

const int LED_PIN = 13;

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

void loop() {
  digitalWrite(LED_PIN, HIGH);
  delay(500);
  digitalWrite(LED_PIN, LOW);
  delay(500);
}
Enter fullscreen mode Exit fullscreen mode

2) LED controlled by a button

Wiring: Button from D2 to GND (use internal pull-up)

const int LED_PIN = 13;
const int BTN_PIN = 2;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BTN_PIN, INPUT_PULLUP);   // button to GND
}

void loop() {
  bool pressed = (digitalRead(BTN_PIN) == LOW);

Enter fullscreen mode Exit fullscreen mode

digitalWrite(LED_PIN, pressed ? HIGH : LOW);
}

3) Fade an LED (PWM “dimming”)

Use a PWM pin (Nano/Uno: 3,5,6,9,10,11).

const int LED_PIN = 9;

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

void loop() {
  for (int v = 0; v <= 255; v++) {   // fade up
    analogWrite(LED_PIN, v);
    delay(5);
  }
  for (int v = 255; v >= 0; v--) {   // fade down
    analogWrite(LED_PIN, v);
    delay(5);
  }
}
Enter fullscreen mode Exit fullscreen mode

4) Blink without delay() (non-blocking)

Best if you want to do other things at the same time (read sensors, buttons, etc.).

const int LED_PIN = 13;
unsigned long lastToggle = 0;
const unsigned long intervalMs = 500;
bool ledState = false;

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

void loop() {
  unsigned long now = millis();
  if (now - lastToggle >= intervalMs) {
    lastToggle = now;
    ledState = !ledState;
    digitalWrite(LED_PIN, ledState);
  }

  // Do other work here without being blocked by delay()
}
Enter fullscreen mode Exit fullscreen mode

5) Addressable LED strip (WS2812 / NeoPixel)

If you mean “LED lights” like RGB strips (WS2812B), code is different.

Wiring (important):

  • Strip DIN → Arduino D6 (example)
  • 5V → external 5V supply (not from Arduino for more than a few LEDs)
  • GND of supply ↔ Arduino GND (must share ground)
  • Add 330Ω resistor in series with DIN
  • Add 1000µF capacitor across 5V/GND near the strip

Code (Adafruit NeoPixel library):

#include <Adafruit_NeoPixel.h>

const int LED_PIN = 6;
const int LED_COUNT = 30;

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();            // turn off all
  strip.setBrightness(80); // 0-255
}

void loop() {
  // Red wipe
  for (int i = 0; i < LED_COUNT; i++) {
    strip.setPixelColor(i, strip.Color(255, 0, 0));
    strip.show();
    delay(30);
  }

  // Clear
  strip.clear();
  strip.show();
  delay(300);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)