pyright © 1999-2020, CSDN.NET, All Rights Reserved
打开APP
xbw12138
关注
树莓派蜂鸣器+超声波测距模块 原创
2016-07-15 21:10:11
3点赞
xbw12138
码龄8年
关注
/2016/07/15
by xbw/
///环境 树莓派 2B+
</pre><p></p><pre>
#! /usr/bin/python
# -*- coding:utf-8 -*-
import
网页链接 as GPIO
import time
def checkdist():
#发出触发信号
GPIO.output(2,GPIO.HIGH)
#保持10us以上(我选择15us)
time.sleep(0.000015)
GPIO.output(2,GPIO.LOW)
while not GPIO.input(3):
pass
#发现高电平时开时计时
t1 = time.time()
while GPIO.input(3):
pass
#高电平结束停止计时
t2 = time.time()
#返回距离,单位为米
return (t2-t1)*340/2
def beep():
print '有人靠近!!!'
GPIO.output(9,GPIO.LOW)
time.sleep(0.5)
GPIO.output(9,GPIO.HIGH)
time.sleep(0.5)
GPIO.setmode(GPIO.BCM)
#第3号针,GPIO2
GPIO.setup(2,GPIO.OUT,initial=GPIO.LOW)
#第5号针,GPIO3
GPIO.setup(3,GPIO.IN)
#第17号针,GPIO9
GPIO.setup(9,GPIO.OUT)
time.sleep(2)
try:
while True:
print '距离: %0.2f m' %checkdist()
if int(checkdist())<=1:
beep()
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup()