树莓派3B+超声波传感器 HY-SRF05

小白新手记录一下,多包涵
1、接线
由于没有面包板,比较粗糙
树莓派3B+超声波传感器 HY-SRF05_第1张图片
2–VCC
16–TRIG
18–一端连1K电阻、ECHO,一端连2K电阻、GND
6–GND

2、代码
打开命令行,输入nano distance.py
代码如下:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
print "Measuing Distance"
print "Press ctrl +c to stop me"
GPIO.setup(23,GPIO.OUT)
GPIO.setup(24,GPIO.IN)
time.sleep(0.02)
GPIO.output(23,False)
print "Setting Trigger pin to zero by default"
time.sleep(1)
while True:
        GPIO.output(23,True)
        time.sleep(0.00001)
        GPIO.output(23,False)
        while GPIO.input(24)==0:
                start_time=time.time()
        while GPIO.input(24)==1:
                end_time=time.time()
        time=end_time-start_time
        distance=17150*time
        print "Measured Distance is:", distance ,"cms."


按ctrl+x 离开,Y保存
在命令行输入:python distance.py

测试成功,如下
pi@raspberrypi:~ $ python distance.py
Measuing Distance
Press ctrl +c to stop me
Setting Trigger pin to zero by default
Measured Distance is: 18.2118654251 cms.
Traceback (most recent call last):
File “distance.py”, line 15, in
time.sleep(0.00001)
AttributeError: ‘float’ object has no attribute ‘sleep’
有成功显示距离,同时也有报错,AttributeError: ‘float’ object has no attribute ‘sleep’.

你可能感兴趣的:(树莓派,Python)