0
点赞
收藏
分享

微信扫一扫

树莓派连接超声波传感器

追风骚年 2022-10-18 阅读 209


  • 介绍

你知道蝙蝠是个“瞎子”吗?那它怎么看东西呢?好吧,它是通过超声波来探路的。下面我要介绍的就是超声波模块,有了它你的树莓派就再也不用当心会“撞墙”了!

该模块会发出超声波,在声波碰到障碍物时会立刻返回被该模块接收到。通过超声波模块来测距的原理就是,计算声波返回的时间,然后与声波的传递速度相乘,就能得到距离了。

我们知道,温度为15度时,声音的传递速度为340米/秒。

另外,大家可以思考一下,为什么非要用超声波来测距呢,别的声波不可以吗?因为,超声波指向性强,能量消耗缓慢,在介质中传播的距离较远。

但是,本文介绍的超声波模块只能探测到4、5米远的距离。

  • 玉照

[caption id="attachment_1593" align="alignnone" width="354"]​​​​ 超声波模块[/caption]

 

  • 实验材料

公对母面包线(4根),超声波模块(1个)

  • 接口介绍

该模块有四个接口,分别如下:(需要使用两个gpio)

VCC 5V

Trig 控制发射超声波

Echo 接收超声波

GND 负极

  • Python实现

[codesyntax lang="python"]


#!/usr/bin/python
# from http://surenpi.com

import RPi.GPIO as GPIO
import datetime
import time

def gpio_init():
GPIO.setmode(GPIO.BCM)
pass

def ultrasound_init(echo, trig):
gpio_init()

GPIO.setup(echo, GPIO.IN)
GPIO.setup(trig, GPIO.OUT)
pass

def get_distance(echo, trig):
ultrasound_init(echo, trig)

send_time = 0
rece_time = 0

GPIO.output(trig, GPIO.LOW)
time.sleep(0.002)
GPIO.output(trig, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(trig, GPIO.LOW)

while GPIO.input(echo) == 0:
send_time = time.time()
pass

while GPIO.input(echo) == 1:
rece_time = time.time()
pass

distance = (rece_time - send_time) * 340 / 2 * 100

return distance

pass

#车位左侧距离
def get_left_distance():
trig = 23
echo = 24
return get_distance(echo, trig)

#车位右侧距离
def get_right_distance():
trig = 17
echo = 27
return get_distance(echo, trig)

#车位背后距离
def get_back_distance():
trig = 5
echo = 6
return get_distance(echo, trig)

#程序入口
if __name__ == '__main__':
try:
left_dis = get_left_distance()
right_dis = get_right_distance()
back_dis = get_back_distance()

print '车位左侧距离:', left_dis
print '车位右侧距离:', right_dis
print '车位背后距离:', back_dis

time.sleep(5)
except KeyboardInterrupt:
GPIO.cleanup()


[/codesyntax]

  • 参考

​​淘宝——观月堂 http://item.taobao.com/item.htm?spm=a1z10.5-c.w4002-10583748383.22.J3WhPx&id=45175508621​​

​​这里是用wiringPi实现的,http://www.tuicool.com/articles/zaeEFr​​

​​不知道你的树莓派的GPIO接口分布?请看这里。​​​

举报

相关推荐

0 条评论