from machine import Pin
import utime
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
def distanceSensor():
trigger.low() # Mute the sensor (could also use trigger.value(0))
utime.sleep(.2) # Sleep for .2 seconds
trigger.high() # Emit sound
utime.sleep(.5) # Sleep
trigger.low() # Mute
while echo.value() == 0: # While no echo signal
off = utime.ticks_us()
while echo.value() == 1: # Once we get a signal
on = utime.ticks_us()
timepassed = on - off # How long between sending a pulse and getting a return signal
distance = (timepassed * 0.0343) / 2 # Calculate time of flight
print("The distance is", distance, "cm")
# Simple loop to test the function
while True:
distanceSensor()
utime.sleep(.1)