from machine import Pin, time_pulse_us
import time
# Pin setup
TRIG = Pin(17, Pin.OUT) # Trigger pin for HC-SR04
ECHO = Pin(16, Pin.IN) # Echo pin for HC-SR04
BUZZER = Pin(18, Pin.OUT) # Buzzer pin
def get_distance():
"""
Measures the distance using the HC-SR04 sensor.
Returns distance in meters.
"""
# Send a 10us pulse to trigger
TRIG.low()
time.sleep_us(2)
TRIG.high()
time.sleep_us(10)
TRIG.low()
# Measure the duration of the echo pulse
duration = time_pulse_us(ECHO, 1, 30000) # Wait for high, timeout after 30ms
# Convert duration to distance in meters (speed of sound = 343 m/s)
distance = (duration / 2) * 0.000343
return distance
try:
while True:
distance = get_distance() # Measure distance
print(f"Distance: {distance:.2f} meters") # Print distance for debugging
if distance >= 3.0:
# Beep the buzzer for distances 3m or greater
BUZZER.high()
time.sleep(0.2)
BUZZER.low()
time.sleep(0.2)
elif distance <= 1.0:
# Turn off the buzzer for distances 1m or less
BUZZER.low()
time.sleep(0.1) # Small delay for sensor stability
except KeyboardInterrupt:
print("Program stopped by user")
BUZZER.low() # Ensure the buzzer is off when exiting