from machine import Pin, time_pulse_us
import utime
# LED setup
led = Pin(15, Pin.OUT)
# Ultrasonic Sensor Pins
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
def get_distance():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
trigger.low()
pulse_duration = time_pulse_us(echo, 1, 30000) # Measure echo time
distance = (pulse_duration * 0.0343) / 2 # Convert to cm
return distance
while True:
distance = get_distance()
print("Distance:", distance, "cm")
if distance < 10: # If object is closer than 10cm, turn LED ON
led.value(1)
else:
led.value(0)
utime.sleep(1) # Wait for 1 second