How do you plan to solve it?
const int buttonPin = 13;
int lastReading = HIGH;
int stableState = HIGH;
unsigned long lastDebounce = 0;
const unsigned long debounceDelay = 50;
unsigned long pressTime = 0;
unsigned long lastClickTime = 0;
int clickCount = 0;
const unsigned long doubleDelay = 300;
const unsigned long longPressTime = 800;
bool longDetected = false;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Serial Monitor Ready (9600)");
}
void loop() {
int reading = digitalRead(buttonPin);
// simple debounce
if (reading != lastReading) {
lastDebounce = millis();
}
if (millis() - lastDebounce > debounceDelay) {
if (reading != stableState) {
stableState = reading;
// pressed (HIGH -> LOW)
if (stableState == LOW) {
pressTime = millis();
longDetected = false;
}
// released (LOW -> HIGH)
else {
unsigned long held = millis() - pressTime;
// if it was a long press
if (!longDetected && held >= longPressTime) {
Serial.println("Long press detected");
clickCount = 0; // clear pending clicks
}
// short press: count it for single/double
else if (!longDetected) {
clickCount++;
lastClickTime = millis();
}
}
}
}
// while button is held, detect long press once
if (stableState == LOW && !longDetected) {
if (millis() - pressTime >= longPressTime) {
Serial.println("Long press detected");
longDetected = true;
clickCount = 0; // don't treat a long press as clicks
}
}
if (clickCount > 0 && (millis() - lastClickTime > doubleDelay)) {
if (clickCount == 1) Serial.println("Single click detected");
else if (clickCount == 2) Serial.println("Double click detected");
clickCount = 0;
}
lastReading = reading;
}