# Modules
from machine import Pin, time_pulse_us
from time import sleep_us, sleep
# Pins
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
sound_speed = 0.0343 # Constant
# Measuring distance function
def measure_distance():
# On trigger pin to release the signal
trig.off()
sleep_us(2)
trig.on()
sleep_us(10)
trig.off()
time = time_pulse_us(echo, 1) # Getting time
# Calculating distance
distance = (sound_speed * time) / 2
return distance
# Main Loop
while True:
cm = measure_distance()
print(f"Distance = {round(cm, 2)} cm")
sleep(1)