from machine import Pin
import utime
# Pin Definitions
TRIG = Pin(3, Pin.OUT)
ECHO = Pin(2, Pin.IN)
def measure_distance():
# Send 10us pulse to trigger
TRIG.low()
utime.sleep_us(2)
TRIG.high()
utime.sleep_us(10)
TRIG.low()
# Wait for echo to go high
while ECHO.value() == 0:
pulse_start = utime.ticks_us()
# Wait for echo to go low
while ECHO.value() == 1:
pulse_end = utime.ticks_us()
# Time difference
duration = pulse_end - pulse_start
# Speed of sound = 343 m/s or 0.0343 cm/us
distance = (duration * 0.0343) / 2
return distance
# Main Loop
while True:
dist = measure_distance()
print("Distance:", dist, "cm")
utime.sleep(1)