Quantcast
Viewing all articles
Browse latest Browse all 5288

Troubleshooting • Re: Problem using HC-SR04 sensor for distance measurement

You aren't measureing what you think. You update the pulse_start every lookp while waiting for the echo, so it will be the start of the echo, not the time of the ouput pulse. And pulse_end is read immediately after the loop so it will be just about the same as pulse_start. So you get very small times / distances.
You want the measure the time between the output pulse and the echo.
You could just remove one line:

There are libraries for this. e.g. import adafruit_hcsr04

Program:

Code:

... # Measure the pulse duration on the echo pin pulse_start = time.time() while GPIO.input(echo_pin) == 0:  pulse_start = time.time()    #,<- remove this line pulse_end = time.time() pulse_duration = pulse_end - pulse_start # Calculate the distance in centimeters distance = pulse_duration * speed_of_sound / 2 return distance[/quote]Think about what this code is measuring.pulse start updates every loop while waiting for the echo.As soon as the echo is detected you read pulse_endSo you measure how long it takes to read time.time() twice in a row.You do set  Pulse_start immediately after sending the output. Don;t update it after that. Just wait for the echo.

Statistics: Posted by PiGraham — Tue Feb 20, 2024 9:42 am



Viewing all articles
Browse latest Browse all 5288

Trending Articles