# Traffic Control System
# Date: 4/12/2023
# Created by ZUNIE
# Import necessary libraries
from machine import Pin, SoftI2C, PWM
from utime import sleep
import SERVOLLLL
import OLEDLIBRARY
# Define GPIO pins
Servo_Pin = 26
Servo2_Pin = 27
warning_led_pin = Pin(13, Pin.OUT)
car_led_pin = Pin(12, Pin.OUT)
train_led_pin = Pin(14, Pin.OUT)
motion_sensor_pin = Pin(25, Pin.IN)
push_button_pin = Pin(15, Pin.IN, Pin.PULL_DOWN)
buzzer_pin = PWM(Pin(33), freq=1000)
# Create object instances
skrin = OLEDLIBRARY.SSD1306_I2C(width=128, height=64, i2c=SoftI2C(scl=Pin(22), sda=Pin(21)))
blade = SERVOLLLL.Servo(pin=Servo_Pin)
blade2 = SERVOLLLL.Servo(pin=Servo2_Pin)
# Function to control the traffic lights and sound the buzzer
def control_traffic_lights(is_train_mode):
warning_led_pin.off()
car_led_pin.off()
train_led_pin.off()
if motion_sensor_pin.value():
warning_led_pin.on()
skrin.fill(1) # Clear the OLED screen
skrin.text("Trainnn", 0, 0)
skrin.show()
# Create "tiktoktiktok" effect with the buzzer
for _ in range(4):
buzzer_pin.duty_u16(50000)
sleep(0.2)
buzzer_pin.duty_u16(0)
sleep(0.2)
warning_led_pin.off()
if is_train_mode:
train_led_pin.on()
sleep(8) # Assume it takes 8 seconds for the train to pass
train_led_pin.off()
else:
car_led_pin.on()
sleep(5) # Assume it takes 5 seconds for the car to pass
car_led_pin.off()
skrin.fill(1) # Clear the OLED screen after the warning LED blinks
# Main loop
is_train_mode = False
while True:
if push_button_pin.value() == 1:
# Move both servo motors to 90 degrees
blade.set_angle(90)
blade2.set_angle(90)
is_train_mode = not is_train_mode
if is_train_mode:
skrin.text("Train Mode", 0, 16)
else:
skrin.text("Car Mode", 0, 16)
skrin.show()
sleep(0.5) # Debounce delay
control_traffic_lights(is_train_mode)
sleep(1)