Tutorial

Table Of Contents
71
GPIO.setmode(GPIO.BCM)
GPIO.setup(Tr, GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(Ec, GPIO.IN)
def checkdist():
GPIO.output(Tr, GPIO.HIGH) # Set the input end of the module to high level and emit an initial sound wave
time.sleep(0.000015)
GPIO.output(Tr, GPIO.LOW)
while not GPIO.input(Ec): # When the module no longer receives the initial sound wave
pass
t1 = time.time() # Note the time when the initial sound wave is emitted
while GPIO.input(Ec): # When the module receives the return sound wave
pass
t2 = time.time() # Note the time when the return sound wave is captured
return round((t2-t1)*340/2,2) # Calculate distance
'''
Output ultrasonic ranging results once per second and output ten times
'''
for i in range(10):
print(checkdist())
time.sleep(1)
As regard the ultrasonic module, this is a commonly used module in many preliminary projects in order
to reduce the complexity of the program, although there is a blocking part in this code, we did not use
multi-threading to solve it If your project has a high demand for product performance, you can refer to the
content of 14 to reconstruct multi-threaded ultrasound.
When your project needs to use the ultrasonic function, you don't need to rewrite the above code, just
copy ultra.py in the robot program server folder to the same folder as your own project Use the following code
to obtain ultrasonic ranging information:
import ultra
distance = ultra.checkdist()