今日目標
在學會讀取溫溼度與光線等環境數據之後,今天我們要讓ESP32具備空間感知的能力。我們將在Wokwi中加入HC-SR04超音波感測器,利用聲波反射的時間差來計算障礙物的距離,模擬汽車的倒車雷達或防撞系統的核心運作方式。
程式碼
import time
from machine import Pin, time_pulse_us
trig = Pin(2, Pin.OUT)
echo = Pin(18, Pin.IN)
led = Pin(2, Pin.OUT)
print("=== 超音波距離測量系統啟動 ===")
def get_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duration = time_palse_us(echo, 1, 30000)
if duration < 0:
return None
distance = (duration * 0.0343)/2
return distance
while True:
dist = get.distance()
if dist is not None:
print(f"【距離測量】當前距離:{dist:.1f}cm")
if dist < 20:
led.value(1)
print("警告:距離過近!(小於20cm)")
else:
led.value(0)
else:
print("量測超出範圍或無反射訊號")
time.sleep(0.5)
心得
今天學會利用MicroPython內建的time_palse_us()來捕捉微秒等級的高電位時間,並成功將物理聲波的反射時間換算成公分距離。讓我體會到超音波感測器是實作中非常實用的模組。