from machine import Pin, time_pulse_us
import utime
trig_pin = Pin(17, Pin.OUT)
echo_pin = Pin(16, Pin.IN)
SOUND_SPEED = 343.2 # speed of sound 343.2 m/s
def ultraSonic():
# send a pulse for 10 millisecnods
trig_pin.high()
utime.sleep_ms(10)
trig_pin.low()
# calculate time to for pulse return
duration = time_pulse_us(echo_pin, 1)
# multiply duration by speed of sound,
# convert to cm, round to 1 decimal place
distance = round((SOUND_SPEED * duration / 20000), 1)
return distance
while True:
# get sensor reading
us_reading = ultraSonic()
print(f"Distance in cm: {us_reading}")
# take reading every second
utime.sleep(1)