All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 To distinguish between a single click, a double click, and a long press using a single push-button, you'll need a combination of simple hardware and smart software. The hardware setup is easy: just wire the button to a microcontroller pin and use a pull-up resistor. On the software side, the microcontroller constantly checks if the button has been pressed. When it detects a press, it starts a timer. If the button is held down past a specific time limit, it's a long press. If the button is released quickly, the program then waits for a short period to see if a second press occurs. If a second press happens within that window, it's a double click. If the time window closes without a second press, the initial action is logged as a single click. This method relies on timing and tracking the button's state to accurately differentiate between the three types of presses.

 

 

 

Code

/*Paste your code here*/

const int buttonPin = 2;  


 

unsigned long lastDebounceTime = 0;

unsigned long debounceDelay = 50;

unsigned long lastClickTime = 0;

unsigned long pressStartTime = 0;


 

bool buttonState = HIGH;       // Current state of button

bool lastButtonState = HIGH;   // Previous state of button

int clickCount = 0;

bool longPressDetected = false;


 

void setup() {

  pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor

  Serial.begin(115200);

}


 

void loop() {

  int reading = digitalRead(buttonPin);


 

  // Debounce

  if (reading != lastButtonState) {

    lastDebounceTime = millis();

  }


 

  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (reading != buttonState) {

      buttonState = reading;


 

      // Button pressed

      if (buttonState == LOW) {

        pressStartTime = millis();

        longPressDetected = false;

      } 

      // Button released

      else {

        unsigned long pressDuration = millis() - pressStartTime;


 

        // Check for long press

        if (pressDuration >= 1000) {  

          Serial.println("Long press detected");

          longPressDetected = true;

          clickCount = 0;

        } else {

          clickCount++;

          if (clickCount == 1) {

            lastClickTime = millis();

          }

        }

      }

    }

  }


 

  // Single Click vs double click

  if (clickCount > 0 && !longPressDetected) {

    if ((millis() - lastClickTime) > 400) {  // 400 ms timeout for double click

      if (clickCount == 1) {

        Serial.println("Single click detected");

      } else if (clickCount == 2) {

        Serial.println("Double click detected");

      }

      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!