Measure the time of object in a specific distance

I have an ultrasonic sensor. I have difficulties to measuser the time frame in which the object was in range. I want to measure the time frame of a object that is in range from 8-20 cm. If that object was in range for example for 0.5s then increase counter. If the the object was in range for more than 0.5s perform task.

Timestamps, using millis()?

I have tried but failed.

if(distance >= 8 && distance<=20)
start = millis();
end = millis();
Ant then here calculate the difference. But the problem is that the else will always execute

Have a look at the state change detection example in the IDE

Like AWOL said you need to detect a change in state. In this case you would consider the following changes:

  1. Going from "out of range" to "in range"
  2. Going from "in range" to "out of range"

For example you would record the millis() value when the object goes from "out of range" to "in range". While "in range" check millis() to determine if 0.5s have passed. If so then perform the appropriate action. When the object goes from "in range" to "out of range" then stop checking millis() for "in range" duration.