from machine import Pin, PWM
import time
trigger_pin = Pin(5, Pin.OUT)
echo_pin = Pin(18, Pin.IN)
buzzer_pin = PWM(Pin(2))
def get_distance():
# Send a short pulse to trigger the measurement
trigger_pin.off()
time.sleep_us(2)
trigger_pin.on()
time.sleep_us(10)
trigger_pin.off()
# Measure the echo duration
while echo_pin.value() == 0:
pulse_start = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
# Calculate the distance in cm
distance = pulse_duration * 0.034 / 2
return distance
def buzz(frequency):
buzzer_pin.freq(frequency)
buzzer_pin.duty(512) # Set duty cycle to 50% for sound
def stop_buzz():
buzzer_pin.duty(0) # No sound
while True:
distance = get_distance()
print(f"Distance: {distance:.2f} cm")
if distance < 20:
buzz(1000) # Buzz at 1000 Hz
elif distance < 50:
buzz(2000) # Buzz at 2000 Hz
else:
stop_buzz() # No sound
time.sleep(0.1) # Delay for 100ms