// https://wokwi.com/projects/431121662330250241
// https://forum.arduino.cc/t/help-with-button-triggering-at-the-wrong-time/1382008
const int buttonPin = 7;
const int holdLimit = 1500; // 1.5 seconds for long press
unsigned long currentMillis;
unsigned long buttonPressMillis;
//... it was not pressed - you could read it in setup
bool lastButtonState = false;
//bool currentButtonState;
bool buttonPressed = false;
const unsigned long debounceDelay = 50; // milliseconds for debounce
bool powerOn;
void setup() {
Serial.begin(115200);
Serial.println("\nPRESS ME\n");
pinMode(buttonPin, INPUT_PULLUP);
powerOn = true;
}
# define PRESSED LOW
void loop() {
currentMillis = millis();
static unsigned long lastButtonTime;
if (currentMillis - lastButtonTime > debounceDelay) {
bool rawReading = digitalRead(buttonPin) == PRESSED; // true = pressed
if (rawReading != lastButtonState) {
if (rawReading) { // button went down
buttonPressMillis = currentMillis; // Record the time of this press
msg("button went down");
buttonPressed = true;
}
else { // button came up
msg("button came up");
if (powerOn && buttonPressed) { // unhandled button down
cycleDevices();
buttonPressed = false; // has been handled
msg("CycleDevice - Short Press on Release");
}
}
lastButtonTime = currentMillis;
lastButtonState = rawReading;
}
}
// always check
if (buttonPressed && currentMillis - buttonPressMillis >= holdLimit) {
msg("Power Toggle - When it's a long press");
powerToggle();
buttonPressed = false; // has been handled
}
}
void powerToggle()
{
Serial.println(" power toggle");
powerOn = !powerOn;
}
void cycleDevices()
{
Serial.println(" cycle devices");
}
void msg(char *theMessage)
{
return; // we don't need no stinkin' messages
static int counter;
Serial.print(counter);
Serial.print(" ");
Serial.println(theMessage);
counter++;
}