import machine
import time
TRIG_PIN = machine.Pin(20, machine.Pin.OUT)
ECHO_PIN = machine.Pin(21, machine.Pin.IN)
BUZZER_PIN = machine.Pin(15, machine.Pin.OUT)
LED_PIN = machine.Pin(14, machine.Pin.OUT)
def send_trigger_pulse():
TRIG_PIN.low()
time.sleep_us(2)
TRIG_PIN.high()
time.sleep_us(10)
TRIG_PIN.low()
def get_echo_pulse_duration():
pulse_duration = machine.time_pulse_us(ECHO_PIN, 1, 30000) # Timeout set to 30ms (maximum range)
return pulse_duration
def distance_in_cm(pulse_duration):
# Speed of sound at sea level is approximately 343 meters per second (or 34300 cm/s)
# Distance = Speed * Time / 2 (since the sound traveled to the object and back)
distance = (pulse_duration / 2) * 0.0343
return distance
def alert():
for _ in range(4): # Repeat the alert beep 4 times
BUZZER_PIN.on()
LED_PIN.on()
time.sleep(0.25) # Beep and LED on duration (half a second)
BUZZER_PIN.off()
LED_PIN.off()
time.sleep(0.25) # Pause between beeps
def main():
while True:
send_trigger_pulse()
pulse_duration = get_echo_pulse_duration()
distance = (pulse_duration / 2) * 0.0343
if distance <= 15:
alert() # Alert beep sound and LED blinking
else:
LED_PIN.off() # Turn off the LED if distance is greater than 15 cm
print("Distance: {:.2f} cm".format(distance))
time.sleep(1)
if __name__ == "__main__":
main()