from machine import Pin
import utime
# Define pins
trig_pin = Pin(3, Pin.OUT)
echo_pin = Pin(2, Pin.IN)
# Speed of sound in cm/s (adjust if needed for your sensor)
sound_speed = 34300
def get_distance():
# Send a 10 microsecond pulse to the trigger pin
trig_pin.high()
utime.sleep_us(10)
trig_pin.low()
# Measure pulse duration
pulse_start = utime.ticks_us()
while echo_pin.value() == 0:
pass
pulse_start = utime.ticks_us()
while echo_pin.value() == 1:
pass
pulse_end = utime.ticks_us()
pulse_duration = pulse_end - pulse_start
# Calculate distance (round to 2 decimal places)
distance = (pulse_duration * sound_speed) / (2 * 1000000) # Convert ticks to seconds and divide by 2 for round trip
return round(distance, 2)
while True:
# Get distance measurement
distance = get_distance()
# Print distance to serial monitor
print("Distance:", distance, "cm")
# Delay between measurements (adjust as needed)
utime.sleep(0.5)