from machine import Pin
import math
import time
trigger_pin = Pin(2, Pin.OUT)
echo_pin = Pin(3, Pin.IN)
def measure_distance():
trigger_pin.low()
time.sleep_us(2)
trigger_pin.high()
time.sleep_us(10)
trigger_pin.low()
while echo_pin.value() == 0:
pulse_start = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance_cm = (pulse_duration * 0.0340)/2
return round(distance_cm)
while True:
distnce = measure_distance()
print("Distance:", distnce, "cm")
time.sleep(2)