from machine import Pin
import time
# 1. Setup the Hardware Pins
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
warning_led = Pin(15, Pin.OUT)
def measure_distance():
# Send a quick 10-microsecond sound pulse from the sensor
trigger.low()
time.sleep_us(2)
trigger.high()
time.sleep_us(10)
trigger.low()
# Start a stopwatch when the sound wave leaves
while echo.value() == 0:
signaloff = time.ticks_us()
# Stop the stopwatch when the sound wave bounces back
while echo.value() == 1:
signalon = time.ticks_us()
# Calculate how much time passed in microseconds
timepassed = signalon - signaloff
# Convert time to distance (Speed of sound is ~0.0343 cm/microsecond)
# Divide by 2 because the sound traveled to the object AND back
distance_cm = (timepassed * 0.0343) / 2
return distance_cm
print("Starting Parking Assist System...")
# 2. The Main Loop (This runs forever while the board has power)
while True:
dist = measure_distance()
print("Distance to object:", round(dist, 1), "cm")
# 3. The Logic: Turn on the LED if an object is closer than 100cm
if dist < 100:
warning_led.value(1)
else:
warning_led.value(0)
# Wait half a second before checking the distance again
time.sleep(0.5)