All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

Code

/*Paste your code here*/
#define BUTTON_PIN 2   // Push-button connected to D2

unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

unsigned long pressTime = 0;
unsigned long releaseTime = 0;
bool buttonState = HIGH;
bool lastButtonState = HIGH;

int clickCount = 0;
unsigned long lastClickTime = 0;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);   // enable internal pull-up
  Serial.begin(9600);                  // open serial terminal
}

void loop() {
  bool reading = digitalRead(BUTTON_PIN);

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

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

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

      // Button released
      else {
        releaseTime = millis();
        unsigned long pressDuration = releaseTime - pressTime;

        if (pressDuration > 1000) {
          Serial.println("Long Press");
          clickCount = 0;
        } else {
          clickCount++;
          lastClickTime = millis();
        }
      }
    }
  }

  // Check for single/double click after timeout
  if (clickCount > 0 && (millis() - lastClickTime) > 500) {
    if (clickCount == 1) {
      Serial.println("Single Click");
    } else if (clickCount == 2) {
      Serial.println("Double Click");
    }
    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!