from machine import Pin, time_pulse_us
import time
# Defining the pin connections for Ultrasonic Sensor and Buzzer
trigger_pin = 27 # initialize the trigger pin to 27
echo_pin = 26 # initialize the echo pin to 26
buzzer_pin = 17 # initialize the buzzer pin to 17
# Initializing the pins as Input or Output
trigger = Pin(trigger_pin, Pin.OUT)
echo = Pin(echo_pin, Pin.IN)
buzzer=Pin(buzzer_pin,Pin.OUT)
# Creating a function to measure distance using Ultrasonic Sensor
def measure_distance():
# Sending a 10 microsecond pulse to trigger the sensor
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Measuring the duration of the pulse on the echo pin
duration = time_pulse_us(echo, 1, 30000) # Timeout set to 30,000 microseconds (30ms)
# Calculating distance in centimeters
distance_cm = (duration / 2) /29.1
return distance_cm #returning the calculated distance
# Main loop
while True:
distance = measure_distance()
print("Distance:", distance, "cm")
# Wait for some time before the next measurement
time.sleep(1)
# The conditional statements for the buzzer
if distance<15:
buzzer.value(1) # Activates the buzzer
else:
buzzer.value(0) # Decactivates the buzzer