Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

// Pin definitions
const int BUTTON_PIN = 2;

// Timing constants
const unsigned long DEBOUNCE_TIME = 50;   // ms
const unsigned long DOUBLE_CLICK_GAP = 300; // max time between clicks
const unsigned long LONG_PRESS_TIME = 800;  // ms to trigger long press

// State variables
int lastButtonState = HIGH;
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongPressed = false;
int clickCount = 0;

void setup() {
  Serial.begin(9600);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.println("System Ready: Single, Double, and Long Press detection");
}

void loop() {
  int buttonState = digitalRead(BUTTON_PIN);

  // Button is pressed (LOW because of INPUT_PULLUP)
  if (buttonState == LOW && lastButtonState == HIGH) {
    pressedTime = millis();
    isPressing = true;
    isLongPressed = false;
  }

  // Button is released
  if (buttonState == HIGH && lastButtonState == LOW) {
    releasedTime = millis();
    isPressing = false;
    
    unsigned long pressDuration = releasedTime - pressedTime;

    if (pressDuration < LONG_PRESS_TIME && pressDuration > DEBOUNCE_TIME) {
      clickCount++;
    }
  }

  // Check for Long Press while button is held down
  if (isPressing && !isLongPressed) {
    if (millis() - pressedTime > LONG_PRESS_TIME) {
      Serial.println("Action: LONG PRESS");
      isLongPressed = true;
      clickCount = 0; // Reset clicks if it's a long press
    }
  }

  // Check for Single vs Double Click after the gap has passed
  if (!isPressing && clickCount > 0) {
    if (millis() - releasedTime > DOUBLE_CLICK_GAP) {
      if (clickCount == 1) {
        Serial.println("Action: SINGLE CLICK");
      } else if (clickCount >= 2) {
        Serial.println("Action: DOUBLE CLICK");
      }
      clickCount = 0;
    }
  }

  lastButtonState = buttonState;
}
*Paste your code here*/

 

 

 

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!