Chapter 24 Ultrasonic Ranging
Subfunction getSonar () function is used to start the ultrasonic module for a measurement, and return the
measured distance with unit cm. In this function, first let trigPin send 10us high level to start the ultrasonic
module. Then use pulseIn () to read ultrasonic module and return the duration of high level. Finally calculate
the measured distance according to the time.
def getSonar(): #get the measurement results of ultrasonic module, with unit: cm
GPIO. output(trigPin,GPIO.HIGH) #make trigPin send 10us high level
time. sleep(0.00001) #10us
GPIO. output(trigPin,GPIO.LOW)
pingTime = pulseIn( echoPin,GPIO.HIGH,timeOut) #read plus time of echoPin
distance = pingTime * 340.0 / 2.0 / 10000.0 # the sound speed is 340m/s, and
calculate distance
r eturn distance
Finally, in the while loop of main function, get the measurement distance and print it out constantly.
w hile(True):
distance = getSonar()
print ("The distance is : %.2f cm"%(distance))
time.sleep(1)
About function def pulseIn(pin,level,timeOut)ļ¼
def pulseIn(pin,level,timeOut):
Return the length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned
long).