from machine import Pin, time_pulse_us
import utime
# Initializing pins for trigger and echo
trigger = Pin(27, Pin.OUT)
echo = Pin(26, Pin.IN)
# Continuously get distance measurements while the board has power
while True:
# Trigger pulse
trigger.low()
utime.sleep_us(5)
trigger.high()
utime.sleep_us(12)
trigger.low()
# Wait for echo (timeout = 50ms)
pulse_us = time_pulse_us(echo, 1, 50000)
if pulse_us < 0:
print("Error: No echo") # Checking for errors
else:
# Converting time into distance
# Sound travels at about 343 m/s, which is 0.0343 cm per microsecond
# Dividing by 2 because the time includes both the trip to the object and the return
distance_cm = (pulse_us / 2) * 0.0343
print(f"Distance: {distance_cm:.1f} cm") # print the calculated distance value with 1 decimal place
utime.sleep(0.5)