33 lines
695 B
Python
33 lines
695 B
Python
from machine import Pin
|
|
import utime
|
|
|
|
trigger = Pin(2, Pin.OUT)
|
|
echo = Pin(3, Pin.IN)
|
|
|
|
sound = 340 * 100 # m/s * centi = cm/s
|
|
|
|
|
|
def ultra():
|
|
trigger.low()
|
|
utime.sleep_us(2)
|
|
trigger.high()
|
|
utime.sleep_us(10)
|
|
trigger.low()
|
|
|
|
# echo goes high as soon as sound wave is sent
|
|
# and returns to low once sound gets back
|
|
while echo.value() == 0:
|
|
sent_time = utime.ticks_us() # us
|
|
|
|
while echo.value() == 1:
|
|
received_time = utime.ticks_us() # us
|
|
|
|
delta_time = received_time - sent_time # us
|
|
distance = delta_time / 1_000_000 * sound / 2
|
|
print("The distance from object is", distance, "cm")
|
|
|
|
|
|
while True:
|
|
ultra()
|
|
utime.sleep(0.1)
|