Arduino LED Chaser|| Sequential LED Blinker || Chaser LED
Iterative Arrays: The Sequential LED Chaser
ผู้เริ่มต้นมักจะทำลายโค้ดของตนเองโดยการเขียน digitalWrite(2, HIGH); delay(100); digitalWrite(2, LOW); digitalWrite(3, HIGH)... ยาวเป็นร้อยบรรทัด เพียงเพื่อทำให้ LED 10 ดวงไล่กันไปมาเป็นเส้นตรง! Sequential LED Chaser ปฏิวัติสถาปัตยกรรมโปรแกรมอย่างสมบูรณ์และสะอาดตา! ด้วยการกำหนดหมายเลขขา Arduino ฮาร์ดแวร์อย่างชัดเจนลงใน One-Dimensional Integer Array นักพัฒนาสามารถใช้ for loop ขนาดใหญ่ได้อย่างเคร่งครัด ซึ่งบีบอัดลำดับ delay ที่วุ่นวายและจัดการไม่ได้กว่า 100 บรรทัด ให้เหลือเพียงสี่บรรทัดที่สง่างามของการวนซ้ำใน C++ อย่างแท้จริง!

ทำความเข้าใจสถาปัตยกรรม for Loop ของ C++
Physical array ทำหน้าที่เหมือนตู้เก็บเอกสารที่จัดระเบียบหมายเลขขาฮาร์ดแวร์ได้อย่างเรียบร้อยโดยอัตโนมัติ
int pinArray[] = {2, 3, 4, 5, 6, 7};(Index 0 แทน Pin 2!)forloop ทำหน้าที่เป็นกลไกการเพิ่มค่าทางคณิตศาสตร์ที่สมบูรณ์แบบ:for (int i = 0; i < 6; i++)- กลไกที่ทรงพลังนี้จะใส่ค่า
iเข้าไปใน array อย่างแม่นยำ:digitalWrite(pinArray[i], HIGH); - มันจะ "ON", รอ
100msอย่างแม่นยำ, "OFF" และกระโดดไปยังขาฮาร์ดแวร์ถัดไปทันที!
int ledPins[] = { 2, 3, 4, 5, 6, 7 }; // The hardware matrix array!
int pinCount = 6;
int timer = 80; // The execution speed of the Light Chaser completely!
void setup() {
// Ultra-efficient pinMode iteration utilizing the Array seamlessly!
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// Knight-Rider Ping-Pong Execution Matrix!
// SCAN COMPLETELY FORWARD!
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
digitalWrite(ledPins[thisPin], HIGH); // Ignite!
delay(timer); // Render frame!
digitalWrite(ledPins[thisPin], LOW); // Extinguish!
}
// SCAN COMPLETELY BACKWARD!
// Start explicit math at index 4 (Because index 5 is the absolute edge!)
for (int thisPin = pinCount - 2; thisPin > 0; thisPin--) {
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
digitalWrite(ledPins[thisPin], LOW);
}
}
กำจัดอันตรายจาก "Cylon" Ghosting
หากคุณต่อ LED สีแดง 6 ดวงเข้าด้วยกันโดยไม่มีตัวต้านทาน 220-Ohm วงจร micro-capacitor ภายใน Arduino die จะไม่สามารถคายประจุได้อย่างถูกต้องและปลอดภัย!
- สิ่งนี้ทำให้เกิด "Ghosting" โดยที่ LED ข้างเคียงเรืองแสงจางๆ อย่างควบคุมไม่ได้!
- ที่แย่กว่านั้น การต่อพ่วง LED เข้ากับ
GNDโดยตรงรับประกันว่าจะมีการดึงกระแสไฟเกิน100mAพร้อมกันในช่วงลำดับที่รวดเร็ว ซึ่งจะทำให้ voltage regulators ของ ATmega328P เสียหายอย่างสิ้นเชิง! - คุณต้องบัดกรี/ใช้ breadboard ตัวต้านทาน
Six 220-Ohmแยก LED แต่ละดวงออกจาก output pin ที่เกี่ยวข้องอย่างสมบูรณ์แบบ!
การกำหนดค่าฮาร์ดแวร์ Output Array
- Arduino Uno/Nano (จัดการการวนซ้ำ array-bounds อย่างต่อเนื่อง)
- 6x 5mm LEDS ที่เหมือนกัน (สีแดงหรือสีน้ำเงินจะสร้างเอฟเฟกต์การสแกนแบบ Cylon ที่น่าทึ่งที่สุด)
- 6x 220-Ohm Resistors (จำกัดกระแสไฟอย่างเคร่งครัดทั่วทั้ง processor!)
- An Analog Potentiometer (ไม่บังคับ) (หากคุณต่อ knob เข้ากับ
A0คุณสามารถแมปanalogReadลงในตัวแปรtimerได้อย่างราบรื่น ทำให้ผู้ใช้สามารถปรับความเร็วของลำดับการไล่ LED ได้แบบเรียลไทม์อย่างไม่มีที่ติ!)