from machine import Pin, time_pulse_us
from time import sleep
trig = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
green_led = Pin(12, Pin.OUT)
red_led = Pin(13, Pin.OUT)
def measure_distance():
trig.low()
sleep(0.002)
trig.high()
sleep(0.01)
trig.low()
pulse_duration = time_pulse_us(echo, 1)
distance_cm = (pulse_duration * 0.0343) / 2
return distance_cm
while True:
d = measure_distance()
print("Distance:", d, "cm")
if d < 100:
red_led.on()
green_led.off()
else:
green_led.on()
red_led.off()
sleep(0.5)