from machine import Pin, time_pulse_us
import utime
# Define the pins for the ultrasonic sensor
trigger_pin = Pin(2, Pin.OUT) # GPIO pin for trigger
echo_pin = Pin(3, Pin.IN) # GPIO pin for echo
def measure_distance():
# Send a 10us pulse to the trigger pin to start the measurement
trigger_pin.value(1)
utime.sleep_us(10)
trigger_pin.value(0)
# Measure the duration of the pulse on the echo pin
pulse_duration = time_pulse_us(echo_pin, 1, 30000)
# Speed of sound is approximately 343 meters per second (29 microseconds per centimeter)
# Calculate the distance in centimeters
distance_cm = pulse_duration / 29 / 2
return distance_cm
while True:
# Measure distance and print the result
distance = measure_distance()
print(f"Distance: {distance} cm")
# Wait for a short duration before the next measurement
utime.sleep(1)