# Import required libraries
from machine import Pin
import utime
# Define the trigger and echo pins
trigger_pin = Pin(5, Pin.OUT)
echo_pin = Pin(6, Pin.IN)
led_pin = Pin(7, Pin.OUT)
# Define a function to get the distance measured by the sensor
def get_distance():
# Set the trigger pin to high for 10 microseconds to send a pulse
trigger_pin.high()
utime.sleep_us(10)
trigger_pin.low()
# Wait for the echo pin to go high and measure the time taken
while echo_pin.value() == 0:
pulse_start = utime.ticks_us()
while echo_pin.value() == 1:
pulse_end = utime.ticks_us()
# Calculate the distance using the time taken for the pulse to return
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance_cm = pulse_duration / 58
return distance_cm
# Main program loop
while True:
# Get the distance and print it
distance = get_distance()
print("Distance:", distance, "cm")
if distance < 200:
led_pin.on()
else:
led_pin.off()
# Wait for some time before taking another measurement
utime.sleep(1)