from machine import Pin, PWM, time_pulse_us
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 ultrasonic sensor pins
TRIG_PIN = Pin(21, Pin.OUT)
ECHO_PIN = Pin(20, Pin.IN)
# Define buzzer
BUZZER = PWM(Pin(27))
# Initial state
gateOpening = False
gateClosing = False
circuitActive = True
def measure_distance():
# Trigger high for 10us to initiate the measurement
TRIG_PIN.off()
time.sleep_us(2)
TRIG_PIN.on()
time.sleep_us(10)
TRIG_PIN.off()
# Measure the duration of echo pulse
duration = time_pulse_us(ECHO_PIN, 1, 30000) # 30ms timeout
# Calculate distance in cm (duration / 2) / 29.1
distance = (duration / 2) / 29.1
return distance
def open_gate():
global gateOpening, gateClosing
gateOpening = True
gateClosing = False
RED_LED.off()
YELLOW_LED.off()
# Simulate gate opening
for i in range(10):
if measure_distance() < 10: # 10 cm threshold for obstacle detection
stop_gate_due_to_obstacle()
return
GREEN_LED.on()
time.sleep(0.5)
GREEN_LED.off()
time.sleep(0.5)
GREEN_LED.on()
gateOpening = False
play_buzzer_tone(2000, 0.5) # Play a tone indicating the gate is fully opened
def close_gate():
global gateOpening, gateClosing
gateClosing = True
gateOpening = False
GREEN_LED.off()
YELLOW_LED.off()
# Simulate gate closing
for i in range(10):
if measure_distance() < 10: # 10 cm threshold for obstacle detection
stop_gate_due_to_obstacle()
return
RED_LED.on()
time.sleep(0.5)
RED_LED.off()
def main():
measure_distance()
open_gate()
close_gate()
main()