from machine import Pin, time_pulse_us
import time
# Define GPIO pins
PIN_TRIGGER = Pin(4, Pin.OUT)
PIN_ECHO = Pin(17, Pin.IN)
def measure_distance():
# Ensure the trigger is low
PIN_TRIGGER.value(0)
time.sleep_us(2)
# Send a 10-microsecond pulse
PIN_TRIGGER.value(1)
time.sleep_us(10)
PIN_TRIGGER.value(0)
# Measure the duration of the echo pulse
pulse_duration = time_pulse_us(PIN_ECHO, 1, 30000) # Timeout after 30ms
# If no echo pulse detected, return None
if pulse_duration < 0:
return None
# Calculate distance (cm)
distance = (pulse_duration * 0.0343) / 2
return round(distance, 2)
try:
print("Waiting for sensor to settle")
time.sleep(2) # Allow sensor to stabilize
while True:
print("Calculating distance...")
distance = measure_distance()
if distance is None:
print("No echo received. Try again.")
else:
print(f"Distance: {distance} cm")
time.sleep(1)
except KeyboardInterrupt:
print("Measurement stopped by user.")