from machine import Pin, time_pulse_us
import time
# Define the pins for TRIG and ECHO
TRIG_PIN = 28
ECHO_PIN = 27
# Set up the TRIG and ECHO pins
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def get_distance():
# Send a 10us pulse to trigger the measurement
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
# Measure the duration of the pulse on the ECHO pin
duration = time_pulse_us(echo, Pin.high)
# Calculate the distance in centimeters
distance = (duration / 2) / 29.1 # Speed of sound is 34300 cm/s (29.1 us/cm for round trip)
return distance
while True:
distance = get_distance()
print("Distance: {:.2f} cm".format(distance))
time.sleep(1)