3.8. Sonar Distance Sensor#
The SR04 Ultrasonic distance sensor allows us to measure distances to objects. It has the following properties:
Minimum rangę: 20mm
Maximum range: 4000mm
Accuracy: 3mm
Angle (horizontal field of view): 15 degrees
Note
We’ll learn more about how ultrasonic sensors work later in Touch and Proximity.
3.8.1. Reading the Distance#
Reading the distance requires knowledge of how the sensor works. For the moment we’ll ignore that and just use the code below to read the distances:
import utime
def ultrasound_measure():
pin1.write_digital(1)
utime.sleep_us(10)
pin1.write_digital(0)
timeout = utime.ticks_us()
while True:
pulseBegin = utime.ticks_us()
if 1 == pin2.read_digital():
break
if (pulseBegin - timeout) > 5000:
return -1
while True:
pulseEnd = utime.ticks_us()
if 0 == pin2.read_digital():
break
if (pulseEnd - pulseBegin) > 5000:
return -2
x = pulseEnd - pulseBegin
d = x / 58
return int(d)
Example#
To read the distance in our main loop we might do:
while True:
dist = ultrasound_measure()
if dist >= 0:
print(dist)
sleep(100)
Note
The ultrasonic sensor reads will fail occasionally, therefore we check that we get a positive distance before accepting the reading. We also keep reading until we get a good measurement.