import time
from machine import Pin
import utime
# Define the GPIO pins for the sensor
TRIGGER_PIN = 4 # GPIO pin for triggering the sensor
ECHO_PIN = 5 # GPIO pin for receiving echo pulses
pin_trigger = Pin(TRIGGER_PIN, machine.Pin.OUT)
pin_echo = Pin(ECHO_PIN, machine.Pin.IN)
def measure_distance():
"""Measures the distance using the ultrasonic sensor."""
# Send a 10-microsecond pulse to the trigger pin
pin_trigger.low()
utime.sleep_us(2)
pin_trigger.high()
utime.sleep_us(10)
pin_trigger.low()
# Measure the duration of the echo pulse
while pin_echo.value() == 0:
signaloff = utime.ticks_us() # Start time of echo pulse
while pin_echo.value() == 1:
signalon = utime.ticks_us() # End time of echo pulse
# Calculate the distance in centimeters using the speed of sound
pulse_duration = signalon - signaloff
distance = pulse_duration * 0.0343 / 2
return distance
while True:
print("Measuring Distance...")
distance = measure_distance()
print("Distance: {:.2f} cm".format(distance))