from machine import Pin, time_pulse_us
from time import sleep_us, sleep
# === CONFIGURATION ===
TRIGGER_PIN = 26
ECHO_PIN = 25
MAX_DISTANCE_CM = 500
ECHO_TIMEOUT_US = MAX_DISTANCE_CM * 2 / 0.0343 # time for max range
# === SETUP PINS (initialized once) ===
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def check_distance():
trigger.value(0)
sleep_us(2)
# Send 10µs pulse
trigger.value(1)
sleep_us(10)
trigger.value(0)
pulse_time = time_pulse_us(echo, 1, int(ECHO_TIMEOUT_US))
return pulse_time
def distance_cm():
pulse_time = check_distance()
distance = (pulse_time / 2) * 0.0343
if distance < 2 :
distance = 0
return distance
while True:
d_cm = distance_cm()
print("Distance: ", d_cm, "cm")
sleep(0.5)