Electronic – Why can’t the HC-SR04 sensor detect objects that are very close to it

hc-sr04mobile robotroboticsultrasound

I am following this worksheet and I am struggling to understand the following piece of code:

# Stop when the Echo pin is no longer high - the end time
        while GPIO.input(pinEcho) == 1:
            StopTime = time.time()
            # If the sensor is too close to an object, the Pi cannot
            # see the echo quickly enough, so we have to detect that
            # problem and say what has happened.
            if StopTime - StartTime >= 0.04:
                print("Hold on there!  You're too close for me to see.")
                StopTime = StartTime
                break

I have implemented the worksheet's instructions and the code and when the sensor is very close to the object, I see the ...You're too close... message on the console. However, the condition StopTime - StartTime >= 0.04 and the associated statement ...You're too close.... make no sense to me.

If StopTime - StartTime is greater than a specific value, does it not mean it is taking longer than we want for the pulse to reach the Echo pin? Does that not in turn mean that the object is too far (rather than too close) for the sensor to detect it?

As far as I know, the echo pin is initially zero. When it gets the return pulse, the echo pin changes from 0 to 1. We record this instant as the start time. We then wait for the echo pin to change back to 0 from 1. This instant is recorded as the end time. This StopTime - StartTime check is happening while the echo pin is 1 and we are waiting for this pin to become 0. So if the echo pin is 1, the echo pin has already sensed the return pulse, hasn't it?

Best Answer

If the time is longer than 0.04 then it means that the Pi "missed" the return because it wasn't fast enough to see the rapid return. It's basically a sanity check because after 0.04s it would mean the return pulse was missed or the object is physically out of range of the sensor.

Related Topic