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,
Wire connecting direct as following:
Vcc 5V Supply
Trigger Pulse Input
Echo Pulse Output
0V Ground
Electric Parameter:
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.
5、 操作:
初始化时将trig和echo端口都置低,
首先向给 trig 发送至少10 us的高电平脉冲(模块自动向外发送8个40K的方波),
然后等待,捕捉 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()