Push button 5s turn on led?

How to write a code to turn on the LED if the button is pressed for more than 5s? If pressed 4s no led on!
Simple code is:

const int BUTTON = 2;
const int LED = 3;
int BUTTONstate = 0;

void setup()
{
  pinMode(BUTTON, INPUT);
  pinMode(LED, OUTPUT);
}

void loop()
{
  BUTTONstate = digitalRead(BUTTON);
  if (BUTTONstate == HIGH)
  {
    digitalWrite(LED, HIGH);
  } 
  else{
    digitalWrite(LED, LOW);
  }
}

Save the value of millis() as the start time when the button becomes pressed and set a boolean to true to flag that timing is in progress. If the button becomes released set the boolean to false. Each time through loop(), if the boolean is true check whether 5 seconds has passed since it was pressed by subtracting the start time from the current value of millis(). If so take action as desired

Set a variable to the time whenever the button becomes pressed (StateChangeDetection example
is relevant for this), then the test is simply:

if (button_is_pressed_currently && millis() - last_become_pressed > 5000)
  turn_led_on() ;

details left for you to fill in.

void loop()
{
  static unsigned long startTime = 0;
  
  BUTTONstate = digitalRead(BUTTON);
  if (BUTTONstate == HIGH)
  {
    if (millis() - startTime >= 5000)
      digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
    startTime = millis();
  }
}

johnwasser:

void loop()

{
 static unsigned long startTime = 0;
 
 BUTTONstate = digitalRead(BUTTON);
 if (BUTTONstate == HIGH)
 {
   if (millis() - startTime >= 5000)
     digitalWrite(LED, HIGH);
 }
 else
 {
   digitalWrite(LED, LOW);
   startTime = millis();
 }
}

This is done. TNX!!!

use a timer, so when the button is pressed, the timer starts and after 5s go to timer interrupt and check if the button is still HIGH and then perform what you want