AR-7Pertengahan

LED Chaser with Adjustable Speed

4.6(72)
148 selesai
LED Chaser with Adjustable Speed
Six LEDs light up one after another, so the light seems to run from one end to the other. Turn the potentiometer knob and the speed of that run changes instantly: one way and the light races along, the other way and each LED waits for almost a second. You see with your own eyes how a knob can set the speed of something.

Video

Gambar Rajah Litar

LED Chaser with Adjustable Speed - Gambar Rajah Litar

Kod Sumber

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   LED Chaser with Adjustable Speed
4// ─────────────────────────────────────────
5// A potentiometer sets the speed of the walking LED effect. A0 is read at
6// every step and its 0-1023 value becomes the delay time (ms).
7//
8// Pins:
9//   D2, D3, D4, D5, D6, D7 -> 6 LEDs (in order)
10//   Each LED with a 330 ohm resistor
11//   A0 -> Potentiometer wiper
12//   (outer legs to 5V and GND)
13
14int ledPins[] = {2, 3, 4, 5, 6, 7};   // LED pins in lighting order
15int potValue;                         // Pot value = delay (ms)
16
17void setup() {
18  // Set all LED pins as outputs
19  for(int i = 0; i < 6; i++) {
20    pinMode(ledPins[i], OUTPUT);
21  }
22}
23
24void loop() {
25  for(int i = 0; i < 6; i++) {
26    potValue = analogRead(A0);        // Read the speed (0-1023)
27    digitalWrite(ledPins[i], HIGH);
28    delay(potValue);                  // Wait as many ms as the pot value
29    digitalWrite(ledPins[i], LOW);
30  }
31}
32

Soalan Lazim

What values does `analogRead` return?

The Uno's analog inputs read 0–5 V with 10-bit resolution and return a value between 0 and 1023. As the potentiometer is turned from one end to the other, the value changes from 0 to 1023.

How do we convert the potentiometer reading to speed?

Using the `map()` function, you can convert the 0–1023 range to any delay range you want (e.g., 20–500 ms): `map(value, 0, 1023, 20, 500)`. When this value is used inside `delay()`, the speed changes instantly.

How do you connect the leads of a potentiometer?

The two outer pins are connected to 5 V and GND, and the middle pin (wiper) is connected to an analog input (e.g., A0). If you connect the outer pins in reverse, only the rotation direction will reverse; the circuit will not be damaged.

Changes in speed are detected with a delay—why?

If the potentiometer is read only at the beginning of the loop, the new value is not applied until all the LEDs have lit up. If you include the reading within each LED step, the speed changes instantly.