// https://www.instructables.com/Arduino-Dual-Function-Button-Long-PressShort-Press/
// if the button is reading HIGH (when pressed)
int LED1 = 8;
int LED2 = 13;
int button = 3;
boolean LED1State = false;
boolean LED2State = false;
long buttonTimer = 0;
long longPressTime = 1200;
boolean buttonActive = false;
boolean longPressActive = false;
unsigned long debounceTime = 100;
void checkButton() {
static unsigned long longPressCount = 0;
static unsigned long shortPressCount = 0;
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
unsigned long timeDiff;
timeDiff = interruptTime - lastInterruptTime;
if (timeDiff > debounceTime) {
// 按下按钮
if (digitalRead(button) == HIGH) {
if (buttonActive == false) {
buttonActive = true;
buttonTimer = millis();
}
if ((millis() - buttonTimer > longPressTime) && (longPressActive == false)) {
++longPressCount;
longPressActive = true;
LED2State = !LED2State;
digitalWrite(LED2, LED2State);
Serial.print("A long press is detected, led2: ");
Serial.print(LED2State);
Serial.print("shortPressCount: ");
Serial.print(shortPressCount);
Serial.print(", longPressCount: ");
Serial.println(longPressCount);
}
}
// 松开按钮
else {
if (buttonActive == true) {
// 长按松开触发
if (longPressActive == true) {
longPressActive = false;
}
else {
++shortPressCount;
LED1State = !LED1State;
digitalWrite(LED1, LED1State);
Serial.print("A short press is detected, led1: ");
Serial.print(LED1State);
}
buttonActive = false;
Serial.print("shortPressCount: ");
Serial.print(shortPressCount);
Serial.print(", longPressCount: ");
Serial.println(longPressCount);
}
}
lastInterruptTime = interruptTime;
}
}
void setup() {
Serial.begin(9600);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
digitalWrite(LED2, LED2State ? HIGH : LOW);
pinMode(button, INPUT);
}
void loop() {
checkButton();
}