When sensor is active for an amount of time trigger LED

Hi all,

I'm a bit stuck at programming.
And there is quite a lot to find about it on the forum, however, so far it didn't help.

I feel like I'm close, but it does not work yet as it should.

I have a sensor which detects vacancy in a room (ToF sensor).
However, I don't want the sensor to turn the light directly on, I rather have the sensor checks the room for 5 seconds and then turn the light on.

So, similar like a pushbutton, if you press it for 5 seconds it will turn a LED on.
But with the sensor it works a bit different.

Here is my code

/* THEBULB. THE SO-LOO-TION SENSOR */

#include <Wire.h>
#include <VL53L1X.h>

VL53L1X sensor;

unsigned long interval = 5000;
unsigned long sensorActive;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000); // use 400 kHz I2C

  pinMode(LED_BUILTIN,OUTPUT);
  pinMode(13, INPUT_PULLUP);
  pinMode(12, OUTPUT); 
 
  sensor.setTimeout(500);
  if (!sensor.init())
  {
    Serial.println("Let op: de sensor wordt momenteel niet gedetecteerd. Controleer aansluitingen. ");
    while (1);
  }
  
  sensor.setDistanceMode(VL53L1X::Long);
  sensor.setMeasurementTimingBudget(50000);
  sensor.startContinuous(100);

}

void loop()
{  
  Serial.print(sensor.read());

  if (sensor.readRangeContinuousMillimeters () <=1000 && millis() - sensorActive < interval) {  //schakelafstand wordt hier ingevoerd. Onder deze waarde is de schakeling actief. 
    digitalWrite (LED_BUILTIN, HIGH);
    digitalWrite (13, HIGH);
    digitalWrite (12, HIGH); 
    }else {                                              //hoger dan de schakelafstand.  
    sensorActive = millis();    
    digitalWrite (LED_BUILTIN, LOW);
    digitalWrite (13, LOW);
    digitalWrite(12, LOW);  
    }

  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT");}
  Serial.println();
}

My favorite method:

Whenever sensor is INACTIVE, store millis() in an unsigned long variable (let's say, 'timer').

When sensor is ACTIVE and millis() - 'timer' is >= your desired interval: Do the thing.

One thing that is almost certainly wrong is that you are setting the built-in LED pin and pin 13 to OUTPUT and INPUT_PULLUP, respectively. On most Arduinos the built-in LED pin is 13. I think you should remove all the lines that use pin 13 explicitly.

It looks like your logic is incorrect, too. On this line:

if (sensor.readRangeContinuousMillimeters () <=1000 && millis() - sensorActive < interval) {

shouldn't the test be for millis() less sensorActive being greater than interval? Just changing that would also not work because it would continually reset sensorActive. You need to separate the tests for when the distance becomes less than 1000 and whether it has been that way for 5 seconds.