from machine import Pin
import time
# Define pin numbers
LED_PIN = 0 # GP0 on Raspberry Pi Pico
TRIGGER_PIN = 7 # GP7 on Raspberry Pi Pico
ECHO_PIN = 6 # GP6 on Raspberry Pi Pico
ULTRASOUND_THRESHOLD = 130 # Threshold distance in cm
# Initialize pins
led = Pin(LED_PIN, Pin.OUT)
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Function to measure distance
def measure_distance():
# Send a 10us pulse to trigger
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Wait for echo to go high
while echo.value() == 0:
pulse_start = time.ticks_us()
# Wait for echo to go low
while echo.value() == 1:
pulse_end = time.ticks_us()
# Calculate duration of pulse
pulse_duration = pulse_end - pulse_start
# Convert pulse duration to distance (in cm)
distance = (pulse_duration * 0.0343) / 2
return distance
# Main loop
while True:
# Measure distance
distance = measure_distance()
# If distance is less than the threshold, turn on the LED
if distance > ULTRASOUND_THRESHOLD:
led.value(1)
else:
led.value(0)
# Delay before next measurement
time.sleep(0.1)