HC-SR04超声波模块测距原理:
给模块1个最少10us的高电平,模块接受到高电平后开始发射8个40KHz的声波,echo脚会由0变为1,MCU开始计时,当超声波模块接收到返回的声波时,echo由1变为0,MCU停止计时,这时间差就是测距总时间,在乘声音的传播速度340米/秒,除2就是距离。
import time
from machine import Pin
Trig, Echo = Pin(4,Pin.OUT),Pin(5,Pin.IN)
led = Pin(2,Pin.OUT)
Trig.value(0)
Echo.value(0)
def checkdist():
Trig.value(1)
time.sleep(0.00001)
Trig.value(0)
while(Echo.value()==0):
pass
t1 = time.ticks_us()
while(Echo.value()==1):
pass
t2 = time.ticks_us()
t3 = time.ticks_diff(t2,t1)/8000
if(t3*340/2<5):
led.value(1)
else:
led.value(0)
return t3*340/2
try:
while 1:
print('Distance:%0.2f cm'%checkdist())
time.sleep(1)
except KeyboardInterrupt:
pass
网友评论