from machine import Pin, time_pulse_us
import time
# Define pins connected to the HC-SR04 sensor
trigger_pin = Pin(4, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
# Function to measure distance from HC-SR04 sensor
def measure_distance():
# Send a 10us pulse on the trigger pin to start the measurement
trigger_pin.value(0)
time.sleep_us(2)
trigger_pin.value(1)
time.sleep_us(10)
trigger_pin.value(0)
# Measure the duration of the echo pulse on the echo pin
duration = time_pulse_us(echo_pin, 1, 30000) # Timeout of 30ms (30,000 microseconds)
# Calculate distance using the speed of sound (343 m/s)
# Divide by 2 because the sound wave travels to the object and back
distance = duration * 0.0343 / 2
return distance
# Main loop
while True:
# Measure distance from HC-SR04 sensor
distance = measure_distance()
# Print distance
print("Distance: {:.2f} cm".format(distance))
# Wait for a short period
time.sleep(1)