This one can be found all over the internet, but I wanted to have it here, just for the reference. And if it comes handy to someone – double win.
Anyway – the sensor is ultrasonic HC-SR04. And it works like that:
- start the timer
- send the sound in direction you want to measure the distance
- measure the time when the sound comes back (an echo)
- calculate the distance
The code is
def check_distance():
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 171500
distance = round(distance, 2)
return distance
This one is a function in Python returning the distance. You need to define TRIG for the transmitter and ECHO for the receiver.
Why are we multiplying with 171500?
Since the speed of sound is 343 m/s and the sound needs to travel double the distance from the sensor to the obstacle we need to half the calculated distance (from the formula v=d/t). We get 171.5 m/s, but since we want the result in millimetres the result has to be multiplied by 1000 (you know – 1m = 100cm = 1000mm) .