from machine import Pin
import time
# Define Pins
TRIG = Pin(14, Pin.OUT) # Trigger as Output
ECHO = Pin(15, Pin.IN) # Echo as Input
def get_distance():
# Step (b) - Generate start sequence
TRIG.value(0)
time.sleep_us(2000) # Hold trigger low for 2 ms
TRIG.value(1)
time.sleep_us(10) # Hold trigger high for 5 µs
TRIG.value(0)
# Step (c) - Wait for ECHO to go HIGH
while ECHO.value() == 0:
pass # Wait while ECHO is low
# Step (d) - Count high time
start_time = time.ticks_us()
while ECHO.value() == 1:
pass # Wait while ECHO is high
end_time = time.ticks_us()
# Step (e) - Compute distance
pulse_duration = time.ticks_diff(end_time, start_time) # Get pulse width in µs
distance = (pulse_duration * 0.0343) / 2 # Convert to cm
return distance
# Continuous loop to read distance
while True:
dist = get_distance()
print("Distance: {:.2f} cm".format(dist))
time.sleep(1) # Delay for readability