Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

/*Paste your code here*/
#define button 13

bool Curr_state;
bool prev_state = 0;

unsigned long pressStart = 0;
unsigned long lastRelease = 0;

bool clickPending = false;
int clickCount = 0;

const unsigned long debounce = 30;
const unsigned long doubleClickGap = 300;
const unsigned long longPressTime = 700;

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

void loop() {
  Curr_state = !digitalRead(button);  // pressed = 1

  unsigned long now = millis();

  // Button pressed
  if (Curr_state && !prev_state) {
    pressStart = now;
  }

  // Button released
  if (!Curr_state && prev_state) {
    unsigned long pressDuration = now - pressStart;

    if (pressDuration >= longPressTime) {
      Serial.println("Long Press detected");
      clickPending = false;
      clickCount = 0;
    } else {
      clickCount++;
      clickPending = true;
      lastRelease = now;
    }
  }

  // Handle single/double click timeout
  if (clickPending && (now - lastRelease > doubleClickGap)) {
    if (clickCount == 1) Serial.println("Single click detected");
    if (clickCount >= 2) Serial.println("Double click detected");

    clickPending = false;
    clickCount = 0;
  }

  prev_state = Curr_state;
}

 

 

 

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!