接线
超声波模块HC-SR05相比于HC-SR04,多了一个OUT引脚,不太懂,没用到
所以,跟HC-SR04一样看待即可
VCC:接5V
GND:接地
Trig和Echo接任意两个GPIO口
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import RPi.GPIO as GPIO import time
EchoPin = 16 TrigPin = 12
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def init(): GPIO.setup(EchoPin,GPIO.IN) GPIO.setup(TrigPin,GPIO.OUT)
def getDistance(): GPIO.output(TrigPin,GPIO.HIGH) time.sleep(0.000015) GPIO.output(TrigPin,GPIO.LOW) while not GPIO.input(EchoPin): pass t1 = time.time() while GPIO.input(EchoPin): pass t2 = time.time() time.sleep(0.01) return ((t2 - t1)* 340 / 2) * 100
try: init() while True: print("distance is %d cm" % getDistance()) time.sleep(0.3) except KeyboardInterrupt: pass GPIO.cleanup()
|
发现这个传感器不是很灵敏,角度不能偏,遮挡物面需要够大且尽可能光滑,不太满意