/*
Make distinction between long and short press
Based on example at bottom of:
https://forum.arduino.cc/t/long-short-button-press-issue/472257/10
*/
#include <Bounce2.h>
#define buttonPin 8
// define times for short and long presses:
#define shortTime 250
#define longTime 1000
#define noEvent 0
#define shortPress 1
#define longPress 2
// Instantiate a Bounce object called button :
Bounce button = Bounce();
unsigned long buttonPressStartTimeStamp;
unsigned long buttonPressDuration;
boolean startTimeout = false;
boolean endTimeout = false;
byte event;
void setup()
{
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
button.attach(buttonPin);
button.interval(20);//set debounce interval
}
void loop()
{
event = checkButton();
switch (event)
{
case shortPress:
Serial.println("Short press");
break;
case longPress:
Serial.println("Long press");
break;
case noEvent:
// nothing...
break;
}
}
byte checkButton()
{
byte event = noEvent;
// Update the Bounce instance, does digitalRead of button
button.update();
// Button press transition from HIGH to LOW)
if (button.fell())
{
buttonPressStartTimeStamp = millis();
startTimeout = true;
}
// Button release transition from LOW to HIGH) :
if (button.rose())
{
buttonPressDuration = (millis() - buttonPressStartTimeStamp);
startTimeout = false;
}
if (buttonPressDuration > 0 && buttonPressDuration <= shortTime)
{
event = shortPress;
buttonPressDuration = 0;
}
if (startTimeout == true && (millis() - buttonPressStartTimeStamp) > longTime)
{
event = longPress;
startTimeout = false;
buttonPressDuration = 0;
}
return event;
}