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():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000)
if duration < 0:
return None
return duration * 0.0343 / 2
print("Ultrasonic obstacle alert system started.")
while True:
distance = get_distance()
if distance is None:
buzzer.value(0)
print("No echo received")
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")
time.sleep(1)