from machine import Pin, PWM
import time
# Initialize components
buzzer = PWM(Pin(19)) # Passive buzzer on GPIO 19
led_detection = Pin(21, Pin.OUT) # Detection LED on GPIO 21
#led_object = Pin(27, Pin.OUT) # Object LED on GPIO 27
trig = Pin(25, Pin.OUT) # Trig pin for ultrasonic sensor on GPIO 25
echo = Pin(26, Pin.IN) # Echo pin for ultrasonic sensor on GPIO 26
# Function to play a tone on the buzzer
def play_tone(frequency, duration):
buzzer.freq(frequency) # Set frequency
buzzer.duty_u16(512) # 50% duty cycle
time.sleep(duration) # Play for the duration
buzzer.duty_u16(0) # Stop the buzzer
# Function to measure distance using the ultrasonic sensor
def measure_distance():
trig.off()
time.sleep_us(2)
trig.on()
time.sleep_us(10)
trig.off()
# Measure the duration of the echo pulse
while echo.value() == 0:
pass
start_time = time.ticks_us()
while echo.value() == 1:
pass
end_time = time.ticks_us()
# Calculate distance (duration * speed of sound / 2)
duration = time.ticks_diff(end_time, start_time)
distance = (duration / 2) / 29.1 # Convert to cm
return distance
# Test loop
while True:
distance = measure_distance()
print("Distance:", distance, "cm")
if distance < 10: # Object detected within 10 cm
play_tone(1000, 0.1) # Beep buzzer
led_detection.value(1) # Turn ON detection LED
#led_object.value(1) # Turn ON object LED
else:
led_detection.value(0) # Turn OFF detection LED
#led_object.value(0) # Turn OFF object LED
time.sleep(0.5) # Wait before the next measurement