from machine import Pin
import utime
trigger = Pin(3,Pin.OUT)
echo = Pin(2,Pin.IN)
def ultra():
# Pull the trigger pin low, to ensure that it is not active, then pause for two microseconds.
trigger.low()
utime.sleep_us(2)
# Pull the trigger pin high for five microsends before pulling the trigger pin low
trigger.high()
utime.sleep_us(5)
trigger.low()
# Create a while loop to check the echo pin.
while echo.value() == 0:
# If no echo pulse is received, update a variable, signaloff so that it contains a timestamp in microseconds.
signaloff = utime.ticks_us()
# Create another while loop,
# this time to check if an echo has been received. This will store the current timestamp in microseconds to the signalon variable.
while echo.value() == 1:
signalon = utime.ticks_us()
# timepassed, which will store the value total time taken for the pulse to leave the sensor, hit the object and return back to the sensor as an echo.
timepassed = signalon - signaloff
# We multiply the journey time (timepassed) by the speed of sound (343.2 m/s,
# which is 0.0343 cm per microsecond) the product of that equation is
# divided by two as we do not need the total journey distance, just the distance from the object to the sensor.
distance = (timepassed * 0.0343) / 2
print("The distance from object is ",distance,"cm")
while True:
ultra()
utime.sleep(1)