// 定义LED引脚
const int ledPin1 = 2;
const int ledPin2 = 3;
// 定义按钮引脚
const int buttonPin = 4;
// 定义一个数组,包含不同的亮灯时长(以毫秒为单位)
const int durations[] = {500, 1000, 1500, 2000, 2500, 3000};
const int arraySize = sizeof(durations) / sizeof(durations[0]);
// 用于存储当前哪个LED是活动的(0表示无活动,1表示LED1,2表示LED2)
int activeLED = 0;
// 用于存储上次按钮按下的时间
unsigned long lastButtonPressTime = 0;
// 定义按钮去抖时间(毫秒)
const unsigned long debounceDelay = 50;
void setup() {
// 初始化LED引脚为输出模式
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
// 初始化按钮引脚为输入模式,并启用内部上拉电阻
pinMode(buttonPin, INPUT_PULLUP);
// 确保LED初始状态为关闭
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
}
void loop() {
// 读取按钮状态
int buttonState = digitalRead(buttonPin);
// 检查按钮是否被按下(按钮连接了上拉电阻,所以按下时按钮状态为LOW)
if (buttonState == LOW) {
// 获取当前时间
unsigned long currentTime = millis();
// 检查按钮是否在上次检查后被按下(去抖)
if (currentTime - lastButtonPressTime > debounceDelay) {
// 重置上次按钮按下时间
lastButtonPressTime = currentTime;
// 随机选择一个LED(1或2)
int randomLED = random(1, 3); // 生成1或2的随机数
// 如果当前没有活动的LED或者选择了另一个LED,则切换
if (activeLED != randomLED && activeLED != 0) {
// 关闭当前活动的LED
if (activeLED == 1) {
digitalWrite(ledPin1, LOW);
} else if (activeLED == 2) {
digitalWrite(ledPin2, LOW);
}
}
// 设置新的活动LED
activeLED = randomLED;
// 从数组中随机选择一个亮灯时长
int randomDuration = durations[random(arraySize)];
// 打开选中的LED
if (activeLED == 1) {
digitalWrite(ledPin1, HIGH);
} else if (activeLED == 2) {
digitalWrite(ledPin2, HIGH);
}
// 等待指定的时长
delay(randomDuration);
// 关闭选中的LED
if (activeLED == 1) {
digitalWrite(ledPin1, LOW);
} else if (activeLED == 2) {
digitalWrite(ledPin2, LOW);
}
// 重置活动LED标志,以便下次按钮按下时可以再次选择
activeLED = 0;
}
}
}