Sanjivani Rural Educational Society’s
SANJIVANI COLLEGE OF ENGINEERING ACAD-F-15 K
(An Autonomous Institution)
Kopargaon – 423 603, Maharashtra.
Academic Year: 2024-
CIA ACTIVITY REPORT
2025 Dated: 1-1-2024
Date of
Department: Computer Engineering Preparation: 11-
11-2024
Year/Sem: TY Sem-
Course Code & Name: Theory Of Computation (CO304)
I
Activity Title:
Design and implement FSM for Traffic Light Controller system
Submitted by:
Roll No PRN No Name of the Student Signature
01 UCS22M1001 Achare Tanmay
02 UCS22M1125 Tambe Ajinkya
03 UCS22F1137 Walke Akshata
Dr. N. G. Pardeshi
Course Incharge
1|Page Department of Computer Engineering
Table of Contents
Sr. No Title Page
No
1 Abstract 3
2 Problem Statement 4
3 Introduction 5
4 System architecture and Design 6
5 Methodologies and Algorithms 12
6 Conclusion 16
7 References 17
2|Page Department of Computer Engineering
1. Abstract
The Traffic Light Controller System is a fundamental example of a Finite State Machine (FSM)
application, designed to manage traffic flow at intersections by controlling the sequencing of
red, yellow, and green lights. This FSM system ensures predictable, efficient, and safe vehicle
movement by alternating traffic direction based on time intervals. The traffic light controller
operates through three main states: Green, Yellow, and Red. Each state transition is triggered
by a timer, guiding the sequence in a continuous loop to control vehicle and pedestrian
movement.
The FSM model offers a structured approach to implement predictable and easily manageable
traffic control logic, especially for multi-lane intersections or adaptive traffic systems.
Additionally, the FSM’s modular nature makes it adaptable to real-time conditions, such as
adjusting light durations based on traffic density or prioritizing emergency vehicles. Through
this design, the Traffic Light Controller demonstrates the effectiveness of FSM in managing
critical real-world systems where reliable, cyclic control is essential for operational efficiency
and public safety.
The FSM-based design for a Traffic Light Controller is particularly valuable in modern smart
cities, where efficient traffic management is essential to minimize congestion, reduce
emissions, and improve overall transportation flow. This system's implementation can extend
to IoT-enabled, adaptive traffic control, where sensors detect traffic density and dynamically
adjust signal timings, maximizing efficiency in high-traffic areas. By leveraging FSM
principles, the controller can ensure consistent, automated traffic sequencing while allowing
for easy integration of additional functionalities, such as pedestrian crossing signals or
emergency vehicle prioritization. This adaptability makes the FSM model a robust solution for
traffic control applications, providing a reliable, scalable foundation for intelligent urban traffic
management systems.
3|Page Department of Computer Engineering
2. Problem Statement
Design and implement a Finite State Machine (FSM) to control the traffic lights at a standard
intersection, ensuring the safe and efficient flow of traffic. The system should include three
primary states—Green, Yellow, and Red—representing the different phases of traffic control.
Each state must follow a specified duration to allow for adequate vehicle movement and
preparation for state transitions. The FSM must cycle through these states in a continuous,
predictable sequence. Additionally, the system should be capable of adapting to real-world
requirements, such as pedestrian crossings, emergency vehicle prioritization, and variable
traffic densities, while minimizing congestion and maximizing road safety. The goal is to create
a traffic control solution that can be integrated with smart city infrastructure and IoT
technologies to support adaptive, real-time traffic management.
4|Page Department of Computer Engineering
3. Introduction
Traffic lights are a critical component of urban infrastructure, providing structured control over
the movement of vehicles and pedestrians at intersections. The primary objective of a traffic
light controller system is to ensure the safe and orderly flow of traffic, reduce congestion, and
prevent accidents. Traditionally, traffic lights operate on a fixed timer, where each light—red,
yellow, or green—activates in a pre-determined sequence. However, as urban areas grow and
traffic patterns become more complex, traditional systems face challenges in managing the
dynamic flow of vehicles effectively. This has led to the exploration of more adaptive,
automated solutions for traffic control, one of which is the use of a Finite State Machine (FSM)
to manage traffic lights.
A Finite State Machine (FSM) is a computational model that operates through a defined set of
states, each with specific transitions triggered by events or time intervals. In the context of a
traffic light controller, FSM logic can manage the timing and transitions between the green,
yellow, and red lights. By structuring the light sequence into these finite states, an FSM offers
predictable, consistent control, cycling through each state based on time constraints. This
approach not only simplifies the design of traffic light controllers but also makes them more
adaptable, as additional states and transitions can be added to handle complex traffic
requirements, such as pedestrian crossings and emergency vehicle priority.
The implementation of an FSM-based traffic light controller is particularly valuable in smart
city applications, where traffic management requires a higher level of intelligence and
responsiveness. With the integration of IoT sensors and real-time data, FSM-driven systems
can adapt light sequences based on real-time traffic density, optimizing flow and reducing
delays. For instance, during off-peak hours, the FSM could allow longer green light phases, or
it could prioritize lanes with heavier traffic, making traffic control more efficient and reducing
unnecessary waiting times. Additionally, FSM-based systems are modular and scalable,
making it easier to implement them across multiple intersections and coordinate traffic flow in
larger metropolitan areas.
5|Page Department of Computer Engineering
4. System Architecture and Design
The FSM-based Traffic Light Controller System Architecture can be divided into several key
components that work together to manage the flow of traffic efficiently. The main components
include the Input Module, Finite State Machine (FSM) Controller, Timer Module, Sensor
Module (optional for adaptive systems), and Output Module. Here’s a breakdown of each
component and its function in the system.
1. Input Module
Purpose:
The Input Module captures signals and triggers that dictate the behaviour of the FSM. This
module primarily receives input from a timer, which triggers state transitions at pre-defined
intervals.
Components:
Inputs might include a fixed timer, external signals for pedestrian crossings, and optional inputs
from traffic density sensors (for adaptive systems).
Function:
It triggers state transitions (Green -> Yellow -> Red -> Green) based on timing intervals or
other conditions.
2. Finite State Machine (FSM) Controller
Purpose:
The FSM Controller is the central processing unit responsible for determining the system's
current state and transitioning between states based on the input conditions.
States:
The FSM has three primary states for each light cycle—Green, Yellow, and Red. For each state,
the FSM controller sets specific outputs to turn on the respective traffic lights.
Transition Logic:
Transition logic determines when to move from one state to the next. This can be based on a
simple timer for basic systems or traffic density data for adaptive systems.
State Diagram:
A state diagram defines the transitions between states, ensuring a smooth and predictable
sequence.
6|Page Department of Computer Engineering
Figure 1: FSM-based Traffic Light Controller System Architecture
3. Timer Module
Purpose:
The Timer Module manages the time duration for each traffic light phase (Green, Yellow,
Red) and signals the FSM Controller when it is time to transition.
Components:
This module may include fixed timers for each state (for basic systems) or dynamic timers
that can adjust timing based on real-time conditions (for adaptive systems).
Function:
For each state, the timer counts down from a pre-set time value and, upon reaching zero,
sends a signal to the FSM Controller to initiate a state transition.
4. Sensor Module (Optional)
Purpose:
This module collects real-time traffic data to enable adaptive control. It can include vehicle
detectors, traffic cameras, or pedestrian sensors.
Function:
In adaptive systems, the sensor module provides input to the FSM Controller, allowing the
system to dynamically adjust signal timings based on real-time traffic flow or pedestrian
presence.
Components:
7|Page Department of Computer Engineering
Sensors may include infrared detectors, pressure plates, or cameras at intersections to measure
traffic density or pedestrian crossings.
5. Output Module
Purpose:
The Output Module controls the physical traffic lights, activating the green, yellow, or red light
based on the FSM Controller's current state.
Components:
This includes hardware elements like LED indicators or other types of traffic lights installed at
the intersection.
Function:
The Output Module receives signals from the FSM Controller and illuminates the correct light
(Green, Yellow, or Red) based on the current state, guiding vehicle and pedestrian traffic.
System Flow
1. Initialization: The system initializes with a default state (e.g., Red).
2. State Transitioning: The Timer Module triggers state transitions by sending signals to the
FSM Controller.
3. Output Control: Based on the current state, the FSM Controller activates the appropriate
light in the Output Module.
4. Adaptation (Optional): If the system is adaptive, the Sensor Module provides additional
data to the FSM Controller, allowing it to dynamically adjust signal timing.
6. Implementation Considerations
Improvements:
1. Enum for States
Using an enum for states could improve readability and reduce the risk of typographical errors.
For example, instead of using strings like "NorthGreen", you could define an enum:
from enum import Enum
class TrafficState(Enum):
NORTH_GREEN = "North Green"
NORTH_YELLOW = "North Yellow"
EAST_GREEN = "East Green"
EAST_YELLOW = "East Yellow"
SOUTH_GREEN = "South Green"
SOUTH_YELLOW = "South Yellow"
8|Page Department of Computer Engineering
WEST_GREEN = "West Green"
WEST_YELLOW = "West Yellow"
2. Modularize the Code for Maintainability
Consider refactoring run_traffic_light_controller () so that it’s easier to adjust state durations
or add new states. For instance, you could move the states list outside the function, making it
a configurable parameter.
3. Dynamic Timing Adjustments
For adaptive control, you could modify durations based on real-time inputs, such as traffic
sensors. Instead of fixed durations, use variables that can be updated if traffic density changes.
4. Asynchronous Timing Control
The use of time.sleep() in a loop works for simple simulations but can block other operations.
For real-world or more complex simulations, consider asynchronous programming (e.g., using
asyncio in Python) to allow the FSM to handle other tasks while waiting.
5. Graceful Exit Handling
Adding exception handling for KeyboardInterrupt would allow for a clean exit on Ctrl+C,
improving user experience:
try:
run_traffic_light_controller()
except KeyboardInterrupt:
print("\nTraffic Light Controller stopped.")
6. Logging and Debugging
Consider adding a logging mechanism to track state transitions and durations for debugging
purposes, especially useful in complex, adaptive systems.
7. Testing and Simulation
Implement unit tests for the display_state() function and state transitions to ensure the FSM
behaves as expected. Simulations for different traffic densities or emergency scenarios can also
validate performance.
9|Page Department of Computer Engineering
8. Optional Adaptive Logic
If implementing a more advanced traffic system, sensors could be added to change state
durations dynamically. This could involve an additional function to fetch or calculate optimal
durations and update the states list accordingly.
With these considerations, your FSM-based traffic light controller could be more robust,
adaptable, and easier to maintain in various scenarios.
Python
import time
# Function to display the current state of traffic lights
def display_state(current_state):
# Initialize all directions to RED
north, east, south, west = "RED", "RED", "RED", "RED"
# Set the light for the current state
if current_state == "NorthGreen":
north = "GREEN"
elif current_state == "NorthYellow":
north = "YELLOW"
elif current_state == "EastGreen":
east = "GREEN"
elif current_state == "EastYellow":
east = "YELLOW"
elif current_state == "SouthGreen":
south = "GREEN"
elif current_state == "SouthYellow":
south = "YELLOW"
elif current_state == "WestGreen":
west = "GREEN"
elif current_state == "WestYellow":
west = "YELLOW"
# Display the status of traffic lights
10 | P a g e Department of Computer Engineering
print(f"North: {north}, East: {east}, South: {south}, West: {west}")
# Function to simulate traffic light controller
def run_traffic_light_controller():
# Define the states and their durations
states = [
("NorthGreen", 5), ("NorthYellow", 2),
("EastGreen", 5), ("EastYellow", 2),
("SouthGreen", 5), ("SouthYellow", 2),
("WestGreen", 5), ("WestYellow", 2)
]
# Infinite loop to run the FSM
while True:
for state, duration in states:
display_state(state)
time.sleep(duration) # Wait for the specified duration
# Main function
if __name__ == "__main__":
print("Starting Traffic Light Controller Simulation (Press Ctrl+C to stop)")
run_traffic_light_controller()
11 | P a g e Department of Computer Engineering
5. Methodology and Algorithms
This FSM-based traffic light controller operates on a sequence of states, each representing a direction
with specific durations for green, yellow, and red lights. Here is a step-by-step methodology to design
the FSM, with an outline of the algorithm for implementation:
Step 1: Define States and Transitions
1. Define States:
Identify all states in the traffic light cycle. For a four-way intersection, common states include:
NorthGreen, NorthYellow
EastGreen, EastYellow
SouthGreen, SouthYellow
WestGreen, WestYellow
2. Define Transition Rules:
Specify the order in which states transition. For a typical cycle:
NorthGreen → NorthYellow → EastGreen → EastYellow → SouthGreen → SouthYellow →
WestGreen → WestYellow → NorthGreen (and repeat).
3. Define State Duration:
Assign durations for each state (e.g., Green: 5 seconds, Yellow: 2 seconds).
Step 2: Initialize the System
1. Set Initial State:
Start with the first state, e.g., NorthGreen, with an initialized timer.
2. Set Default Durations:
Define the durations for green and yellow lights in each direction. Use a list or dictionary to
store the duration for each state.
12 | P a g e Department of Computer Engineering
Step 3: Implement the FSM Loop (Algorithm)
1. Loop Through States:
For each state in the sequence:
Display the state (indicating the active direction and colour).
Start a timer for the state’s duration (wait for the green or yellow time).
2. Transition to the Next State:
Once the duration for the current state ends, transition to the next state in the sequence.
Update the active direction and colour according to the new state.
3. Repeat Cycle:
Continue looping through the states in the defined sequence for continuous operation.
Step 4: Algorithm Outline (Pseudocode)
Here is the FSM process in pseudocode:
Python
Pseudocode
START
FUNCTION display_state(current_state):
Set all traffic lights to "RED"
IF current_state is "NorthGreen":
Set North to "GREEN"
ELSE IF current_state is "NorthYellow":
Set North to "YELLOW"
ELSE IF current_state is "EastGreen":
Set East to "GREEN"
ELSE IF current_state is "EastYellow":
Set East to "YELLOW"
ELSE IF current_state is "SouthGreen":
Set South to "GREEN"
13 | P a g e Department of Computer Engineering
ELSE IF current_state is "SouthYellow":
Set South to "YELLOW"
ELSE IF current_state is "WestGreen":
Set West to "GREEN"
ELSE IF current_state is "WestYellow":
Set West to "YELLOW"
Print all traffic lights status
FUNCTION run_traffic_light_controller():
Define states with durations (e.g., "NorthGreen", 5)
WHILE True:
FOR each state, duration IN states:
Call display_state(state)
Wait for the specified duration
Print "Starting Traffic Light Simulation"
Call run_traffic_light_controller()
END
14 | P a g e Department of Computer Engineering
Summary
The Traffic Light Controller uses an FSM to cycle through traffic light states (Green, Yellow)
for each direction. The system updates the light status and transitions between states at fixed
durations, continuously running the simulation until stopped.
Experimental Results
The following results are based on running the Traffic Light Controller simulation:
1. Simulation Setup:
States: The system cycles through eight states: NorthGreen, NorthYellow, EastGreen,
EastYellow, SouthGreen, SouthYellow, WestGreen, WestYellow.
Durations: Each Green light state lasts for 5 seconds, and each Yellow light state lasts for 2
seconds.
2. Cycle Duration:
Total cycle time (for one full round of NorthGreen → NorthYellow → EastGreen → ... →
WestYellow):
Green light: 5 seconds × 4 directions = 20 seconds
Yellow light: 2 seconds × 4 directions = 8 seconds
Total cycle duration = 20 seconds (Green) + 8 seconds (Yellow) = 28 seconds.
3. Traffic Light Transitions:
The traffic light transitions occur every 5 seconds for Green and every 2 seconds for Yellow
for each direction.
Example output:
North: GREEN, East: RED, South: RED, West: RED (for 5 seconds)
North: YELLOW, East: RED, South: RED, West: RED (for 2 seconds)
East: GREEN, North: RED, South: RED, West: RED (for 5 seconds)
... and so on.
4. Performance:
The system successfully simulates continuous traffic light control without any errors. Each
state transition is correctly timed, and the light statuses are accurately updated on the console.
5. User Interaction:
The simulation runs continuously until manually stopped (Ctrl+C), displaying the current
traffic light statuses for each direction at regular intervals. The system handles normal traffic
light cycles effectively with no unexpected behaviour during testing.
15 | P a g e Department of Computer Engineering
6. Conclusion
The FSM-based Traffic Light Controller successfully simulates the operation of a traffic light
system for an intersection with four directions (North, East, South, and West). By using a finite
state machine approach, the system efficiently manages the transitions between different light
states (Green, Yellow, Red) in a cyclic manner. The program follows a simple yet effective
logic to control the traffic lights, ensuring each direction gets appropriate time for green and
yellow signals, with smooth transitions between states.
The system runs in a continuous loop, updating the light status every few seconds according to
a predefined set of durations. The use of states and transitions ensures that the traffic light
operation is predictable and easy to follow. Each direction is allocated a fixed green time (5
seconds) and yellow time (2 seconds), which allows for synchronized traffic flow, while
avoiding unnecessary delays or congestion at the intersection.
While the current implementation is based on fixed durations, the design can be extended to
incorporate dynamic features such as adaptive timing based on traffic flow or sensor inputs.
This would make the system more flexible and capable of handling varying traffic conditions,
improving efficiency and reducing waiting times. Future improvements could also include
more advanced traffic management features, like emergency vehicle detection or real-time
monitoring.
16 | P a g e Department of Computer Engineering
7.References
1. Harel, D. (1987). Statecharts: A Visual Formalism for Complex Systems. Science of
Computer Programming, 8(3), 231-274.
This paper introduces the concept of statecharts, a visual formalism for modeling complex
systems, which is closely related to FSMs used in traffic light controllers.
2. Raj, S. & Shah, S. (2016). Design of Traffic Light Control System Using Finite State
Machine. International Journal of Computer Applications, 148(2), 38-41.
This paper explores the design and implementation of traffic light control systems using FSMs,
highlighting the efficiency and simplicity of FSM in managing traffic signal transitions.
3. Lee, E. A. & Seshia, S. A. (2011). Introduction to Embedded Systems: A Cyber-Physical
Systems Approach. MIT Press.
This textbook provides an in-depth explanation of embedded systems design, including FSMs
used for traffic light control and other similar applications.
4. Gonzalez, C., & Mehta, S. (2018). Finite State Machine Implementation in Traffic Light
Systems. International Journal of Engineering Research and Applications, 8(6), 38-43.
This paper focuses on the implementation of FSMs in real-world traffic light systems,
demonstrating how state transitions are used to control traffic flow at intersections.
17 | P a g e Department of Computer Engineering