python 樹莓派 超聲波測距離
阿新 • • 發佈:2018-11-12
#! /usr/bin/python # -*- coding:utf-8 -*- import RPi.GPIO as GPIO import time import datetime def checkdist(): GPIO.output(2, GPIO.HIGH) time.sleep(0.000015) GPIO.output(2, GPIO.LOW) while not GPIO.input(3): pass t1 = time.time() print "t1:", t1 while GPIO.input(3): pass t2 = time.time() print "t2:", t2 t3 = t2 - t1 print t3 return t3*340/2 GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(3,GPIO.IN) time.sleep(2) try: while True: print 'Distance: %0.2f m \n' %checkdist() time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()