from machine import Pin, time_pulse_us
import time
# Define pins
TRIG = Pin(21, Pin.OUT)
ECHO = Pin(27, Pin.IN)
LED = Pin(18, Pin.OUT)
def get_distance():
# Send a short trigger pulse
TRIG.low()
time.sleep_us(2)
TRIG.high()
time.sleep_us(10)
TRIG.low()
# Measure the duration of the echo pulse
duration = time_pulse_us(ECHO, 1, 30000) # 30ms timeout
distance = (duration * 0.0343) / 2 # Distance in cm
return distance
while True:
dist = get_distance()
print("Measured Distance = %.2f cm" % dist)
# LED control
if dist < 100:
LED.value(1)
else:
LED.value(0)
time.sleep(1)