import machine
import utime
# Define the pins connected to the sensor
trigger_pin = machine.Pin(0, machine.Pin.OUT)
echo_pin = machine.Pin(1, machine.Pin.IN)
# Function to measure distance using the ultrasonic sensor
def measure_distance():
# Send a 10us pulse on the trigger pin to start the measurement
trigger_pin.low()
utime.sleep_us(2)
trigger_pin.high()
utime.sleep_us(10)
trigger_pin.low()
# Measure the time it takes for the echo pin to go high and then low
while echo_pin.value() == 0:
pass
pulse_start = utime.ticks_us()
while echo_pin.value() == 1:
pass
pulse_end = utime.ticks_us()
# Calculate the distance using the speed of sound (343 meters/second)
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance = pulse_duration * 0.0343 / 2
return distance
# Main loop
while True:
try:
distance_cm = measure_distance()
print("Measured Distance: {:.2f} cm".format(distance_cm))
except Exception as e:
print("Error: ", e)
# Wait for a short delay before taking the next measurement
utime.sleep(1)