I have a better solution - the previous solutions don't take into consideration that a "long" button press may need to be the same duration on different processors, or in coordination with different blocking calls that may alter how long it takes to run the loop.
I have a solution that uses a timer to count how long the button press has been in place, and debounces the button of course.
// long button press variables
unsigned long longButtonTimeout_ms = 2000; // two second button timeout
bool previousButtonState;
bool listeningForLongButtonPress;
// debounce variables
int buttonState;
int lastButtonState = LOW;
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
byte buttonPin = 9;
void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
currentTime_ms = milils();
bool buttonPressed = false;
int reading = digitalRead(buttonPin);
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
buttonPressed = true;
} else {
buttonPressed = false;
}
}
// check for a long button press
if (buttonPressed) {
// if we are already within a button press
if (listeningForLongButtonPress) {
// and the button has been pressed for a long enough time
if (currentTime_ms > (lastUpdate_ms + longButtonTimeout_ms)) {
// we have a long button press
longButtonPress();
// stop listening for a button press
listeningForLongButtonPress = false;
Serial.println("Button Pressed for a long time!");
}
} else {
// otherwise, this is a new button press... begin listening for a long buttonpress
listeningForLongButtonPress = true;
Serial.println("Button has been pressed");
}
} else {
// button released? Stop listening for a long button press
listeningForLongButtonPress = false;
Serial.println("Button Released");
}
}