import time
from machine import Pin, time_pulse_us
TRIG_PIN = 5
ECHO_PIN = 18
BUZZER_PIN = 4
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
def get_distance_cm():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000) # 30ms timeout ~ 5m max range
if duration < 0:
return None
return (duration * 0.0343) / 2 # speed of sound -> cm
print("Ultrasonic obstacle alert system started.")
while True:
distance = get_distance_cm()
if distance is None:
print("No echo received (out of range).")
buzzer.value(0)
else:
print("Distance: {:.1f} cm".format(distance))
if distance < 15:
buzzer.value(1)
print("BUZZER ON - Obstacle too close!")
else:
buzzer.value(0)
print("BUZZER OFF - Clear path")
print("------------------------")
time.sleep(1)