from machine import Pin, PWM
from time import sleep
import utime
# Initialize ultrasonic sensor pins
trigger = Pin(28, Pin.OUT)
echo = Pin(27, Pin.IN)
# Initialize buzzer with PWM
buzzer = PWM(Pin(20))
# Function to measure distance using ultrasonic sensor
def measure_distance():
# Send a 10 microsecond pulse to trigger pin
trigger.value(1)
utime.sleep_us(10)
trigger.value(0)
# Wait for the echo pin to go high
while echo.value() == 0:
pulse_start = utime.ticks_us()
# Wait for the echo pin to go low again
while echo.value() == 1:
pulse_end = utime.ticks_us()
# Calculate pulse duration
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
# Convert pulse duration to distance
distance = (pulse_duration * 0.0343) / 2
return distance
# Function to turn on the buzzer with a specific frequency
def buzzer_on(frequency):
buzzer.freq(frequency)
buzzer.duty_u16(32768) # Set duty cycle to 50%
# Function to turn off the buzzer
def buzzer_off():
buzzer.duty_u16(0) # Set duty cycle to 0%
# Main loop
while True:
# Measure distance
distance = measure_distance()
# Print distance
print("Distance:", distance, "cm")
# Check if distance is less than or equal to 20 cm
if distance <= 20:
# Activate buzzer
buzzer_on(1000) # You can change the frequency as needed
print("Buzzer ON")
else:
# Deactivate buzzer
buzzer_off()
print("Buzzer OFF")
# Wait for a short period before taking the next measurement
sleep(0.1)