from machine import Pin, time_pulse_us
import time
# Define pins
TRIG = Pin(4, Pin.OUT)
ECHO = Pin(5, Pin.IN)
PIR = Pin(14, Pin.IN)
LED = Pin(13, Pin.OUT)
def get_distance():
# Trigger the ultrasonic burst
TRIG.off()
time.sleep_us(2)
TRIG.on()
time.sleep_us(10)
TRIG.off()
# Measure the echo duration
duration = time_pulse_us(ECHO, 1, 30000) # 30ms timeout
distance_cm = (duration / 2) / 29.1 # Convert to cm
return distance_cm
while True:
distance = get_distance()
motion = PIR.value() # 1 = motion detected, 0 = no motion
print("Distance:", distance, "cm | Motion:", motion)
# Combine both conditions
if distance < 50 and motion == 1:
LED.on()
print("Doorbell ON - Someone is at the door!")
else:
LED.off()
time.sleep(0.5)