How do you plan to solve it?
I will connect a push button to a GPIO pin and use timing functions (millis()
) to measure the duration and sequence of button presses. A short press will be detected as a single click, two quick presses within a short interval will be recognized as a double click, and holding the button beyond a threshold time will be identified as a long press. Finally, I will print the detected action to the Serial Monitor for verification.
/*Paste your code here*/
#define BUTTON_PIN 2 // Button connected to pin 2
// Timing settings
#define DEBOUNCE_DELAY 50
#define DOUBLE_CLICK_TIME 400
#define LONG_PRESS_TIME 1000
// Variables
unsigned long lastPressTime = 0;
unsigned long buttonDownTime = 0;
unsigned long lastButtonChangeTime = 0;
bool buttonPressed = false;
int pressCount = 0;
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN);
unsigned long currentTime = millis();
// Debounce check
if (currentTime - lastButtonChangeTime > DEBOUNCE_DELAY) {
// Button pressed
if (buttonState == LOW && !buttonPressed) {
buttonPressed = true;
buttonDownTime = currentTime;
lastButtonChangeTime = currentTime;
}
// Button released
if (buttonState == HIGH && buttonPressed) {
buttonPressed = false;
unsigned long pressDuration = currentTime - buttonDownTime;
lastButtonChangeTime = currentTime;
if (pressDuration >= LONG_PRESS_TIME) {
Serial.println("Long press detected");
pressCount = 0;
} else {
if (currentTime - lastPressTime <= DOUBLE_CLICK_TIME) {
Serial.println("Double click detected");
pressCount = 0;
} else {
pressCount = 1;
}
lastPressTime = currentTime;
}
}
}
// Handle single click if no second click comes
if (pressCount == 1 && (currentTime - lastPressTime > DOUBLE_CLICK_TIME)) {
Serial.println("Single click detected");
pressCount = 0;
}
}