HC-SR04超聲波模塊測距原理:
給模塊1個最少10us的高電平,模塊接受到高電平后開始發(fā)射8個40KHz的聲波,echo腳會由0變?yōu)?,MCU開始計時,當(dāng)超聲波模塊接收到返回的聲波時,echo由1變?yōu)?,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