from machine import Pin, time_pulse_us
import time
SOUND_SPEED=340 # sound speed in the air
TRIG_PULSE_DURATION_US=10
trig_pin = Pin(15, Pin.OUT) # Pico GP15 pin
echo_pin = Pin(14, Pin.IN) # Pico GP14 pin
led_pin = Pin(13, Pin. OUT)
while True:
# Prepare the signal
trig_pin.value(0)
time.sleep_us(5)
# 10 µs impulse
trig_pin.value(1)
time.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
ultrason_duration = time_pulse_us(echo_pin, 1, 30000) # Returns the propagation time of the wave. (µs)
distance_cm = SOUND_SPEED * ultrason_duration / 20000
if distance_cm <= 200:
led_pin.value(1)
else:
led_pin.value(0)
print(f"Distance : {distance_cm} cm")
time.sleep_ms(500)