0% found this document useful (0 votes)
2 views

IOT 6

The document provides an overview of Real-Time Operating Systems (RTOS), focusing on the RTOS kernel's key functions, task management, and scheduling mechanisms. It explains the characteristics of RTOS tasks, including task states, priorities, and synchronization methods, as well as the differences between preemptive and non-preemptive scheduling. Additionally, it outlines the importance of task properties for ensuring predictability and efficiency in real-time applications.

Uploaded by

aliaahisham208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

IOT 6

The document provides an overview of Real-Time Operating Systems (RTOS), focusing on the RTOS kernel's key functions, task management, and scheduling mechanisms. It explains the characteristics of RTOS tasks, including task states, priorities, and synchronization methods, as well as the differences between preemptive and non-preemptive scheduling. Additionally, it outlines the importance of task properties for ensuring predictability and efficiency in real-time applications.

Uploaded by

aliaahisham208
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

IOT

RTOS II
Associated Prof. Wafaa
Shalash
Lect. 6
Class Rules
• Be in class on time,
• Listen to instructions and
explanations.
• Talk to your classmates only when
there is an activity.
• Use appropriate and professional
language.
• Keep your mobile silent.
Sensors & Protocols
Lecture Topics
• RTOS kernelKey
• Functions of the RTOS
Kernel
• What is RTOS task?
Scheduler
• The Heart of RTOS
• Preemptive vs Non-
Preemptive Scheduling
RTOS kernel

An RTOS kernel is the core part of a Real-Time Operating System


that manages the hardware resources of the system and
facilitates multitasking by managing task scheduling, memory
allocation, inter-task communication, and synchronization.
The RTOS kernel is responsible for ensuring tasks are executed
within their defined time constraints (real-time performance). It
typically provides the following functions:
Key Functions of the RTOS Kernel:
1. Task Scheduling:
1. It schedules tasks based on priorities (preemptive or non-preemptive) and time-slices, ensuring critical tasks get executed within
deadlines.
2. Inter-Task Communication (IPC):
1. The kernel supports various methods like queues, semaphores, and mailboxes to allow tasks to communicate with each other in a
synchronized way.
3. Memory Management:
1. It manages memory allocation for tasks and system resources, ensuring each task gets its required memory without causing conflicts.
4. Synchronization:
1. The kernel synchronizes tasks by providing mechanisms like mutexes and semaphores, ensuring data consistency when multiple tasks
access shared resources.
5. Interrupt Management:
1. The kernel handles hardware interrupts and ensures the system responds to events in real-time, delegating execution of critical tasks
based on interrupt priority.
6. Time Management:
1. The kernel tracks system time and manages the execution of time-sensitive tasks, ensuring they run at specific intervals or within
deadlines.
Types of RTOS Kernels:
1.Monolithic Kernel:
1. In a monolithic kernel, the entire kernel works in a single address space, offering
fast communication and system calls, but potentially less stability and security if a
bug occurs.
2.Microkernel:
1. A microkernel keeps minimal services running in the kernel and moves other
services (e.g., device drivers) into user space. It offers better stability and
modularity but may incur some overhead due to the inter-process communication
between user space and kernel space.
3.Hybrid Kernel:
1. A hybrid kernel combines aspects of both monolithic and microkernels, trying to
balance speed and modularity.
What is RTOS task?
• An RTOS task refers to a unit of work that the
RTOS schedules for execution. It is essentially a
program or a thread that is executed within the
operating system in response to a specific event
or condition. In a Real-Time Operating System
(RTOS), tasks are typically designed to perform
specific, time-sensitive functions.
Task Status
Key Characteristics of RTOS Tasks:
1.Task States:
•Tasks in an RTOS can have different states such as:
•Ready: The task is ready to be executed but waiting for CPU time.
•Running: The task is currently being executed.
•Blocked/Waiting: The task is waiting for an event (e.g., data from a sensor, or
completion of another task).
•Suspended: The task is stopped temporarily, often by the kernel or by the task
itself.
2.Task Priority:
•RTOS tasks can have priorities to determine which tasks are executed first. Higher-
priority tasks can preempt lower-priority ones.
•Tasks are scheduled based on these priorities and can be preemptive (task with the
highest priority can interrupt lower-priority tasks) or non-preemptive (tasks continue
to run until they yield the CPU).
3.Multitasking:
•RTOS tasks enable multitasking where multiple tasks are running concurrently. The
RTOS kernel manages the switching between tasks using scheduling algorithms
(such as round-robin, priority-based, etc.).
Key Characteristics of RTOS Tasks:
4.Task Creation and Management:
•RTOS tasks are typically created using specific API calls like xTaskCreate() in FreeRTOS. These tasks are
given names, priorities, stack sizes, and functions they will execute.
•Tasks may also be suspended or resumed programmatically using functions like vTaskSuspend() or
vTaskResume().
5.Synchronization and Communication:
•Tasks often need to synchronize with each other to ensure data integrity, particularly when multiple tasks
share resources. RTOS provides synchronization mechanisms like semaphores, mutexes, and message
queues to achieve this.
6.Time Constraints:
•RTOS tasks are often time-constrained to meet real-time deadlines. These constraints could involve
processing data from sensors at regular intervals, or executing a task within a certain period to maintain
system stability.
Key RTOS Task Properties

1. Task Priority
•Determines the order in which tasks are executed.
•Higher-priority tasks preempt lower-priority ones (in preemptive scheduling).
•Example: In FreeRTOS, priority ranges from 0 (lowest) to configMAX_PRIORITIES-1
(highest).
2. Task State
•A task can be in one of these states:
•Ready – Waiting to be executed (eligible for CPU time).
•Running – Currently executing on the CPU.
•Blocked/Waiting – Waiting for an event (e.g., delay, semaphore, message).
•Suspended – Manually paused (not scheduled until resumed).
Key RTOS Task Properties (cont.)

3. Task Stack Size


•Each task has its own stack memory for local variables and function calls.
•Must be carefully allocated to avoid stack overflow.
•Example: xTaskCreate(taskFunc, "Task1", 256, NULL, 2, &handle) → 256 bytes stack.
4. Task Entry Function
•The function where the task begins execution.
•Typically runs in an infinite loop (while(1)).
•Example: void vTaskFunction(void *pvParameters) {
while(1)
{ // Task code here
}
}
Key RTOS Task Properties (cont.)
• 5. Task Control Block (TCB)
• A data structure maintained by the RTOS to store task information:
• Current state.
• Priority.
• Stack pointer.
• Delays or event waits.
• 6. Task Scheduling Policy
• Preemptive Scheduling – Higher-priority tasks immediately take CPU.
• Time-Sliced (Round Robin) – Tasks of equal priority share CPU time.
• Cooperative Scheduling – Tasks yield CPU voluntarily.
Key RTOS Task Properties (cont.)
9. Task Notification & Synchronization
•Tasks can communicate via:
•Semaphores (xSemaphoreTake/Give).
•Mutexes (for resource locking).
•Message Queues (xQueueSend/Receive).
•Event Groups (xEventGroupSet/Wait).
10. Task Deletion & Cleanup
•Tasks can be dynamically deleted (vTaskDelete()).
•Some RTOS require manual cleanup (e.g., freeing memory).
Key RTOS Task Properties (cont.)
• 7. Task Parameters
• Allows passing data to a task during creation.
• Example:
xTaskCreate(taskFunc, "Task1", 128, (void*)&config, 1, NULL);
8. Task Delay & Timeouts
•Tasks can sleep (vTaskDelay()) or wait for events with timeouts.
•Example:
vTaskDelay(100); // Delay for 100 RTOS ticks
xQueueReceive(queue, &data, pdMS_TO_TICKS(200)); // Wait max 200ms
Example Task Properties in FreeRTOS
void vSensorTask(void *pvParameters) {
uint32_t sensor_id = *(uint32_t*)pvParameters;
while(1) {
// Read sensor data
vTaskDelay(pdMS_TO_TICKS(100)); // 100ms delay
}
}
void main() {
uint32_t sensor_id = 5;
xTaskCreate(
vSensorTask, // Task function
"Sensor Task", // Task name
256, // Stack size (bytes)
&sensor_id, // Task parameter
3, // Priority (higher = more urgent)
NULL // Task handle (optional)
);
vTaskStartScheduler(); // Start RTOS
}
Summary Table of RTOS Task Properties

Property Description
Priority Determines execution order (higher = runs first)
State Ready, Running, Blocked, Suspended
Stack Size Memory reserved for task execution
Entry Function The function where the task starts
TCB OS-managed metadata for task control
Scheduling Preemptive, Round Robin, or Cooperative
Parameters Input data passed at task creation
Delay/Timeout Pausing or waiting for events
Sync Mechanisms Semaphores, Mutexes, Queues, Events
Deletion Dynamically removing a task
More On Priorie
Why Are Task Properties Important?
• Predictability – Ensures real-time deadlines are met.
• Resource Management – Prevents stack overflows and deadlocks.
• Efficiency – Optimizes CPU usage and task switching.
Example of an RTOS Task (FreeRTOS):

•Task 1 has a priority of 2, while Task 2 has a


priority of 1.
•Task 1 runs every 1 second, and Task 2 runs
every 0.5 second.
•The tasks are scheduled based on their priorities
and delays using vTaskDelay(), which tells the
RTOS when to pause a task.
Let me know if you need additional
Scheduler: The Heart of RTOS

• A scheduler is a system software component or module within an


operating system (OS) responsible for determining the order in which
multiple tasks, processes, or threads are executed by the CPU.
• In Real-Time Operating Systems (RTOS), the scheduler plays a critical role in
managing tasks to ensure they meet their timing constraints.
• The scheduler implements various scheduling algorithms to decide which
task gets CPU time and for how long.
Key Functions of a Scheduler
1.Task Selection: Selects which task should run next based on the
scheduling algorithm.
2.Preemption and Context Switching: Switches between tasks if the
chosen algorithm allows preemption.
3.Time Management: Keeps track of task deadlines, execution times,
and periodic intervals.
4.Prioritization: Assigns and manages priorities to ensure high-priority
tasks receive appropriate CPU time.
5.Resource Management: Allocates and deallocates CPU resources
efficiently among tasks.
Common RTOS Scheduling Requirements
• Predictability: Ability to predict task execution times and meet
deadlines.
• Resource Utilization: Efficiently using CPU time and other resources.
• Scalability: Handle varying numbers of tasks without significant
performance degradation.
Scheduling Algorithms in RTOS
Algorithm Description Suitability

Priority is based on task period


Rate Monotonic Scheduling (RMS) Good for periodic tasks
(shorter = higher priority)

Priority is based on the earliest


Earliest Deadline First (EDF) Optimal for dynamic deadlines
deadline

Fixed Priority Scheduling Priorities are set manually Simple and predictable

Tasks of equal priority share CPU


Round Robin Used in hybrid RTOS
time
How the Scheduler Works (Core Steps)
1. Task Creation
Tasks are created and assigned priorities. Each task has:
1. Stack space
2. Program counter (PC)
3. Task Control Block (TCB)
2. Task States
Tasks move between different states:
1. Ready: Waiting to be scheduled
2. Running: Currently executing
3. Blocked: Waiting for an event (e.g., I/O, semaphore)
4. Suspended: Paused until resumed
3. Scheduling Decision
1. When an event occurs (timer tick, interrupt, task finishes), the scheduler runs.
2. It checks the ready list and selects the highest-priority task.
3. Context switching is performed if a new task is chosen.
4. Context Switching
1. Saves the state (registers, PC, stack) of the current task
2. Restores the state of the new task
3. Switches execution to the new task
RTOS Scheduler Characteristics
• Deterministic behavior: Same input → same output every time
• Low latency: Interrupt and task switching are fast
• Priority-based: Not all tasks are equal
• Real-time constraints: Tasks must meet timing deadlines
Preemptive vs Non-Preemptive Scheduling

• Scheduling in RTOS can be categorized into two types based on the


ability of the system to preempt or interrupt a task.
• In preemptive scheduling, the operating system can interrupt a task to
give way to a higher-priority task. This type of scheduling is more
suitable for real-time systems as it allows critical tasks to be executed
immediately.
• In contrast, non-preemptive scheduling does not allow tasks to be
interrupted once they have started executing.
• This can lead to delays in the execution of high-priority tasks and is generally
not suitable for real-time systems.
• However, it can be used in systems where task execution time is predictable
and short.
Preemptive vs Non-Preemptive Scheduling
Preemptive Scheduling
• Task Switching Triggered by Priority:
• The RTOS continuously monitors tasks.
• If a higher-priority task becomes ready (e.g., due to an interrupt), it preempts
(interrupts) the currently running lower-priority task.
• Responsive to Real-Time Events:
• Ideal for systems where some tasks must respond immediately (e.g., handling
sensor input).
• Example in the diagram:
• Task B starts running, but is interrupted when Task A (higher priority) becomes
ready. Task A preempts B.
Non-Preemptive Scheduling (Right Side)
• Task Switching Only When Task Voluntarily Yields or Completes:
• Even if a higher-priority task becomes ready, it must wait until the current task
finishes.
• Simpler and Safer for Shared Resources:
• No unexpected task switches, easier debugging.
• Less responsive:
• May delay important tasks if a long-running task doesn’t yield.
• Example in the diagram:
• Task B continues running until it finishes, even though Task A becomes ready.
Feature Preemptive Non-Preemptive

Task interruption Yes, by higher priority No, runs to completion

Responsiveness High Low

Needs careful
Resource handling Safer and simpler
management

Complexity More complex Easier to implement


FreeRTOS Scheduler
• In your FreeRTOS example, the scheduler type being used is the preemptive
priority-based scheduler, which is the default scheduler in FreeRTOS (unless
configured otherwise in FreeRTOSConfig.h).
Scheduler Type: Preemptive Priority-Based
Features:
•Preemptive: The highest priority task that is ready to run will always execute.
•Priority-based: Tasks are scheduled based on their assigned priority
(osPriorityHigh, osPriorityNormal, etc.).
•Context switching happens automatically when:
•A higher priority task becomes ready.
•A task blocks (e.g., waits for delay or I/O).
Example
const osThreadAttr_t tempTaskAttr = {
.name = "TempTask",
.priority = osPriorityHigh};
const osThreadAttr_t uartTaskAttr = {
.name = "UARTTask",
.priority = osPriorityNormal};

osPriorityAboveNormal osPriorityAboveHigh
1. Preemptive Scheduling Example (Default in FreeRTOS)

Configuration:
#define configUSE_PREEMPTION 1 // Enables preemptive scheduling

Behavior:
•Task B starts running.
•When Task A becomes ready, it preempts
Task B.
•Task A runs first every time it's ready.
2. Non-Preemptive Scheduling Example
• Configuration:
#define configUSE_PREEMPTION 0 // Disables preemptive scheduling

Behavior:
Tasks only switch when they call vTaskDelay or
yield.
Even if Task A is higher priority, it must wait for
Task B to yield.
Task switching is cooperative.
Summary:

Behavior Preemptive Non-Preemptive

RTOS preempts based on


Task Switch Trigger Tasks voluntarily yield
priority

Responsiveness High (good for real-time) Low (task must give up CPU)

Simpler systems, UI apps,


Use Case Sensor input, real-time control
teaching
Comparison
Feature Preemptive Non-Preemptive (Cooperative)
Automatically by the RTOS based Manually by the task (e.g.,
Task switch trigger
on priority delay/yield)
Control over CPU RTOS has full control Tasks control when to yield
Feature Preemptive Non-Preemptive (Cooperative)
Response to high-priority tasks Immediate Delayed until current task yields
May suffer under long-running
Real-time performance Better, more deterministic
tasks
Feature Preemptive Non-Preemptive (Cooperative)
Higher (low-priority tasks can be Lower (all tasks must yield for
Risk of task starvation
preempted often) others to run)
Less fair unless priority inversion is More fair if tasks yield
Fairness
managed appropriately
Comparison
Feature Preemptive Non-Preemptive (Cooperative)
Scheduler complexity Higher Lower
More complex due to context Easier to trace, more predictable
Debugging difficulty
switching anytime flow

Scenario Preemptive Non-Preemptive (Cooperative)


Real-time systems with strict
Ideal for Simple systems, limited resources
deadlines
Small embedded systems, simple
Example Industrial automation, robotics
appliances
NEXT TIME

You might also like