#Project: Smart Railway Gate Control System
#
#Description:
#  This project simulates an intelligent railway crossing system that automates
#  traffic lights and safety gates based on train detection. It aims to improve
#  safety by controlling gate movements and signals using sensor input and logic.
#
#Note: 
#  please be aware that you might experience delays, limited functionality, or slower  performance
#  These issues are more common in free version , which may not fully
#  #support real-time execution or advanced features.
#
#  For a smoother experience, consider using paid version or testing directly
#  on hardware whenever possible.
#
#  developed by Rababe Ben Abdelhadi


import machine
import time
from machine import Pin, I2C, PWM
import ssd1306
import servo_library
from utime import sleep 

# OLED Setup
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)

# PIR Sensor Setup
pir = Pin(15, Pin.IN)

# LED Setup
red_led = Pin(2, Pin.OUT)
yellow_led = Pin(4, Pin.OUT)
green_led = Pin(26, Pin.OUT)

# Buzzer Setup
buzzer =PWM(Pin(14, Pin.OUT))

# Servo Motor Setup
servo = machine.PWM(Pin(13), freq=50)
servo.duty(77)  # Initial position

while True:
    if pir.value() == 1:
        oled.fill(0)
        oled.text("Train Detected", 0, 0)
        oled.show()
        print("train detected don't cross ")
        green_led.off()
        yellow_led.on()  # Turn on yellow light as warning
        for _ in range(5):  # Blink yellow light for 5 seconds
            yellow_led.value(not yellow_led.value())
            time.sleep(1)
            buzzer.init(freq=1703,duty=400)
            sleep(0.2)
            buzzer.init(freq=1,duty=0)
            sleep(2)
            yellow_led.off()  # Turn off yellow light
        servo.duty(29)  # Keep gate closed
        oled.fill(0)
        oled.text("Train's crossing", 0, 0)
        oled.show()
        print("stay safe .. ")
        red_led.on()
        buzzer.init(freq=1703,duty=400)
        sleep(10)

       

    else:
        oled.fill(0)
        oled.text("No Train Detected", 0, 0)
        oled.show()
        print(" No train detected ")
        print("Check before crossing...")
        servo.duty(77)  # Open gate position
        red_led.off()
        yellow_led.off()
        green_led.on()
        buzzer.init(freq=1,duty=0)
        sleep(10)