import machine
import utime
# Define the GPIO pins for the ultrasonic sensor
TRIGGER_PIN = 23
ECHO_PIN = 22
# Initialize the trigger and echo pins
trigger = machine.Pin(TRIGGER_PIN, machine.Pin.OUT)
echo = machine.Pin(ECHO_PIN, machine.Pin.IN)
# Function to measure distance using the ultrasonic sensor
def measure_distance():
# Send a trigger pulse to the sensor
trigger.value(1)
utime.sleep_us(10)
trigger.value(0)
# Wait for the echo pin to go high
while echo.value() == 0:
pass
pulse_start = utime.ticks_us()
# Wait for the echo pin to go low
while echo.value() == 1:
pass
pulse_end = utime.ticks_us()
# Calculate the pulse duration and convert it to distance (in centimeters)
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance_cm = pulse_duration / 58.0
return distance_cm
try:
while True:
distance = measure_distance()
print("Distance: {:.2f} cm".format(distance))
utime.sleep(1) # Delay for 1 second between measurements
except KeyboardInterrupt:
pass