timing an event

This should be easy but for some reason I cannot get around it. I'm old and realize my brain cells are rapidly dying off.

I have an SR04 ultrasonic detector working fine. When something is detected, it lights an LED. I want to time the interval between the LED going on and then off. I have searched and searched and read many timing sketches using millis() but cannot get the answer I want. If I hold a stick in front of the sensor for 5 seconds, I expect readout of 5 seconds (5000 millis). I get 101 millis or thereabouts no matter how long my stick is in front of the sensor.

There are only two statements that I have to put "somewhere" in order to make this work, the two that use "millis()". Like I said, it should be easy. Can someone point me on the right path? THanks for any help.

void loop() {
  //Activate sonar
  duration = sonar.ping_median(iterations); //5 iterations to reduce noise
  distance = (duration / 2) * 0.0343;// Use 343 metres per second as speed of sound

  if (distance < 40) //less than 40 means something is blocking the view
  { digitalWrite(ledPin, HIGH);
  }
  else
  { digitalWrite(ledPin, LOW);
  }
  val = digitalRead(ledPin);
  if (val == HIGH) {
    currentState = 1;
    start=millis();
  }
  else {
    currentState = 0;
  }
  if (currentState != previousState) {
     if (currentState == 1){ 
    counter = counter + 1;}
    elapsed=millis()-start;
      Serial.print("Activated ");
      Serial.print(counter);
      Serial.println(" times");
      Serial.print(" Elapsed ");
      Serial.println(elapsed);}
 
 previousState = currentState;
}

Don’t post snippet... for example we don’t know the type of your variables

here's program...uh sketch.

CounterFE3.ino (1.89 KB)

I’m on my phone - Can’t read post in line

There is no reason to read the state of the output pin. You assigned it a value. WHEN you did that is what matters.

The state change detection example is what you need to look at, to heed Delta_G's comment.

I moved both statements around ad nauseum without getting proper results.
I can't put the "start" any closer than in the test for distance, eg

if (distance < 40)
{ digitalWrite(ledPin, HIGH);
start=millis();}

so where can I put it to start as soon as I get a blip?