Counting with photoresistor (searched)

Hello all,
Making a very simple circuit to count when objects move over it. The problem I'm having is the incrementing variable is counting too many times per object.

I want to ++ everytime there is 1 object moving over the sensor but it seems that the code is ++ the all the while the sensor is blocked.

The threshold for the light value is 15, so anything less than that would be considered an object.

// car counting program
int highPin = 52;
int lightVal;
int sNBT = 15;
long NBT = 0;
long previousMillis = 0;
long interval = 3000;
long bin = 1;
int x = 1;



void setup(){
  pinMode(highPin, OUTPUT);
  pinMode(sNBT, INPUT);
  Serial.begin(9600);
}

void loop(){
  digitalWrite(highPin, HIGH);
  //read the sensors light value
  lightVal = analogRead(sNBT);
  //sense if car is on sensor
  //Serial.println(lightVal);

if(lightVal <15){
  NBT++;
  lightVal = analogRead(sNBT);
  while(lightVal < 15){
    lightVal = analogRead(sNBT);
  }
}
  
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval){
    bin++;
    Serial.println(bin);
    Serial.print("NBT Cars :");
    Serial.println(NBT);
    previousMillis = currentMillis;
    NBT = 0;
    Serial.print("Current Light Level:");
    Serial.println (lightVal);
  }
}

Thanks for any advice!

It looks like you're reading light levels all of the time and whenever it is lower than 15 you increase the NBT variable. Try moving the "if(lightval < 15)" block of code inside the "if(currentMillis - previousMillis > interval)" block.

I see that it's supposed to stay in that while loop until the level rises above 15, and presumably that's expected to happen when the object has cleared the sensor. Have you tried logging the values you actually get in practice? It may be that the readings don't consistently stay below 15 while the object is there.

Is there any other filtering you could apply to prevent the multiple readings? For example, is there a minimum delay between genuine triggers of the sensor? If so you could use that to 'debounce' the sensor readings.