/*
Forum: https://forum.arduino.cc/t/trying-to-make-a-short-and-long-press-function-with-button/1221545
Wokwi: https://wokwi.com/projects/389182520812865537
2024/02/08
ec2021
*/
const byte buttonPin = 2;
unsigned long pressTime = 0;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
Serial.println("Start");
}
void loop() {
// put your main code here, to run repeatedly:
if (buttonReleased(pressTime)) {
Serial.println(pressTime);
}
}
boolean buttonReleased(unsigned long &buttonPressTime) {
static unsigned long downTime;
static unsigned long lastChange = 0;
static byte lastState = HIGH;
static byte state = HIGH;
byte actState = digitalRead(buttonPin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
}
if (actState != state && millis() - lastChange > 20) {
state = actState;
if (state) {
buttonPressTime = millis() - downTime;
} else {
downTime = millis();
}
return (state);
}
return false;
}