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   // Button connected to pin 2

// Timing settings
#define DEBOUNCE_DELAY 50
#define DOUBLE_CLICK_TIME 400
#define LONG_PRESS_TIME 1000

// Variables
unsigned long lastPressTime = 0;
unsigned long buttonDownTime = 0;
unsigned long lastButtonChangeTime = 0;
bool buttonPressed = false;
int pressCount = 0;

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

void loop() {
  int buttonState = digitalRead(BUTTON_PIN);
  unsigned long currentTime = millis();

  // Debounce check
  if (currentTime - lastButtonChangeTime > DEBOUNCE_DELAY) {
    // Button pressed
    if (buttonState == LOW && !buttonPressed) {
      buttonPressed = true;
      buttonDownTime = currentTime;
      lastButtonChangeTime = currentTime;
    }

    // Button released
    if (buttonState == HIGH && buttonPressed) {
      buttonPressed = false;
      unsigned long pressDuration = currentTime - buttonDownTime;
      lastButtonChangeTime = currentTime;

      if (pressDuration >= LONG_PRESS_TIME) {
        Serial.println("Long press detected");
        pressCount = 0;
      } else {
        if (currentTime - lastPressTime <= DOUBLE_CLICK_TIME) {
          Serial.println("Double click detected");
          pressCount = 0;
        } else {
          pressCount = 1;
        }
        lastPressTime = currentTime;
      }
    }
  }

 

 

 

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!