All submissions

Single Double Click and Long Press Detection

Solving Approach

simulation

 
 

 

 

 

Code

const int buttonPin = 7; 

int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
unsigned long lastClickTime = 0;
const int doubleClickTime = 300; 
const int longPressTime = 1000;  

void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT);
}

void loop() {
int reading = digitalRead(buttonPin);

if (reading != lastButtonState) {
lastDebounceTime = millis();
}

if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;

if (buttonState == HIGH) {
if (millis() - lastClickTime < doubleClickTime) {
Serial.println("Double click detected");
lastClickTime = 0; 
} else {
lastClickTime = millis();
}
}
}
}

if (buttonState == HIGH && (millis() - lastClickTime) > longPressTime && lastClickTime != 0) {
Serial.println("Long press detected");
lastClickTime = 0; 
} else if (buttonState == LOW && (millis() - lastClickTime) > doubleClickTime && lastClickTime != 0) {

if ((millis() - lastClickTime) < longPressTime) {
Serial.println("Single click detected");
lastClickTime = 0;
}
}

lastButtonState = reading;
}

 

 

 

Output

Video

Add a video of the output (know more)

https://wokwi.com/projects/442622944659044353 

 

 

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!