from machine import Pin, PWM
import utime
# Define GPIO pins
IR_RECEIVER_PIN = 4
SERVO_PIN = 2
RELAY_PIN = 6
# Initialize IR receiver pin
ir_receiver = Pin(IR_RECEIVER_PIN, Pin.IN)
# Initialize servo motor
servo = PWM(Pin(SERVO_PIN))
servo.freq(50) # Set PWM frequency to 50Hz
# Initialize relay pin
relay = Pin(RELAY_PIN, Pin.OUT)
# Function to rotate servo to 180-degree position
def rotate_servo():
utime.sleep(2.5)
servo.duty_u16(1622) # Set duty cycle for 180 degrees position
# Wait for servo to reach the position
# Function to turn on relay
def turn_on_relay():
relay.value(1) # Set relay pin high (turn on)
utime.sleep(0.5)
relay.value(0)
# Flag to track whether servo has already rotated
servo_rotated = False
# Loop to continuously read IR signals
while True:
if ir_receiver.value() == 0 and not servo_rotated:
# IR signal detected, turn on relay
turn_on_relay()
# Rotate servo to 180-degree position
rotate_servo()
servo_rotated = True