/**
Simon Game for Arduino with Score display
Copyright (C) 2022, Uri Shaked
Released under the MIT License.
*/
/**
Set up the Arduino board and initialize Serial communication
*/
int ledPins[] = {9, 10, 11, 12};
int numLeds = 4;
int interval = 200; // 切换 LED 的时间间隔
volatile bool buttonPressed = false;
int direction = 1; // 1和-1转化
int currentLed = 0; // 索引
unsigned long previousMillis = 0; // 重置时间
void setup() {
pinMode(2, INPUT_PULLUP);
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
}
// 中断
attachInterrupt(digitalPinToInterrupt(2), onButtonPress, FALLING);
}
void loop() {
if (buttonPressed) {
direction = -direction; // 改变方向
buttonPressed = false; // 复位
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // 重置时间
// 使当前LED熄灭,亮下一个
digitalWrite(ledPins[currentLed], LOW);
// 根据方向更新当前 LED 索引
currentLed += direction;
if (currentLed >= numLeds) {
currentLed = 0; //第一个LED
} else if (currentLed < 0) {
currentLed = numLeds - 1; //第四个LED
}//根据索引的方向来进行第一个和第四个LED的转化
// 打开新的 LED
digitalWrite(ledPins[currentLed], HIGH);
}
}
// 中断
void onButtonPress() {
buttonPressed = true; // 标记按键被按下
}
// int i =1;
// for(i =1; i<=10;i++){
// for(int n =0;n<=3;n++){
// digitalWrite(ledPins[n],HIGH);
// delay(1000-i*100);
// //digitalWrite(ledPins[n],LOW);
// }
// for(int n=3;n>=0;n--){
// digitalWrite(ledPins[n],LOW);
// delay(1000-i*100);
// }
// }