Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

const int buttonPin = 2;

unsigned long pressTime = 0;
unsigned long releaseTime = 0;
unsigned long lastClickTime = 0;

bool waitingForSecondClick = false;

const unsigned long debounceTime = 50;
const unsigned long longPressTime = 1000;
const unsigned long doubleClickGap = 400;

bool lastButtonState = HIGH;

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

void loop() {
  bool buttonState = digitalRead(buttonPin);

  // Button pressed
  if (lastButtonState == HIGH && buttonState == LOW) {
    pressTime = millis();
  }

  // Button released
  if (lastButtonState == LOW && buttonState == HIGH) {
    releaseTime = millis();
    unsigned long pressDuration = releaseTime - pressTime;

    if (pressDuration >= longPressTime) {
      Serial.println("Long Press");
      waitingForSecondClick = false;
    } else {
      if (waitingForSecondClick &&
          (releaseTime - lastClickTime <= doubleClickGap)) {
        Serial.println("Double Click");
        waitingForSecondClick = false;
      } else {
        waitingForSecondClick = true;
        lastClickTime = releaseTime;
      }
    }
  }

  // Single click confirmation
  if (waitingForSecondClick &&
      (millis() - lastClickTime > doubleClickGap)) {
    Serial.println("Single Click");
    waitingForSecondClick = false;
  }

  lastButtonState = buttonState;
}

 

 

 

Output

Video

Add a video of the output (know more)

 

 

Upvote
Downvote

Submit Your Solution

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