#define pin_led 13 // 控制LED的亮灭#define pin_button 2 // 用于读取按钮状态
const unsigned long doubleClickTime = 300; // 双击的时间阈值(毫秒)const unsigned long longPressTime = 1000; // 长按的时间阈值(毫秒)
bool buttonState = digitalRead(pin_button); // 初始读取按钮状态bool lastButtonState = buttonState; // 上一个循环中的按钮状态
bool ledState = false; // LED的当前状态bool buttonPressed = false; // 按键是否被按下的标志unsigned long lastPressTime = 0; // 上次按键被按下的时间unsigned long pressDuration = 0; // 按键按下的持续时间bool doubleClickDetected = false; // 是否检测到双击
void setup() { Serial.begin(9600); pinMode(pin_led, OUTPUT); // LED引脚设为输出模式 pinMode(pin_button, INPUT_PULLUP); // 按键引脚设为上拉输入模式 digitalWrite(pin_led, ledState); // 初始化LED状态}
void loop() { bool currentButtonState = digitalRead(pin_button) == LOW; // 按键是否被按下(低电平)
if (currentButtonState && !buttonPressed) { // 按键刚刚被按下 lastPressTime = millis(); buttonPressed = true; } else if (!currentButtonState && buttonPressed) { // 按键刚刚被释放 pressDuration = millis() - lastPressTime; if (pressDuration < doubleClickTime) { // 检查是否是双击 if (millis() - lastPressTime < doubleClickTime && doubleClickDetected) { // 双击逻辑(立即熄灭灯并重置状态) ledState = false; digitalWrite(pin_led, ledState); Serial.println("Double click detected: LED off"); // 重置双击检测标志和上次按键时间 doubleClickDetected = false; lastPressTime = 0; } else { // 单击逻辑(切换LED状态) doubleClickDetected = true; // 设置双击检测标志,等待下一次按键释放来确认 // 注意:这里不立即切换LED状态,因为需要等待确认是否双击 } } else if (pressDuration >= longPressTime) { // 长按逻辑(灯闪烁) for(int i = 0; i < 100; i++) { ledState = !ledState; // 切换LED状态 digitalWrite(pin_led, ledState); delay(100); // 闪烁间隔 ledState = !ledState; // 再次切换LED状态,实现闪烁效果 digitalWrite(pin_led, ledState); Serial.println("Long press detected: LED flash"); // 重置状态 if (currentButtonState != lastButtonState) { // 按钮状态已改变,跳出循环 break; } buttonPressed = false; doubleClickDetected = false; lastPressTime = 0;} } else { // 既不是双击也不是长按,处理单击(但需要在双击确认后) // 重置双击检测标志和按钮按下标志 doubleClickDetected = false; buttonPressed = false; if (!doubleClickDetected) { // 单击逻辑(切换LED状态,但这里实际上会在双击确认后的下一次按下时执行) ledState = !ledState; digitalWrite(pin_led, ledState); Serial.println("Single click detected: LED toggled"); } } }
// 如果没有按键活动,重置双击检测标志(防止误判) if (millis() - lastPressTime > doubleClickTime * 2) { doubleClickDetected = false; }}