from machine import Pin, PWM
import time
# Define LEDs
RED_LED = Pin(3, Pin.OUT)
YELLOW_LED = Pin(4, Pin.OUT)
GREEN_LED = Pin(5, Pin.OUT)
# Define switches
SW1 = Pin(0, Pin.IN, Pin.PULL_DOWN)
SW2 = Pin(1, Pin.IN, Pin.PULL_UP)
SW3 = Pin(2, Pin.IN, Pin.PULL_UP)
# Define PIR sensor and buzzer
PIR_SENSOR = Pin(21, Pin.IN)
BUZZER = PWM(Pin(27))
# Initial state
gateOpening = False
gateClosing = False
def open_gate():
global gateOpening, gateClosing
gateOpening = True
gateClosing = False
RED_LED.off()
YELLOW_LED.on()
# Simulate gate opening
for i in range(10):
YELLOW_LED.on()
time.sleep(0.5)
YELLOW_LED.off()
time.sleep(0.5)
YELLOW_LED.on()
gateOpening = False
def close_gate():
global gateOpening, gateClosing
gateClosing = True
gateOpening = False
YELLOW_LED.off()
RED_LED.on()
# Simulate gate closing
for i in range(10):
RED_LED.on()
time.sleep(0.5)
RED_LED.off()
time.sleep(0.5)
RED_LED.on()
gateClosing = False
def stop_gate():
global gateOpening, gateClosing
gateOpening = False
gateClosing = False
RED_LED.off()
YELLOW_LED.off()
def play_buzzer_tone(frequency, duration):
BUZZER.freq(int(frequency))
BUZZER.duty_u16(32768) # 50% duty cycle
time.sleep(duration)
BUZZER.duty_u16(0) # Stop buzzer
while True:
sw1_state = SW1.value()
sw2_state = SW2.value()
sw3_state = SW3.value()
pir_detected = PIR_SENSOR.value()
if sw1_state == 1:
print("SW1 pressed")
if gateOpening or gateClosing:
stop_gate()
else:
# Toggle the gate state
if YELLOW_LED.value() == 1:
close_gate()
else:
open_gate()
if sw2_state == 0:
print("SW2 pressed")
close_gate()
if sw3_state == 0:
print("SW3 pressed")
open_gate()
if pir_detected:
print("PIR detected")
stop_gate()
GREEN_LED.on()
play_buzzer_tone(1000, 0.5) # Play a high-pitched tone for 0.5 seconds
play_buzzer_tone(500, 0.5) # Play a low-pitched tone for 0.5 seconds
else:
GREEN_LED.off()
BUZZER.duty_u16(0) # Stop buzzer
time.sleep(0.1) # Small delay for debouncing switches