All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

const int buttonPin = 2;  

unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
unsigned long lastClickTime = 0;
unsigned long pressStartTime = 0;

bool buttonState = HIGH;       
bool lastButtonState = HIGH;   
int clickCount = 0;
bool longPressDetected = false;

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

void loop() {
  int reading = digitalRead(buttonPin);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == LOW) {
        pressStartTime = millis();
        longPressDetected = false;
      } 
      
      else {
        unsigned long pressDuration = millis() - pressStartTime;
        if (pressDuration >= 1000) {  
          Serial.println("Long press detected");
          longPressDetected = true;
          clickCount = 0;
        } else {
          clickCount++;
          if (clickCount == 1) {
            lastClickTime = millis();
          }
        }
      }
    }
  }

  // Single Click vs double click
  if (clickCount > 0 && !longPressDetected) {
    if ((millis() - lastClickTime) > 400) {  // 400 ms timeout for double click
      if (clickCount == 1) {
        Serial.println("Single click detected");
      } else if (clickCount == 2) {
        Serial.println("Double click detected");
      }
      clickCount = 0;
    }
  }

  lastButtonState = reading;
}

 

 

 

Output

Video

Add a video of the output (know more)

 

 

 

Submit Your Solution

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