ESP32 Micropython编程(Thonny)HC-SR04超声波测距仪

180it 2022-05-30 PM 1315℃ 0条

HC-SR04超声波测距仪

一、硬件连接
HC-SR04超声波测距仪 ESP32开发板
VCC 5V
Trig D2
Echo D4
GND GND
二、示例代码
注:以下程序不是标准库,自己编写

import machine, time
trig = machine.Pin(2,machine.Pin.OUT)
echo = machine.Pin(4,machine.Pin.IN)

def distance():
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)
    while echo.value() == 0:
        pass
    while echo.value() == 1:
        ts = time.ticks_us()
        while echo.value() == 1:
            pass
        te = time.ticks_us()
        tc = te - ts
        distance = round((tc*170)/10000, 2)
    return distance

while True:
    dist = distance()
    print('distance:', dist, 'cm')
    time.sleep(2)

在shell终端里可以看到

distance: 213.83 cm
distance: 210.95 cm
distance: 211.36 cm
distance: 211.24 cm
distance: 212.94 cm
distance: 211.46 cm
distance: 212.58 cm
distance: 212.82 cm
distance: 214.42 cm
distance: 215.27 cm
distance: 212.43 cm

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

ESP32 Micropython编程(Thonny)HC-SR04超声波测距仪