ESP32 simply implements the new version of HC-SR04 ultrasonic module (MicroPython+Thonny)

1. Brief introduction of new version HC-SR04

The performance of the new version HC-SR04 far exceeds that of the old version HC-SR04 and US-015; when the ranging accuracy is higher than that of the old version HC-SR04 and US-015, the ranging range
is farther General ultrasonic ranging module. Using CS-100A ultrasonic ranging SOC chip, high performance, industrial grade, wide voltage, low price, cost breakdown base price, only half the price of ordinary ultrasonic ranging modules, and performance far exceeds ordinary ultrasonic ranging modules. The performance is the same as US-025A, both adopt CS100A chip, and the interface is fully compatible.

New version HC-SR04

2. Circuit connection

ESP32 HC-SR04
3v3 VCC
GPIO19 Trig
GPIO18 Echo
GND GND

Fritzing connection diagram

3. MicroPython code

from machine import Pin
import time
# echo脚会由0变为1,MCU开始计时,当超声波模块接收到返回的声波时,echo由1变为0,MCU停止计时,
#定义IO口模式,以及初始状态
trig = Pin(19, Pin.OUT)
echo = Pin(18,  Pin.IN)
trig.value(0)
echo.value(0)
cars = 0
#构建函数
def measure():
  #触发超声波模块测距
  trig.value(1)
  time.sleep_us(10)
  trig.value(0)
  #检测回响信号,为低时,测距完成
  while(echo.value() == 0):
    pass
  #开始不断递增的微秒计数器 1 
    t1 = time.ticks_us()
  #检测回响信号,为高时,测距开始
  while(echo.value() == 1):
    pass
  #开始不断递增的微秒计数器 2 
    t2 = time.ticks_us()
  #计算两次调用 ticks_ms(), ticks_us(), 或 ticks_cpu()之间的时间,这里是ticks_us()
  # 这时间差就是测距总时间,在乘声音的传播速度340米/秒,除2就是距离。
  t3 = time.ticks_diff(t2,t1)/10000
  #返回一个值给调用方,不带表达式的return相当于返回 None。
  #这里返回的是:开始测距的时间减测距完成的时间*声音的速度/2(来回)
  return t3*340/2
 
result = measure()
 #try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理  
try:
    if int(result) < 10:
        cars += 1
    if cars == 1:
        print("已停车")
    if cars == 0:
        print("未停车")
    print("测量距离为:%0.2f cm" %float(result))
 
except KeyboardInterrupt:
    pass 

Guess you like

Origin blog.csdn.net/Little_Carter/article/details/128743786