from machine import Pin
import utime
from time import sleep
# Pin setup
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
LED1 = Pin(14, Pin.OUT)
LED2 = Pin(15, Pin.OUT)
# Initialize trigger
trigger.low()
utime.sleep_us(2)
while True:
# Trigger the ultrasonic sensor
trigger.high()
utime.sleep_us(5)
trigger.low()
# Measure the time it takes for the echo to return
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
# Calculate distance based on the time
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
print("The distance from object is ", distance, "cm")
# Control LEDs based on the distance
if distance > 100:
LED1.on()
LED2.off()
else:
LED1.off()
LED2.on()
# Pause before next measurement
sleep(1)