You are on page 1of 19

VIETNAM NATIONAL UNIVERSITY, HO CHI MINH CITY

UNIVERSITY OF TECHNOLOGY
FACULTY OF COMPUTER SCIENCE AND ENGINEERING

Microprocessor - Microcontroller [CO3091]

ASSIGNMENT REPORT

Traffic Light using STM32F103RB

Instructor: Le Trong Nhan


Students: Nguyen Vu Khanh - 2153444
Hoang Tien Duc - 2152520
Nguyen Duc Bao Huy - 2152089

HO CHI MINH CITY, DEC 2023


Contents
1 Introduction 2

2 Configuration 2
2.1 Pinout Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Clock Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Button Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 UART Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5 Buzzer Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Finite State Machine 7


3.1 Automatic Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Manual Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Pedestrian Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Buzzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

4 UART Communication 11

5 Scheduler 13
5.1 Scheduler overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5.2 Deep dive in to each operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

6 Source code 17

7 Conclusion 17

1
Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Members list & Workload

Student Percentage
No. Full name Contribution
ID of work

Design FSM structure & button, imple-


1 Hoang Tien Duc 2152520 100%
ment Buzzer, test on STM32F103RBTx
Design, implement pedestrian FSM &
2 Nguyen Duc Bao Huy 2152089 100%
Scheduler, test on STM32F103RBTx
Design, implement UART Communica-
3 Nguyen Vu Khanh 2153444 100%
tion, test on STM32F103C6

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 1/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

1 Introduction
In the realm of contemporary urban infrastructure, the effective management of vehicular and pedestrian
traffic at intersections is of paramount importance. This report delves into the intricacies of a meticulously
designed 4-way traffic light system, driven by a microcontroller. As urban landscapes evolve, the demand for
intelligent traffic control solutions becomes increasingly critical.

The system’s architecture is multifaceted, encompassing a Finite State Machine (FSM), UART commu-
nication capabilities, and a cooperative scheduler. These components collectively contribute to the system’s
ability to adapt dynamically to varying traffic scenarios, ensuring optimal efficiency and safety. The report
provides an in-depth exploration of each module, offering a comprehensive understanding of the system’s design
philosophy and operational intricacies.

Navigating through three primary modes - Automatic, Manual, and Pedestrian - the system presents
a holistic approach to traffic control. The Automatic Mode seamlessly manages traffic light patterns,
responding to changing conditions at the intersection. In Manual Mode, users are empowered to make real-time
adjustments, introducing a flexible and user-friendly dimension to the system. Pedestrian Mode incorporates a
safety-centric feature, synchronizing pedestrian crossings with vehicular traffic to enhance overall intersection
safety.

The integration of UART communication facilitates insightful console outputs, providing users and
operators with a comprehensive view of the system’s state and operation. The cooperative scheduler serves as
the backbone, efficiently managing tasks with precision timing, enabling the seamless execution of functions
critical to the system’s operation.

This report meticulously details the functionalities, design rationale, and operational intricacies of each
module within the microcontroller-based 4-way traffic light system. With a focus on promoting efficiency,
safety, and adaptability, the system presented herein contributes to the discourse on intelligent urban traffic
management systems. The subsequent sections delve into the Finite State Machine, UART Communication,
Pedestrian Mode, and the intricacies of the cooperative scheduler, providing a comprehensive overview of the
system’s capabilities and design considerations.

2 Configuration
2.1 Pinout Configuration
Based on the assignment requirement, we have specified the configuration of various buttons and ports in
the traffic light control system on STM32F103RBTx board.
• Button 1, linked to port PA1, facilitates the transition between AUTOMATIC MODE and MANUAL
MODE in the traffic light system. This toggle functionality allows users to easily switch between the two
modes.
• Button 2 is set to PA4 port, which is used to extend the duration of the traffic light in MANUAL MODE.
• Button 3, connected to PB0, is employed to confirm the adjusted time duration of the traffic light and
swiftly transition the system to AUTOMATIC mode.
• The Pedestrian Button, connected to pin PA0, is used for toggling pedestrian modes, which will be
described later.
• In terms of UART Communication, the transmission (TX) and reception (RX) functions are assigned to
PA2 and PA3, respectively.
• The display of the horizontal lights, representing RED, AMBER, and GREEN signals, is controlled
through ports PA10 and PB3. Meanwhile, the vertical lights are adjusted using ports PB5 and PB4
based on specific input conditions.
• For pedestrian light control, ports PB10 and PA8 are designated to manage the operation of the pedestrian
signals.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 2/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Figure 1: Pinout Configuration of STM32F103RBTx.

In addition, we have created a project specifically for the STM32F103C6 to simulate each phase on Proteus,
allowing us to verify the correctness of the code before deploying it onto the STM32F103RBTx board. This
simulation allows us to make necessary adjustments, specifically focusing on displaying the traffic light, and
verify that the code operates correctly in a controlled environment.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 3/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Figure 2: Pinout Configuration of STM32F103C6.

Figure 3: Proteus Simulation.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 4/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

2.2 Clock Configuration


Within this project, we have implemented timer interrupts as a crucial component. Timer interrupts are
employed to enhance precision and efficiency in managing time-sensitive tasks. By utilizing timer interrupts,
we can ensure that specific actions occur at precise intervals, optimizing the synchronization of tasks and
enhancing the overall reliability and accuracy of our system.

To establish a timer interrupt, the frequency of executing this function can be determined using a following
equation:
F
f=
(1 + Pre)(1 + Counter)
Since the requirement is internal clock source is set to 64MHz, and the target is to set an timer interrupt
to 10ms, we have defined as follow:
• By setting the P rescaller to 7999, and the Counter to 79, the input clock source to timer will be
64MHz/(7999 + 79) = 1000Hz.
• The interrupt is raised when the timer counter is counted from 0 to 79, meaning that the frequency is
divided by 80, which is 100Hz.
• The frequency of the timer interrupt is 100Hz, meaning that the period is 1/100Hz = 10ms.

Figure 4: Clock source setting for the system.

Figure 5: Prescaler and Counter Period setting.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 5/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

2.3 Button Configuration


As outlined earlier, Button 0, Button 1, Button 2 and Pedestrian Button are connected to pin PA1, PA4,
PB0, PA0 respectively. These pins are configured as GPIO inputs with pull-up mode to facilitate signal detec-
tion.

Figure 6: Setting of button for pedestrians.

2.4 UART Configuration

Figure 7: UART Configuration.

To address the absence of a 7-segment LED display on the testing board for presenting the current time
length of the traffic light, a pragmatic solution has been implemented using UART communication. This
facilitates the transmission of pertinent information to the virtual terminal, allowing real-time display of the
traffic light status in automatic mode, showcasing adjustments in manual mode, confirming new time lengths,
and other relevant system updates. The UART configuration parameters are meticulously set as follows:

• USART2 is selected for UART channel 2 within the Connectivity settings of the .ioc file.
• The UART channel operates in Asynchronous mode, maintaining a baud rate of 9600 bits per second,
and is configured with no parity and a single stop bit. Subsequent to this UART configuration, the

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 6/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

communication pins PA2 (Tx) and PA3 (Rx) are activated, establishing a seamless channel for information
exchange between the system and the virtual terminal.

2.5 Buzzer Configuration


A buzzer serves as a straightforward device for generating buzzing or beeping sounds through the application
of electrical current. This electromechanical component is designed to produce audible signals when activated.
To regulate the sound output, we employ Pulse Width Modulation (PWM), a technique allowing us to adjust
the intensity or frequency of the buzzer’s sound. PWM, a widely used method in electronics, operates by modi-
fying the duty cycle of a periodic waveform. This versatile modulation approach is commonly utilized in various
applications, such as controlling motor speed, adjusting LED brightness, and managing audio amplifier outputs.

To use the buzzer, P rescaler and Counter are both set to 79, and Channel1 is set to PWM Generation
CH1:
• The clock source is 64MHz, by setting the prescaller to 7999, the input clock source to the timer is
64MHz/(79+1) = 800000Hz
• The interrupt is raised when the timer counter is counted from 0 to 79, meaning that the frequency is
divided by 80, which is 10000Hz.
• The frequency of the timer interrupt is 10000Hz, meaning that the period is 1/10000Hz = 10us.

Figure 8: Buzzer timer setting.

3 Finite State Machine


3.1 Automatic Mode
Requirement: The system operates as normal. The light colors are RED, AMBER, and GREEN.

The system for automatic mode operates as follows:

1. In the realm of automated functionality, our system seamlessly navigates the intricacies of conventional
conditions, orchestrating the dance of RED, AMBER, and GREEN hues that typify the nuanced states of
traffic signals. Presently, our undertaking delves into the deployment of a highly sophisticated traffic light
system tailored for an intersection, a complex juncture where crossroad traffic converges. Our primary
ambition is to refine the orchestration of state transitions within the sophisticated state machine governing
this intricate traffic control system.
2. In pursuit of synchronization, a nuanced approach is adopted wherein two distinct states from divergent
roads are conjoined into a harmonized state. To illustrate, when the traffic light on road 1 displays
GREEN or AMBER, the corresponding signal on road 2 is set to RED. Conversely, should the traffic
light on road 1 be RED, the signal on road 2 transitions to either AMBER or GREEN, embodying a
reciprocal and orchestrated pattern to optimize the flow of traffic at the intersection.
3. By default, from INIT, the system will be set to the RED_GREEN state.
4. In conclusion, there will be 5 states to be concerned:

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 7/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

• INIT

• RED_GREEN

• RED_AMBER

• GREEN_RED

• AMBER_RED

Figure 9: Automatic FSM.

3.2 Manual Mode


Requirement: A button is used to switch the light colors in this mode.

1. Transition to manual mode: When Button 1 is pressed in automatic mode, the system transitions to
manual mode. Upon entering manual mode, the default state is set to MAN_RED.
2. Blinking Lights in manual mode: In manual mode, the lights corresponding to the current state
blink at intervals of 0.5 seconds. For example, if the system is in MAN_RED state, the RED light blinks
every 0.5 seconds.
3. State Transition and Timeout in manual mode:Continuous pressing of Button 1 in manual mode
cycles through states MAN_AMBER, MAN_GREEN, and eventually returns to automatic mode. To
ensure a seamless user experience, if no button is pressed within 5 seconds during manual mode, the
system autonomously reverts to automatic mode.
4. Incrementing Timer: Button 2 is designed to increment the current time, simulating a manual ad-
vancement of the timer. Each press of Button 2 increases the time period for the relative light by 1
second, with the timer counter resetting to 0 when it reaches 99.
5. Confirmation and Return to automatic mode: Pressing Button 3 confirms the latest time length
displayed on the virtual terminal. The system immediately switches to automatic mode, and the traffic
light continues its regular operation based on the new settings.
6. In conclusion, there will be 5 states to be concerned:
• AUTOMATIC
• MANUAL
• MAN_RED
• MAN_AMBER
• MAN_GREEN

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 8/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Figure 10: Manual FSM.

3.3 Pedestrian Mode


Requirement: Pedestrian scramble when the button for pedestrian is pressed, its light is turned on and
operates reversely to the light of vehicles. The system for pedestrian mode operates as follows:

Figure 11: Pedestrian FSM.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 9/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

1. When the pedestrian button is pressed, the pedestrian lights will exhibit the opposing color to the traffic
lights on the road awaiting crossing. For instance, if the traffic lights signal GREEN or AMBER, the
pedestrian lights will indicate RED.
2. Upon the traffic lights on the road displaying RED, the pedestrian lights will shift to GREEN. As the
designated time for crossing nears its conclusion, a buzzer will progressively heighten in both volume and
speed, serving as a warning to pedestrians that the signal is on the verge of changing.
3. After that, when the traffic lights on the road displays GREEN again, the pedestrian light goes to sleep
mode and waits for next pedestrian pressed button.
4. In conclusion, there will be 4 states to be concerned (notes: G(GREEN), R(RED), A(AMBER)):
• INIT

• P_RED(Pedestrian RED)

• P_GREEN(Pedestrian GREEN)

• P_OFF(Pedestrian OFF))

3.4 Buzzer
Requirement: When the green light for pedestrian is going to switch to red, a buzzer is used to alert
pedestrians with a progressive loud and frequency-increasing.

1. By default, when the system initializes, the Pedestrian Button is in an unpressed state. Consequently,
the state of the buzzer remains in the OFF mode. This default configuration creates a harmonious urban
environment until pedestrian interaction is detected.
2. An instantaneous response is triggered when the Pedestrian Button is pressed while the pedestrian light
is in the green phase. In this scenario, the state of the buzzer immediately transitions to the ON mode.
This proactive approach aims to prepare and alert pedestrians to proceed swiftly and safely, aligning with
the ongoing traffic light signals.
3. The functional intricacy of the system is further exemplified when the traffic status progresses from green
to RED_AMBER. At this critical juncture, the buzzer commences its notification sequence, emitting
a progressively loud and frequency-increasing alert. This auditory cue persists until the traffic status
transitions back to GREEN_RED, indicating a safe pedestrian crossing period.
4. In conclusion, there will be 2 states to be concerned:
• OFF
• ON

Figure 12: Buzzer FSM.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 10/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

4 UART Communication
Requirement: One of the primary objective of the microcontroller project is to implement a 4-way traffic
light system with UART communication capabilities. The UART communication will be utilized to print
relevant information to the console, providing insights into the system’s operation. The specific system for
UART communication is operated as follows:

1. Automatic Mode: The system initiates in Automatic Mode, where predefined traffic light patterns
control the sequence of lights. UART communication plays a crucial role in periodically printing the
current state of the traffic lights. The console output details the countdown during each phase, allowing
users to monitor the progression of the traffic light cycle.

Figure 13: Automatic Mode.

2. Transition to Manual Mode: Upon pressing Button 1, the system seamlessly transitions to Manual
Mode. This button press acts as a trigger, enabling the user to take control of the traffic light timings
and make manual adjustments.

Figure 14: Mode Transition.

3. Manual Mode: Once in Manual Mode, users can modify three critical parameters: RED, AMBER, and
GREEN counters. The console displays the current mode, indicating whether the system is in Modifying
RED, AMBER, or GREEN mode. This provides users with clear feedback about which parameter they
are currently adjusting.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 11/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Figure 15: Manual Mode.

4. Counter Updates in Manual Mode: Buttons 2 and 3 play a pivotal role in Manual Mode. Button
2 is designed to increment the current time, simulating a manual advancement of the timer. Pressing
Button 3 not only updates the current time but also displays the updated time on the console. These
buttons facilitate precise adjustments to the traffic light timings, allowing users to fine-tune the operation
of the system according to specific requirements.

Figure 16: Manual Mode Operations.

5. Manual Mode Termination: To ensure a smooth user experience, if no button is pressed within a
fixed time (e.g., 5 seconds) during Manual Mode, the system autonomously reverts to Automatic Mode.
This feature prevents unintentional manual overrides from disrupting the system’s regular operation.

Figure 17: Timeout.

6. Pedestrian Mode: In this mode, when the pedestrian button is pressed, the pedestrian lights undergo
a transition to the opposite color of the current traffic light on the road awaiting crossing. For instance,
if the traffic lights signal GREEN or AMBER, the pedestrian lights will indicate RED, signifying to
pedestrians that it is not safe to cross. Upon the traffic lights on the road displaying RED, the pedestrian
lights shift to GREEN, allowing pedestrians to safely cross the intersection.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 12/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

Figure 18: Pedestrian Mode.

After the vehicular traffic lights display GREEN again, the pedestrian lights enter sleep mode and await
the next pedestrian button press.

Figure 19: Sleep mode.

5 Scheduler
5.1 Scheduler overview
1. Operation: Tasks within this framework are meticulously scheduled to execute at specific times,
adhering to either a periodic or one-shot cadence. When a task is designated to run, it seamlessly
integrates into the waiting list. Subsequently, in moments of CPU idleness, the scheduler orchestrates
the execution of the next awaiting task, if any. The task operates to completion before gracefully
relinquishing control back to the scheduler.

2. Implementation Insight: Implementing this cooperative scheduler is an endeavor marked by simplic-


ity, requiring only a modest amount of code. The scheduler’s memory allocation is tailored to handle a
singular task at any given time. Composed predominantly in a high-level language like ’C,’ the scheduler
becomes an integral part of the developer’s code, eschewing the distinction of a standalone application.

3. Performance Metrics: Efficiency in responding swiftly to external stimuli necessitates meticulous at-
tention during the design phase. The cooperative scheduling paradigm excels in simplicity, predictability,
reliability, and safety.
4. The scheduler data structure:
• void (*pTask) (void): pointer to task (must be a void function)

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 13/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

• uint32_t Delay: Delay(ticks) until the function will be run

• uint32_t Period: Interval (ticks) between subsequent runs

• uint8_t RunMe: Incremented (by scheduler) when task is due to execute

• uint32_t TaskID: identification of each assigned task

• sTask* TasksCircularLinkedList: stores all assigned task in circular linked list (support O(1) in
update operation)
5. The scheduler operations:
• void (*pTask) (void): pointer to task (must be a void function)

• uint32_t Delay: Delay(ticks) until the function will be run

• uint32_t Period: Interval (ticks) between subsequent runs

• uint8_t RunMe: Incremented (by scheduler) when task is due to execute

• uint32_t TaskID: identification of each assigned task

• sTask* TasksCircularLinkedList: stores all assigned task in circular linked list (support O(1) in
update operation)
• uint8_t task_position[SCH_MAX_TASKS]: keep tracks of task position after adding
• SCH_MAX_TASKS: define max task (by default: we set it to maximum of 40 tasks)
• LOCK, UNLOCK: we use mutex_lock to ensure synchronization in the scheduler

Figure 20: Circular linked list of tasks.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 14/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

6. All related operations:


• UpdateTaskPosition: update tasks to correct position after adding/ dispatching tasks

• SCH_Add_Task: adding task to scheduler

• SCH_Update: update tasks status, which is called in timer interupt, so it needs to have complexity
of O(1)

• SCH_Dispatch_Tasks: dispatch task to be executed in appropriate time, which is called directly


in while loop

• SCH_Delete_Task: delete a specific task from scheduler (mainly used in one-shot task)

5.2 Deep dive in to each operation


1. Update_position_task (UpdateTaskPosition)
• Loop for Finding Position: The function enters a loop that iterates through the linked list until it
finds the correct position for the updateTask based on its delay.check is used to ensure that the
loop doesn’t run indefinitely, breaking out if the head of the list is encountered more than once.

• Adjusting Delay: Inside the loop, the delay of updateTask is adjusted based on the delay of the
current task (it).The loop moves to the next task in the linked list.

• Insertion at Appropriate Position: After finding the correct position, updateTask is inserted into
the linked list .The RunMe flag is set to 1 if the adjusted delay is less than or equal to zero,
indicating that the task is ready to run.

• Update Section: The function now enters a section to update the linked list and the delay of the
tasks accordingly(The task is updated to the lowest position or middle or highest in the list).

• In conclusion, the UpdateTaskPosition function plays a crucial role in maintaining the proper
ordering of tasks in the linked list based on their delays. It adjusts the delays of tasks and inserts
the updateTask at the appropriate position. The function ensures that the linked list is updated
correctly, and tasks are marked for execution when their delays expire. This is a fundamental part
of the cooperative scheduling mechanism, facilitating the orderly execution of tasks in the system.

2. Add task (SCH_Add_Task)


• Task ID Allocation: The function enters a loop to find the first available task position in the
task_position array, where each position corresponds to a unique task ID.If a valid task position is
found, the corresponding entry in the task_position array is set to 1, indicating that the task ID is
now occupied.

• Task Initialization: The task attributes are initialized with the provided parameters (Delay, Period,
func, taskID, RunMe)

• Linked List Update: If TasksLinkedList is not null, meaning that there are existing tasks in the
linked list, the UpdateTaskPosition function is called to place the new task in the appropriate
position based on its delay.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 15/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

• In conclustion, The SCH_Add_Task function dynamically allocates memory for a new task,
assigns it a unique task ID, initializes its attributes, and places it in the linked list in a position
based on its delay. The function ensures thread safety by acquiring and releasing a lock around the
critical section of code. The addition of a new task is contingent on the availability of task IDs and
the validity of the provided function pointer.

3. Update scheduler with complexity of 0(1) (SCH_Update)


• RunMe and Lock Checks: The condition checks that the RunMe flag of the first task in the
linked list is not set (!TasksLinkedList->RunMe), and the lock is in an unlocked state (lock ==
UNLOCK). This check ensures that the task is not already marked for execution and that the
scheduler is not currently locked, allowing for safe execution

• Delay Update: If the above conditions are met, the function proceeds to update the delay of the
first task in the linked list (TasksLinkedList).The delay is decremented by 1, representing the
passage of time. This step simulates the countdown of the delay towards zero.

• RunMe Flag Setting: Following the delay update, there is another conditional check to see if the
updated delay is now less than or equal to zero (TasksLinkedList->Delay <= 0). If this condition
is true, it means that the delay has expired, and the task is ready to run. Consequently, the RunMe
flag of the task is set to 1.

• The SCH_Update function is a critical component of the cooperative scheduling mechanism. It


primarily focuses on managing the delay of the first task in the linked list and determining whether
it’s time to mark the task for execution by setting the RunMe flag. The function ensures that these
operations occur safely by checking for the validity of the linked list, the state of the RunMe flag,
and the lock status. This function is typically called at regular intervals to simulate the passage of
time and update the status of tasks in the scheduling system.

4. Scheduler dispatch task at specific time (SCH_Dispatch_Tasks)


• Task Dispatch Loop: The function enters a while loop that continues as long as there are tasks in the
linked list (TasksLinkedList) and the first task is marked for execution (TasksLinkedList->RunMe
is true).This loop is responsible for dispatching tasks that are ready to run.

• Execute Task: Inside the loop, the function executes the function associated with the first task
in the linked list using (*TasksLinkedList->funcPointer)(). This is where the actual task logic is
executed.

• One-Shot Task Handling: fter executing the task, there is a check to determine whether the task
is a one-shot task (TasksLinkedList->Period == 0).If it is a one-shot task, the task is marked
for deletion (toDelete) from the linked list. The linked list is then updated to point to the
next task in line (TasksLinkedList = TasksLinkedList->right), and the task is deleted using the
SCH_Delete_Task function.. If this condition is true, it means that the delay has expired, and the
task is ready to run. Consequently, the RunMe flag of the task is set to 1.

• Periodic Task Handling: If the task is periodic, the linked list is updated to skip the current task.
The relevant pointers are adjusted to remove the current task from the linked list (TasksLinkedList-
>right->left and TasksLinkedList->left->right).The linked list pointer is then moved to the next
task (TasksLinkedList = TasksLinkedList->right).The RunMe flag of the dispatched task is reset
to 0, indicating that it has been executed.The delay of the task is set to its period (toFind->Delay
= toFind->Period), and the task is then inserted back into the linked list in the correct position
using the UpdateTaskPosition function.

• The SCH_Dispatch_Tasks function is a core part of the scheduler responsible for executing
tasks that are ready to run. It distinguishes between one-shot and periodic tasks, handles their

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 16/17


Ho Chi Minh University of Technology
Faculty of Computer Science and Engineering

execution, and updates the linked list accordingly. The lock mechanism ensures that these opera-
tions occur atomically, preventing race conditions in a multitasking environment. The function is
typically called at regular intervals to process and dispatch tasks in a cooperative scheduling system.

5. Scheduler deletes task (rarely called) (SCH_Delete_Task)


• Task Position Check: he function begins by checking if the task at the specified index (index) is
currently present in the scheduler. This check is performed using the task_position array.If the
task is indeed present (task_position[index] is true), the function proceeds with the deletion.

• Task Position Reset: The task_position[index] is set to 0, indicating that the task position is now
available for reuse. This update ensures that the scheduler can allocate this position for a new task
in the future.

• Adjusting Pointers: Once the task to be deleted is found, the function adjusts the pointers of the
neighboring tasks to bypass the task to be deleted. it->right->left is set to it->left, and it->left-
>right is set to it->right. This effectively removes the task from the linked list.
• Freeing Memory: The memory allocated for the task to be deleted is freed using the free func-
tion. This step is crucial to prevent memory leaks and release the resources associated with the task.

• The SCH_Delete_Task function is responsible for removing a task from the scheduler based on its
index. It involves updating the task position array, traversing the linked list to find the specified
task, adjusting the pointers of neighboring tasks to skip the task to be deleted, and freeing the
allocated memory for that task. This function is crucial for maintaining the integrity of the
scheduler by efficiently managing the addition and removal of tasks during runtime.

6 Source code
The source code for the assignment can be accessed via the following link: MCU Assignment.

7 Conclusion
In culmination, our comprehensive project seamlessly integrates timer interrupts, button controls, UART
communication, and a scheduler to meet all specified requirements. Successfully realizing automatic, manual,
and tuning modes, along with a pedestrian scramble feature, the system provides a versatile traffic management
solution. With user-friendly button controls facilitating mode transitions and UART ensuring efficient commu-
nication, our project achieves a harmonious synergy of diverse functionalities for a robust and adaptable traffic
light system.

Microprocessor & Microcontroller - Academic year 2023 - 2024 Page 17/17

You might also like