树莓小车-超声波模块HC-SR04简介以及编程

Product features:

Ultrasonic ranging module HC - SR04 provides 2cm -400cm non-contact measurement function, the ranging accuracy can reach to 3mm. The modules includes ultrasonic transmitters, receiver and control circuit. The basic principle of work:

(1) Using IO trigger for at least 10us high level signal,

(2) The Module automatically sends eight 40 kHz and detect whether there is a pulse signal back.

(3) IF the signal back, through high level , time of high output IO duration is the time from sending ultrasonic to returning. Test distance = (high level time×velocity of sound (340M/S) / 2,


164619_Yrg3_1584562.png

Wire connecting direct as following:

Vcc 5V Supply

Trigger Pulse Input

Echo Pulse Output

0V Ground


Electric Parameter:

164939_NcJY_1584562.png

Trig 和 Echo 为 TTL电平,所以可以直接接在TTL电平的GPIO口上。

Timing diagram

The Timing diagram is shown below.

You only need to supply a short 10uS pulse to the trigger input to start the ranging,

and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo.

The Echo is a distance object that is pulse width and the range in proportion .

You can calculate the range through the time interval between sending trigger signal and receiving echo signal. Formula: uS / 58 = centimeters or uS / 148 =inch; or: the range = high level time * velocity (340M/S) / 2;

we suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal.

 170540_qMIH_1584562.png

5、 操作

初始化时将trigecho端口都置低,

首先向给 trig    发送至少10 us的高电平脉冲(模块自动向外发送840K的方波),

然后等待,捕捉 echo 端输出上升沿,捕捉到上升沿的同时,打开定时器开始计时,再次等待捕捉echo的下降沿,当捕捉到下降沿,读出计时器的时间,

因为echo高电平的时间等于超声波在空气中运行的时间,按照  测试距离=(高电平时间*声速(340M/S))/2   就可以算出超声波到障碍物的距离。

 

树莓派上连接这个模块,写程序 ultrasonic_hc-sr04.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO  
import time  

SONIC_ECHO = 36
SONIC_TRIG = 37  
        
def checkdist():
    #发出触发信号
    GPIO.output(SONIC_TRIG,GPIO.HIGH)
    #保持10us以上(我选择20us)
    time.sleep(0.000020)
    GPIO.output(SONIC_TRIG,GPIO.LOW)
    while not GPIO.input(SONIC_ECHO):
        pass
    #发现高电平时开时计时
    t1 = time.time()
    while GPIO.input(SONIC_ECHO):
        pass
    #高电平结束停止计时
    t2 = time.time()
    #返回距离,单位为米
    return (t2-t1)*340/2

GPIO.setmode(GPIO.BOARD)
GPIO.setup(SONIC_TRIG,GPIO.OUT,initial=GPIO.LOW) 
GPIO.setup(SONIC_ECHO,GPIO.IN) 

time.sleep(2)
while True:
    L_distance = checkdist()
    if L_distance > 10:
       pass
    else:
       print 'Distance: %0.2f m' %L_distance
    time.sleep(0.5)      

GPIO.cleanup()



转载于:https://my.oschina.net/RagingTyphoon/blog/494439

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值