from machine import Pin
from time import sleep_us, sleep, ticks_us, ticks_diff
# Define the velocity of sound
soundVelocity=340
# Define led, Trigger and echo pins
triggerPin = Pin(14,Pin.OUT)
echoPin = Pin(17,Pin.IN)
led = Pin(21, Pin.OUT)
print("Start Measuring distance")
# Start an endless loop
while True:
# Set the Trigger pin to LOW
triggerPin.off()
sleep_us(5)
# Make a 10 microSeconds HIGH pulse
triggerPin.on()
sleep_us(10)
triggerPin.off()
# Wait for the echo pin to get to ON status
while (echoPin.value() == 0):
pass
# Start measuring the time
startTime = ticks_us()
# Wait for the echo pin to get to OFF status
while (echoPin.value() == 1):
pass
# Stop measuring the time
stopTime = ticks_us()
# Calculate the time for the echo to arrive
echoTime = ticks_diff(stopTime,startTime)
# Calculate the distance
distance = echoTime*soundVelocity/2/10000
# Print the distance
print("Distance: %5.1f" % (distance),"cm")
if (distance<20):
led.on()
sleep(0.2)