Wait for 5 seconds to turn off LED, unless there is low input

I’m working on a project with an LDR (light dependent resistor), where I want an LED to turn on when the input is low (<= 800) and to turn off when the input is high (> 800).

The challenging part is to make the LED stay on after 5 seconds of high input, and then turn off. If in those 5 seconds there is low input then the timer will restart again, waiting for 5 seconds of undisturbed high input. If the input is low then the LED should turn off immediately.

I’ve tried using the delay() function but this doesn’t work well, because in those 5 seconds no inputs are recorded, whereas I need a continuous stream of inputs to determine if the light will stay on. Using the delay() function results in a blink in the LED, possibly due to the last high input recorded by the serial.

const int LDR_Pin = A0; // Photoresistor at analog pin A0
const int led_Pin=9;       // Led pin at pin 9

//Variables
int value;		// input value from LDR

void setup(){
 Serial.begin(9600);
 pinMode(led_Pin, OUTPUT);  // Set led_Pin - 9 pin as an output
 pinMode(LDR_Pin, INPUT);// Set LDR_Pin - A0 pin as an input
}

void loop(){
  
  value = analogRead(LDR_Pin);
  Serial.println(value);
  Serial.println("");
  //You can change value threshold
  if (value > 800){
    delay(5000);
    if (value > 800){
      digitalWrite(led_Pin, LOW);  //Turn led off
    }
      
  }
  
  else{
    digitalWrite(led_Pin, HIGH); //Turn led on
  }

  delay(100); //Small delay
  
}

Is there an alternative way this can be achieved without the LED blinking?

Thanks.

I'm not sure that I understand your description of the requirement.

Try this pseudo code if you want to ensure that something remains HIGH for 5 secs

if (lightLevel == LOW) {
    lastLowLightMillis = millis(); // reset the timer
}

if (millis() - lastLowLightMillis >= 5000) {
   // light has been HIGH for 5 secs
  // do stuff
}

...R