ESP32 Knight Rider LED
6 LEDs moving sequentially from left to right and right to left (Knight Rider style). A basic example of using for loops and arrays. Teaches the logic of direction change.

Video
Elektr sxemasi

Manba kodi
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// ESP32 Knight Rider LED
4// ─────────────────────────────────────────
5// The 6 LEDs light up one by one from left to right, then back from right
6// to left (Knight Rider effect). Shows arrays and two-way for loops.
7//
8// Pins:
9// GPIO 5, 18, 19, 21, 22, 23 -> 6 LEDs (in order)
10// Each LED with a 330 ohm resistor, cathodes to GND
11
12const int LED_PINS[] = {5, 18, 19, 21, 22, 23}; // LED pins, in order
13const int LED_COUNT = 6; // Number of LEDs
14const int DELAY_MS = 100; // On time per LED (ms)
15
16void setup() {
17 // Set all LED pins as outputs
18 for (int i = 0; i < LED_COUNT; i++) {
19 pinMode(LED_PINS[i], OUTPUT);
20 }
21}
22
23void loop() {
24 // Right
25 for (int i = 0; i < LED_COUNT; i++) {
26 digitalWrite(LED_PINS[i], HIGH);
27 delay(DELAY_MS);
28 digitalWrite(LED_PINS[i], LOW);
29 }
30 // Left: the end LEDs are skipped so the bounce looks seamless
31 for (int i = LED_COUNT - 2; i >= 1; i--) {
32 digitalWrite(LED_PINS[i], HIGH);
33 delay(DELAY_MS);
34 digitalWrite(LED_PINS[i], LOW);
35 }
36}
37
Ko‘p so‘raladigan savollar
Is the ESP32's current sufficient for 6 LEDs?
The recommended current for each GPIO is approximately 20 mA; with a 330 Ω resistor, each LED draws 3–5 mA. Since only one LED is lit at a time, the total current is very low.
Why do we keep the pins in an array?
Since the pin numbers aren't sequential (5, 18, 19, 21, 22, 23), using an array makes it easier to access them one by one in a loop. When adding an LED, update both the LED_PINS array and LED_COUNT; to change only the order, editing the array is sufficient.
Can I speed up the effect?
Reduce the delay() value between steps. A value between 40 and 80 ms produces a smooth "Knight Rider" effect.
Can I use LED strips instead of LEDs?
Yes, with a WS2812B (NeoPixel) addressable strip, you can drive hundreds of LEDs from a single pin and make each one light up in a different color. A separate 5 V power supply is required for long strips.
