import machine
import time
# Define the pins for the trigger and echo
trigger_pin = machine.Pin(12, machine.Pin.OUT)
echo_pin = machine.Pin(14, machine.Pin.IN)
def measure_distance():
# Send a 10us pulse to start the measurement
trigger_pin.value(0)
time.sleep_us(2)
trigger_pin.value(1)
time.sleep_us(10)
trigger_pin.value(0)
# Wait for the echo pin to go high
while echo_pin.value() == 0:
pass
start = time.ticks_us()
# Wait for the echo pin to go low
while echo_pin.value() == 1:
pass
end = time.ticks_us()
# Calculate the duration of the echo pulse
duration = time.ticks_diff(end, start)
# Calculate the distance (duration of the echo pulse in microseconds / 58 = distance in cm)
distance = duration / 58
return distance
while True:
print('Distance:', measure_distance(), 'cm')
time.sleep(1)