All submissions

Single Double Click and Long Press Detection

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

/*Paste your code here*/
const int buttonPin = 2; // the number of the pushbutton pin

// Variables for tracking button state and time
int lastButtonState = LOW;
long lastPressTime = 0;
long lastReleaseTime = 0;
long longPressThreshold = 1500; // Time in milliseconds
long doubleClickThreshold = 500; // Time in milliseconds

void setup() {
  Serial.begin(9600); // Initialize serial communication at 9600 baud
  pinMode(buttonPin, INPUT_PULLUP); // Use INPUT_PULLUP to avoid external resistors
  Serial.println("Ready! Press the button to test single, double, and long press detection.");
}

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

  // If the button state changes
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) { // Button is pressed
      lastPressTime = millis();
    } else { // Button is released
      long pressDuration = millis() - lastPressTime;

      if (pressDuration > longPressThreshold) {
        Serial.println("Long press detected");
      } else {
        long timeSinceLastClick = millis() - lastReleaseTime;
        if (timeSinceLastClick < doubleClickThreshold) {
          Serial.println("Double click detected");
        } else {
          Serial.println("Single click detected");
        }
      }
      lastReleaseTime = millis();
    }
  }
  lastButtonState = buttonState;
}

 

 

 

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!