checking button hold for a period of time

Hi guys i have this another timing sketch below … another different encounter in programming timings in arduino for me…hehe…

this is what the sketch does:

*at button press/hold

  • PROCESS1 - the ledPin will be ON for 500UL and then OFF

*when the button is released from pressing or holding

-PROCESS2 - the ledPin will be ON again for 500UL and then OFF

but what i want to happen is to check if the button is pressed or held for exactly 4s BEFORE process1 occurs , that is;

if button is held for 4s

  • do process 1

  • proceed to process2 if button is released

  • loop from the start (check again if button is held for 4s)

i’m having a hard time thinking of a way to check the presence of button hold for 4s, mind if u may help me with this one

thanks !

const int ledPin =  13;      // the number of the LED pin
unsigned long startTime;        // will store last time LED was updated
const int DisplayButton = 2; 
int lastButtonState = 0; 
int ledState;
unsigned long interval = 500UL;           // interval at which to blink

void setup() 
{
  pinMode(ledPin, OUTPUT);  
  pinMode(DisplayButton, INPUT);  
}

void loop()
{ 
  int buttonState = digitalRead(DisplayButton);
  if (buttonState != lastButtonState) // on any state change...
  {
    startTime = millis();// .... reset the timer
  }
  lastButtonState = buttonState;
  
  if (millis() - startTime <= interval)
  {
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  } 
}

If the only thing required of the MCU when the button is pressed … is to read the button/switch state ? Do any other actions have to occur while this is ongoing ? Are you aware that switches “bounce” ? If there’s nothing else going on then why not something like the following pseudo-code ?

read button state
if (button == pressed){
  Ptime = millis()
  wait debounce time
  read button state
  while (button == pressed){
    if (millis()-Ptime > 4 secs){
      if (P1flag == not done){
        do process 1
        P1flag = done
      }
    }
  }
  button is now released, do process 2
}