
Video
Gambar Rajah Litar

Kod Sumber
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// LED Chaser
4// ─────────────────────────────────────────
5// The 6 LEDs light up one after another for 150 ms each, so the light
6// walks along the row. Shows multi-pin control with an array and a for
7// loop.
8//
9// Pins:
10// D2, D3, D4, D5, D6, D7 -> 6 LEDs (in order)
11// Each LED with a 330 ohm resistor
12
13int ledPins[] = {2, 3, 4, 5, 6, 7}; // LED pins in lighting order
14
15void setup() {
16 // Set all LED pins as outputs
17 for(int i = 0; i < 6; i++) {
18 pinMode(ledPins[i], OUTPUT);
19 }
20}
21
22void loop() {
23 // Light each LED in turn for 150 ms
24 for(int i = 0; i < 6; i++) {
25 digitalWrite(ledPins[i], HIGH);
26 delay(150);
27 digitalWrite(ledPins[i], LOW);
28 }
29}
30
Soalan Lazim
Why is it better to use an array?
If you store the pin numbers in an array, you can use a for loop to cycle through all the LEDs in a single line of code. To change the number of LEDs in this code, you must update both the ledPins array and the i < 6 loop limits in setup() and loop(); you don't have to write a separate line for each LED.
If 6 LEDs light up at the same time, will the Arduino be damaged?
Assuming approximately 10 mA per LED, six LEDs draw about 60 mA. The recommended upper limit for a single pin is 20 mA; both individual pin and pin-group current limits must be observed. The 200 mA absolute maximum rating specified for the ATmega328P's VCC/GND pins is neither a normal operating target nor a current budget available solely for I/O.
How do I reverse the walking direction?
Set up the `for` loop in reverse order: `for (int i = 5; i >= 0; i--)`. This way, the light moves in the opposite direction. If you place the two loops one after the other, you’ll get a lightning bolt effect.
One of the LEDs isn't lit—what could be the reason?
The LED might be installed upside down, its leg might not be seated properly on the breadboard, or the resistor might be in a different row. You can determine whether the LED is defective or if there’s a connection issue by replacing it with a working LED.
