return 0;
pulseTime = ( time.time() - t0)*0.000001
r eturn pulseTime
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 (cm)
r eturn distance
def setup():
p rint ('Program is starting...')
GPIO. setmode(GPIO.BOARD) #numbers GPIOs by physical location
GPIO. setup(trigPin, GPIO. OUT) # set trigPin to output mode
GPIO. setup(echoPin, GPIO. IN) # set echoPin to input mode
def loop():
w hile(True):
distance = getSonar()
print ("The distance is : %.2f cm"%(distance))
time.sleep(1)
if __name__ == '__main__': #program start from here
setup()
try:
loop()
e xcept KeyboardInterrupt: #when 'Ctrl+C' is pressed, the program will exit
GPIO.cleanup() #release resource
If the module does not return high level, we can not wait forever. So we need to calculate the lasting time
over maximum distance, that is, timeOut( μ s) . timeOut= 2*MAX_DISTANCE/100/340*1000000. The
constant part behind is approximately equal to 58.8.