from machine import Pin, time_pulse_us
from time import sleep_us, sleep
LED_PIN = 5
ECHO_PIN = 26
TRIGGER_PIN = 27
led = Pin(LED_PIN, Pin.OUT)
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def measure_distance():
trigger.low()
sleep_us(2)
trigger.high()
sleep_us(10)
trigger.low()
# Measure the duration of the echo pulse (in microseconds)
pulse_duration = time_pulse_us(echo, Pin.high)
# Calculate the distance (in centimeters) using the speed of sound (343 m/s)
distance = pulse_duration * 0.0343 / 2
return distance
def main():
while True:
distance = measure_distance()
print("Distance:", distance, "cm")
if distance <= 150:
led.toggle()
else:
led.low()
sleep(1)
if __name__ == "__main__":
main()