Incorrect Distance Readings from HC-SR04 Ultrasonic Sensor on BeagleBone Black

Hey guys based on my question on developing an obstacle detection system using a BeagleBone Black running Embedded Linux using HC-SR04 ultrasonic sensor to measure distances and displays the measurements on a 16x2 LCD screen. i was finally able to solve the issue with the lcd screen it turns out it was faulty and i had to change it and is now working smootly, but am having another issue where am getting incorrect distance reading, i know this because from my observations the distance readings are inconsistent and unrealistic, with extreme values and occasional zero readings, please how can i resolve this

here's my code
def measure_distance_simple():
    GPIO.output(TRIG_PIN, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(TRIG_PIN, GPIO.LOW)

    while GPIO.input(ECHO_PIN) == GPIO.LOW:
        start_time = time.time()

    while GPIO.input(ECHO_PIN) == GPIO.HIGH:
        end_time = time.time()

    duration = end_time - start_time
    distance = (duration * 34300) / 2
    return distance

try:
    while True:
        distance = measure_distance_simple()
        print(f"Distance: {distance:.2f} cm")
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()
file0.jpg
Solution
It's likely because of the noise or timing inaccuracies. Try adding a timeout for the echo response
Try if that would work!
Was this page helpful?