print("Project: Goal 9 (Industries, Inovation & Infrastructure)")
print("Dateline: 22/11/2024")
print("Created By: Jd")
#Import Libraries
from machine import Pin, PWM
from time import sleep
#Pin Declaration
ir_sensor_approach = Pin(15, Pin.IN) # IR sensor to detect approaching train (orange)
ir_sensor_depart = Pin(16, Pin.IN) # IR sensor to detect departing train (yellow)
servo_pin = PWM(Pin(4)) # Servo motor control pin
red_led = Pin(18, Pin.OUT) # Red LED for closed gate
green_led = Pin(19, Pin.OUT) # Green LED for open gate
buzzer = PWM(Pin(21)) # Buzzer configured as PWM
# Servo motor configuration
servo_pin.freq(50)
def set_servo_angle(angle):
"""Set servo motor to a specific angle."""
duty = int((angle / 180.0 * 102) + 26) # Map angle to duty cycle (26-128)
servo_pin.duty(duty)
# Buzzer functions
def buzzer_on():
"""Turn the buzzer on by setting a duty cycle."""
buzzer.freq(1000) # Set the buzzer frequency (e.g., 1 kHz)
buzzer.duty(512) # 50% duty cycle for sound
def buzzer_off():
"""Turn the buzzer off by setting the duty cycle to zero."""
buzzer.duty(0)
#Main Program
set_servo_angle(90) # Open gate
red_led.off()
green_led.on()
print("System ready. Gate is open.")
try:
while True:
# Check if train is approaching
if ir_sensor_approach.value() == 0: # IR sensor detects train
print("Train approaching! Closing gate.")
green_led.off()
red_led.on()
# Warning sound
for _ in range(5):
buzzer_on()
sleep(0.2)
buzzer_off()
sleep(0.2)
# Close the gate
set_servo_angle(0) # Gate closed
print("Gate is closed.")
# Check if train has departed
if ir_sensor_depart.value() == 0: # IR sensor detects train departure
print("Train departed. Opening gate.")
red_led.off()
green_led.on()
# Open the gate
set_servo_angle(90) # Gate open
print("Gate is open.")
sleep(0.1) # Short delay to prevent rapid polling
except KeyboardInterrupt:
print("System shutting down.")
# Reset state
set_servo_angle(90) # Ensure gate is open
red_led.off()
green_led.on()
buzzer_off()