All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 To solve the problem of detecting single clicks, double clicks, and long presses using a push-button connected to a microcontroller like the ESP32, I would implement a non-blocking timing-based algorithm that monitors the button state and evaluates the duration and sequence of presses. The button would be connected to a GPIO pin configured with an internal pull-up resistor, and its state would be read using digital input. By tracking the time when the button is pressed and released using the  function, I can calculate how long the button was held down. If the duration exceeds a predefined threshold it would be classified as a long press. For single and double clicks, I would count the number of presses within a short time window and use a counter to differentiate between one and two quick taps. Debouncing logic would be included to filter out false triggers caused by mechanical noise. The result of each interaction whether a single click, double click, or long press would be printed to the serial monitor for verification. 
 

 

 

 

Code

const int buttonPin = 4;
unsigned long lastPressTime = 0;
unsigned long pressStartTime = 0;
bool buttonState = false;
bool lastButtonState = false;
int clickCount = 0;

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

void loop() {
  buttonState = !digitalRead(buttonPin); // Active LOW

  if (buttonState && !lastButtonState) {
    pressStartTime = millis();
  }

  if (!buttonState && lastButtonState) {
    unsigned long pressDuration = millis() - pressStartTime;

    if (pressDuration > 1000) {
      Serial.println("Long press detected");
      clickCount = 0;
    } else {
      clickCount++;
      if (clickCount == 1) lastPressTime = millis();
      else if (clickCount == 2 && millis() - lastPressTime < 500) {
        Serial.println("Double click detected");
        clickCount = 0;
      }
    }
  }

  if (clickCount == 1 && millis() - lastPressTime > 500) {
    Serial.println("Single click detected");
    clickCount = 0;
  }

  lastButtonState = buttonState;
}


 

 

 

Output

Video

Add a video of the output (know more)

https://drive.google.com/file/d/1D_Sea6-yUl1zhcpEmgkxvHSYFIl-uVHh/view?usp=drive_link

 

 

 

Submit Your Solution

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