const int ledPins[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; // ตำแหน่งขาของ LED
int currentLED = 0; // LED ปัจจุบันที่ต้องการควบคุม
unsigned long previousMillis = 0;
const long interval = 364; // ช่วงเวลาระหว่างการสลับ LED
void setup() {
// กำหนดขา LED เป็น OUTPUT
for (int i = 0; i < 7; i++) {
pinMode(ledPins[i], OUTPUT);
}
// ตั้งค่า Timer 0 ให้ใช้ตัวแปร millis()
noInterrupts(); // ปิด Interrupts
TCCR0A = 0; // ตั้งโหมด Normal
TCCR0B = 0; // ปิด Timer 0
TCNT0 = 0; // ตั้งค่าค่าเริ่มต้นให้เป็น 0
OCR0A = 249; // ตั้งค่าค่าเปรียบเทียบให้เท่า 250
TCCR0B |= (1 << CS02); // ตั้งค่าตัวคูณให้เท่า 256
TIMSK0 |= (1 << OCIE0A); // อนุญาตให้ใช้ Interrupt จากการเปรียบเทียบ
interrupts(); // เปิด Interrupts
}
void loop() {
// ไม่ต้องทำอะไรใน loop() เนื่องจากการควบคุม LED ถูกจัดการในฟังก์ชัน ISR(TIMER0_COMPA_vect)
}
// ฟังก์ชันที่ถูกเรียกเมื่อ Timer 0 สร้าง Interrupt
ISR(TIMER0_COMPA_vect) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// ปิด LED ปัจจุบัน
digitalWrite(ledPins[currentLED], LOW);
// สลับไปยัง LED ถัดไป
currentLED = (currentLED + 1) % 7;
// เปิด LED ใหม่
digitalWrite(ledPins[currentLED], HIGH);
}
}