Timing a button press

So I did some research and got an example but it hasn't really helped.

I want to press and hold a button for 2 seconds, and after the 2 seconds, pulse an output.

Once the pulse is complete, reset the timer.

Right now, it works, but not the timer..

  int buttonState2 = digitalRead(BTN2);
  static long Warptime;


 if (buttonState2 == LOW && (i == 0)) {
    
    Warptime = millis(); 
    
    if (Warptime >= 2000) {
      
  digitalWrite(WARP, HIGH);
  delay(500);
  digitalWrite(WARP, LOW); 
  delay(500);
  
  Warptime = 0;
  }

Any suggestions??

Any help would be greatly appreciated.

Thank you,

  Warptime = millis();

  if (Warptime >= 2000) {

millis() is the number of milliseconds since the program started so will get to 2000 in 2 seconds and remain greater than 2000 for the next 49 days so your program will not work as it is.

What you need to do is to save the time of the button press from millis() then each time through loop() check whether the current millis() value is 2000 greater than it was when the button was pressed.

Have you seen the BlinkWithoutDelay example in the IDE ?

You need code that is something like this - I always think it seems counter-intuitive

if (button is not pressed) {
   lastMillis = millis();   // restart the time value
}
if (millis() - lastMillis >= interval) {
   // time has elapsed without the button being released
}

See also the use of millis() for timing in several things at a time

...R

Excellent! Thank you! :slight_smile:

This works wonderfully:

2000 milliseconds was too long, reduced it to 750 ms.

if (buttonState2 == HIGH) {
    
    Warptime = millis(); 
    digitalWrite(WARP, LOW); 
   }

    if ((millis() - Warptime >= 750) && (buttonState2 == LOW))  {
      
  digitalWrite(WARP, HIGH);  
}