from machine import Pin, PWM
import time
# Pins
trig = Pin(0, Pin.OUT)
echo = Pin(1, Pin.IN)
led = Pin(2, Pin.OUT)
# Use PWM for buzzer
buzzer = PWM(Pin(14))
buzzer.duty_u16(0) # start OFF
def get_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
while echo.value() == 0:
pass
start = time.ticks_us()
while echo.value() == 1:
pass
end = time.ticks_us()
duration = time.ticks_diff(end, start)
distance = (duration * 0.0343) / 2
return distance
while True:
dist = get_distance()
print("Distance:", dist, "cm")
print("Safe")
# Default OFF
led.off()
buzzer.duty_u16(0)
if dist < 50:
# Turn ON buzzer with sound
buzzer.freq(1000) # 1kHz sound
buzzer.duty_u16(30000) # volume
print("Buzzer as less than 50m from the wall...")
if dist < 10:
led.on()
print("LED lights up as less than 10m from wall...")
time.sleep(0.1)