from machine import Pin, PWM
import time
# Define GPIO pins
TRIG = Pin(14, Pin.OUT) # Trigger
ECHO = Pin(15, Pin.IN) # Echo
BUZZER = PWM(Pin(16)) # Buzzer using PWM
# Function to measure distance
def get_distance():
TRIG.value(0)
time.sleep_us(2000) # Hold trigger low for 2 ms
TRIG.value(1)
time.sleep_us(5) # Hold trigger high for 5 µs
TRIG.value(0)
while ECHO.value() == 0:
pass # Wait for ECHO to go HIGH
start_time = time.ticks_us()
while ECHO.value() == 1:
pass # Wait for ECHO to go LOW
end_time = time.ticks_us()
pulse_duration = time.ticks_diff(end_time, start_time) # Get pulse width in µs
distance = (pulse_duration * 0.0343) / 2 # Convert to cm
return distance
# Function to control buzzer based on distance
def beep_buzzer(distance):
if distance > 150: # If far, no beeping
BUZZER.duty_u16(0) # Turn off buzzer
else:
freq = 1000 - (distance * 8) # Decrease frequency as car gets closer
if freq < 250:
freq = 250 # Minimum frequency limit
BUZZER.freq(int(freq)) # Set buzzer frequency
BUZZER.duty_u16(30000) # Set loudness (50%)
# Main loop
while True:
distance = get_distance()
print("Distance: {:.2f} cm".format(distance))
beep_buzzer(distance)
time.sleep(0.2) # Small delay for reading updates