Salted fish ZTMR example-ultrasonic ranging
Main control board: ZTMR1.1python development board
Ultrasound module
The working principle of the ultrasonic module
(1) uses the IO port TRIG to trigger the distance measurement, and gives a high level signal of at least 10us.
(2) The module automatically sends eight 40khz square waves and automatically detects whether a signal returns.
(3) When a signal returns, a high level is output through the IO port ECHO. The duration of the high level is the time from the transmission of the ultrasonic wave to the return. Test distance = (high level time * speed of sound (340M / S)) / 2.
VCC provides 5V power supply, GND is ground wire, TRIG trigger control signal input, ECHO echo signal output and other four interface terminals.
Pin description
Pin | Explanation |
---|---|
VCC | 5v |
Trig | Output |
Echo | Input |
GND | GND |
# main.py -- put your code here!
import pyb
from pyb import Pin
from time import sleep_us,ticks_us
trig = Pin('A8',Pin.OUT_PP)
echo = Pin('A7',Pin.IN)
distance = 0
while True:
trig.value(1)
sleep_us(20)
trig.value(0)
while echo.value == 0:
trig.value(1)
sleep_us(20)
trig.value(0)
if echo.value() == 1:
ts = ticks_us() #开始时间
while echo.value()==1: #等待脉冲高电平结束
pass
te = ticks_us()
tc = te-ts #结束时间
distance = (tc*170)/10000 #us(微秒) 1微秒等于一百万分之一秒(10的负6次方秒)
print('distance',distance,'cm') #距离计算 (单位为:cm)
pyb.udelay(20)
Serial tool to see the effect