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 BUTTON_PIN = 10;
const unsigned long DEBOUNCE = 50, DOUBLECLICK = 400, LONGPRESS = 800;

unsigned long lastChange = 0, pressStart = 0, lastRelease = 0;
int lastReading = HIGH, state = HIGH;
byte clicks = 0;
bool longReported = false;

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

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

if (reading != lastReading) lastChange = millis();

if (millis() - lastChange > DEBOUNCE && reading != state) {
state = reading;

if (state == LOW) {
pressStart = millis();
longReported = false;
} else { // released
unsigned long dur = millis() - pressStart;
if (!longReported) {
if (dur >= LONGPRESS) Serial.println("Long Press");
else { clicks++; lastRelease = millis(); }
}
}
}

if (state == LOW && !longReported && millis() - pressStart >= LONGPRESS) {
Serial.println("Long Press");
longReported = true;
clicks = 0;
}

if (clicks > 0 && millis() - lastRelease > DOUBLECLICK) {
if (clicks == 1) Serial.println("Single Click");
else if (clicks == 2) Serial.println("Double Click");
clicks = 0;
}
lastReading = reading;
}

 

 

 

Output

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!