import machine
import utime
# GPIO Pin assignments
TRIG_PIN = 15 # GPIO Pin for Trigger
ECHO_PIN = 14 # GPIO Pin for Echo
BUZZER_PIN = 16 # GPIO Pin for Buzzer
# Set up GPIO pins
trigger = machine.Pin(TRIG_PIN, machine.Pin.OUT)
echo = machine.Pin(ECHO_PIN, machine.Pin.IN)
buzzer = machine.Pin(BUZZER_PIN, machine.Pin.OUT)
# Function to measure distance using the Ultrasonic Distance Sensor
def measure_distance():
# Send a trigger pulse
trigger.off() # Set trigger pin low
utime.sleep_us(2)
trigger.on() # Set trigger pin high
utime.sleep_us(10)
trigger.off() # Set trigger pin low
# Measure the duration of the echo pulse
while echo.value() == 0:
pulse_start = utime.ticks_us()
while echo.value() == 1:
pulse_end = utime.ticks_us()
# Calculate distance from pulse duration
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
speed_of_sound = 34300 # Speed of sound in cm/s
distance = (pulse_duration * speed_of_sound) / 2 / 1000000 # Convert to meters
return distance
# Set minimum distance threshold for buzzer activation (in cm)
MIN_DISTANCE_THRESHOLD = 20
# Continuously acquire distance measurements while the board has power
while True:
distance_cm = measure_distance() * 100 # Convert to cm
print("Distance: {:.2f} cm".format(distance_cm))
# Check if distance is below the threshold for buzzer activation
if distance_cm < MIN_DISTANCE_THRESHOLD:
buzzer.on() # Turn on the buzzer
else:
buzzer.off() # Turn off the buzzer
utime.sleep(0.1)