#The door will automatically open when a person comes closer
import machine
import utime

trigger = machine.Pin(0, machine.Pin.OUT)#Output pin is assigned as 0
echo = machine.Pin(1, machine.Pin.IN, machine.Pin.PULL_DOWN)#Input pin is assigned as 0

# Initialize PWM output for the servo motor
servo = machine.PWM(machine.Pin(16))
servo.freq(50) # Set PWM frequency to 50 Hz
SERVO_CLOSED = 1500
SERVO_OPEN = 8100
check=True# Using these check variable to make run if or elif condition one and wait until next condition satisfies.
check1=True
while True:
    trigger.low()
    utime.sleep_us(2)
    trigger.high()
    utime.sleep_us(5)
    trigger.low()
    while echo.value() == 0:
        send = utime.ticks_us()#Store the value when triggered is send
    while echo.value() == 1:
        received = utime.ticks_us()#Store the value when triggered is received
    duration = received - send
    distance = (duration * 0.0343) / 2#Calculated distance and duration
    print(distance, "cm")
    utime.sleep(1)
    # Define constants for servo positions
    if distance < 150 and check:
        # If distance is less than 150, the person arrived closely.
        # Gradually open the door
        check=False
        check1=True
        for duty in range(SERVO_CLOSED, SERVO_OPEN + 1, 100):# Increment duty in steps of 100
            servo.duty_u16(duty)
            utime.sleep_ms(100)  # Adjust the delay based on the desired speed
    elif distance>150 and check1:
        # The person is away from the door, so the door will gradually close
        check1=False
        check=True
        for duty in range(SERVO_OPEN, SERVO_CLOSED - 1, -100):  # Decrement duty in steps of 100
            servo.duty_u16(duty)
            utime.sleep_ms(100)  # Adjust the delay based on the desired speed
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT