from machine import Pin, time_pulse_us
import time
trig = Pin(26, Pin.OUT)
echo = Pin(22, Pin.IN)
buzzer = Pin(17, Pin.OUT)
led = Pin(0, Pin.OUT)
SPEED=0.0343
def get_distance():
# Send trigger pulse
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
# Measure echo pulse
duration = time_pulse_us(echo, 1)
# Convert to distance (meters)
distance = ((duration *SPEED) / 2 )/100
real_dist=(400*distance)
return real_dist
while True:
distance = get_distance()
print("Distance: {:.2f} m".format(distance))
# Case 1: less than 50 m → buzzer beeping
if distance < 50 and distance >= 10:
buzzer.on()
time.sleep(0.2)
buzzer.off()
time.sleep(0.2)
# Case 2: less than 10 m → LED ON + continuous buzzer
elif distance < 10:
led.on()
buzzer.on()
else:
led.off()
buzzer.off()
time.sleep(0.1)