SlideShare une entreprise Scribd logo
1  sur  133
Télécharger pour lire hors ligne
Mastering RTOS: Hands on FreeRTOS
and STM32Fx with Debugging
Learn Running/Porting FreeRTOS Real Time Operating System on
STM32F4x and ARM cortex M based Mircocontrollers
Created by :
FastBit Embedded Brain Academy
Visit www.fastbitlab.com
for all online video courses on MCU programming, RTOS and
embedded Linux
PART-3
FastBit Embedded Brain Academy is an online training wing of Bharati Software.
We leverage the power of the internet to bring online courses at your fingertip in the domain of embedded
systems and programming, microcontrollers, real-time operating systems, firmware development,
Embedded Linux.
All our online video courses are hosted in Udemy E-learning platform which enables you to
exercise 30 days no questions asked money back guarantee.
For more information please visit : www.fastbitlab.com
Email : contact@fastbitlab.com
About FastBitEBA
Queues and its features
So ,what are queues ?
Item-4 Item-3 Item-2 Item-1
Item-5
Tail head Item-0
Enqueue
dequeue
So ,what are queues ?
Tail
Head
Append
(enqueue)
Queue
Task A Task B
15
Queue
Task A Task B
Whena Queueis createdit does not containanythingso it is empty
TaskA writes a valuein to thequeue. Thevalueis sentto the front Sincethequeuewas
previouslyempty,the valueis nowboththefirst andthelast valuein thequeue:
12 15
Queue
Task A Task B
12 15
Queue
Task A Task B
TaskA sends another value. Thequeuenowcontains thepreviouslywrittenvalueandthis newly
addedvalue.The previous value remains at the front of the queue while the new one is now at its
back.Threespaces are stillavailable
TaskB reads a valuein thequeue.It willreceivethevalue whichis in thefront of thequeue
12
Queue
Task A Task B
Task B has removedan item.Theseconditemis movedto be theoneinthefrontof thequeue.
Thisis the valuetask 2 will readnext timeit tries to reada value. Fourspaces are nowavailable:
Main Uses of Queues in RTOS
1. Synchronization between Tasks or Interrupts
2. Inter-task communication
Queues in Synchronization and inter-Task
communication
Blocked while
accessing the
empty Queue
I needsomedatatoconsume
But waitingforTASKA to producesome
datain thequeue
Task A Task B
Data Producer
Empty
Queue
Data Consumer
Queues in Synchronization and inter-Task
communication
I m
unblocked
Looks like
Data
available in
the queue
Task A Task B
Queue
Data Produced
Unblocks Task B
Data Producer Data Consumer
Creating a Queue
FreeRTOS API to Create a Queue
xQueueHandle xQueueCreate( unsigned portBASE_TYPE uxQueueLength,
unsigned portBASE_TYPE uxItemSize );
RAM
Low High
Heap (configTOTAL_HEAP_SIZE)
Task -1
TCB
Stack
TCB1
STACK-1
Task -2
TCB
Stack
TCB-2
STACK-2
SCB
Semaphore
SCB
Queue
QCB
Item list
QCB
ITEMLIST
This RAM space is used for
Global data, arrays, static variables,
etc
Dynamically Created kernel objects
xTaskCreate() xTaskCreate() xSemaphoreCreateBinary()xQueueCreate()
Sending data to the
Queue
Sending data to the queue
xQueueSendToFront()
xQueueSendToBack()
xQueueSendToFront()
portBASE_TYPE xQueueSendToFront( xQueueHandle xQueue,
const void * pvItemToQueue,
portTickType xTicksToWait );
xQueueSendToBack()
portBASE_TYPE xQueueSendToBack( xQueueHandle xQueue,
const void * pvItemToQueue,
portTickType xTicksToWait );
Receiving data from the
Queue
Receiving data from the Queue
xQueueReceive()
xQueuePeek()
xQueueReceive()
portBASE_TYPE xQueueReceive(xQueueHandle xQueue,
const void * pvBuffer,
portTickType xTicksToWait );
xQueuePeek()
portBASE_TYPE xQueuePeek(xQueueHandle xQueue,
const void * pvBuffer,
portTickType xTicksToWait );
Exercise
Design a FreeRTOS application which implements the below commands
LED_ON,
LED_OFF,
LED_TOGGLE_START
LED_TOGGLE_STOP
LED_STATUS_READ
RTC_DATETIME_READ
The command should be sent to the board via UART from the user.
Command Format
struct APP_CMD
{
uint8_t COMMAND_NUM;
uint8_t COMMAND_ARGS[10];
};
/* Lets use this data
structure to store
command number and
its associated
arguments. */
Software Timers
Use case
Toggle the led for very 500ms .
led_toggle();
Hardware Vs Software Timers
Hardware timers Software timers
Handled by the TIMER peripheral of the MCU Handled by FreeRTOS kernel Code
No FreeRTOS APIs . You have to create your
own Function to manage the timer
peripherals
FreeRTOS APIs are availabe
Micros/nano seconds resolutions are
possible
Resolution Depends on the
RTOS_TICK_RATE_HZ
Software Timers APIs
https://www.freertos.org/FreeRTOS-Software-
Timer-API-Functions.html
PT PT PT
ISR execution (an event) will be caught by counting semaphore
HT
HT HT
Events will be processed by handler Task
Synchronization and Mutual
Exclusion in real world
A semaphore is a kernel object or you can say kernel
service, that one or more threads of execution can
acquire or release for the purpose of synchronization or
mutual exclusion.
Synchronization in real world
Synchronization in Computing
Manager Employee
Meeting @ 11 o Clock Tomorrow
Both are synchronized withthe time, hencethe One-on-One meeting runningas
expected
Manager Employee
Meeting Tomorrow
Wasting your time arriving sooner
You are not yet arrived for the meeting
Task-A
producer
Task-B
Consumer
t1 Task A runs first and it is waiting for data from
Device driver
t2 Task B runs that means Task A is pre-empted
t3 Task A runs again and finds the device driver
not yet given any data.
t4 no data is available so it again doesn't take any action
Task A and TaskB are not synchronizedfor the
productionand consumptionof data
Task-A
producer
Task-B
Consumer
t1 Task A runs first and it is waiting for data from
Device driver
t2 Task B runs that means Task A is pre-empted
t3 Task A runs again and finds the device driver
not yet given any data.
t4 no data is available so it again doesn't take any action
Kernel Objects which can be used for
Synchronization
Events (or Event Flags)
Semaphores ( Counting and binary )
Queues and MessageQueues
Pipes
Mailboxes
Signals (UNIXlike signals)
Mutex
FreeRTOS Supports
Semaphores, Queues and
Mutex
Mutual Exclusion
Shared
Entity
TASK-1
TASK-2
Task-2cannot accessthe
sharedentityunless Task-1
withdraws theownership
Global variable , data structure
Common function which use some
global data .
Peripheral memory ,etc
Concluding points
Synchronization is nothing but aligning number of Tasks to achieve a desired behaviour.
Where as mutual exclusion is avoiding a task to execute the critical section which is
already owned by another task for execution.
Typically Semaphores are used to implement the synchronization between tasks and
between tasks and interrupts.
Mutex are the best choice to implement the mutual exclusion. That is protecting access of
a shared item.
Semaphores also can be used to implement the mutual exclusion but it will introduce
some serious design issues which we will see later.
Lets see how we can use semaphores
for Synchronization
Creating a Semaphore
Creating a Semaphore
SCB
Value
(Binary or a Count)
Task-1 Task-2 Task-3
Task-Waiting-List
ThisvalueDetermines howmany
semaphoretokens are available.
Keys or tokens
Semaphore id or
name
Types of Semaphore
1 Binary semaphore
2 Counting semaphore
Creating a Semaphore
A single semaphore can be acquired a finite number of times
by the tasks depending upon the how you first initializae the
semaphore.
Different types
of semaphores
Semaphore
Semaphores are kernel objects, or you can say
kernel services which you can use to achieve the
synchronization and mutual exclusion in your
project.
Types of Semaphore
1. Binary semaphore
2. Counting semaphore
Binary Semaphore
as name indicates, this semaphore works on
only 2 values that is 1 and 0.
Binarysemaphore
SCB
Value
Task-Waiting-List
This“Value”eitherwillbe 0 or 1
Analogous toOnly 1 key
Semaphore id or
name
Taskwaitinglistwill havethe
Blocked tasks whichare waiting
forthekey
Binary semaphore use cases
1. Synchronization
That is synchronization between tasks or synchronization
between interrupts and tasks.
2. Mutual Exclusion
Binary semaphore can also be used for Mutual Exclusion, that is to
guard the critical section
Counting semaphore
SCB
Value
Task-Waiting-List
This“Value”canbe any number. If youinitializeit
to 5 forexample, thenit is analogous having5 keys.
Analogous to having
manykeys
Semaphore id or
name
Taskwaitinglistwill havethe
Blocked tasks whichare waiting
forthekeys.
Counting semaphore use cases
1. CountingEvents
In this usage scenario an event handler will 'give' a semaphore each time an event occurs
– causing the semaphores count value to be increment on each give. A handler task will
'take' a semaphore each time it processes an event – causing the semaphores count
value to be decremented on each take.
2. ResourceManagement
In this usage scenario the count value indicates the number of resources available. To
obtain control of a resource a, task must first obtain a semaphore – decrementing the
semaphores count value. When the count value reaches zero there are no free
resources. When a task finishes with the resource it 'gives' the semaphore back –
incrementing the semaphores count value.
Counting semaphore use cases
Resource Management
In this usage scenario the count value indicates the number of
resources available. To obtain control of a resource a task must first
obtain a semaphore by decrementing the semaphores count value.
When the count value reaches zero there are no free resources. When
a task finishes with the resource it 'gives' the semaphore back thus
incrementing the semaphores count value.
void interrupt_handler(void)
{
do_important_work(); /* this is very short code */
sema_give(&sem); /* Give means release the key */
} /* exit from the interrupt */
void task_function(void)
{
/* if taking a key is un-successful then this task will be blocked until key is available */
while ( sem_get(&sem ) ) // GET means, trying to take the key
{
// it will come here, only if taking a key is successful .
/* Do time consuming work of the ISR */
}
}
Counting semaphore use cases
Event/Interrupt counting &
handling
Binary Semaphore to
achieve Synchronization
between two tasks
Lets first see how binary semaphore can be
used for synchronization between 2 tasks.
The main use of binary semaphore or counting semaphore is synchronization. The
synchronization can be between tasks or between a task and an interrupt.
Binary sema to Synchronize between
Tasks
Task-1
Data
Producer
Task-2
Data
Consumer
Sema_key
Increments the key
Whendatais produced
Unblocks Task-B
If it was blockeddueto
Non-availabilityof key
voidtask1_running(void)
{
if( TRUE== produce_some_data())
{
/* This is a signallingforthetask2 towakeup if it is blockeddueto nonavailabilityof key*/
sema_give(&sema_key); // ‘GIVE’ operationwill incrementthesemaphorevalueby 1
}
}
voidtask2_running(void)
{
/* if sema_key is unavailable thentask2will be blocked.*/
/*if sema_key is available,thentask2will takeit and sema_key becomes unavailableagain
*/
while(sema_take(&sema_key) )
{
//Taskwillcomehereonlywhenthe sem_take operationis successful.
/* lets consumethe data*/
/*sincethe sem_keyvalueis zeroat this point,thenext timewhentask-2tries to
take,it willbe blocked. */
}
}
/* declaring a semaphore object */
Semaphore sem_key;
int main()
{
/* Create Task1 */
/* Create Task-2 */
/* Create a binarysemaphore*/
Sem_key = create_bin_sema();
/* schedule both the tasks */
}
Exercise
Create 2 tasks 1) Manager task 2) Employee task
With manager task being the higher priority .
When manager task runs it should create a “Ticket id” and post it to the
queue and signal the employee task to process the “Ticket id”.
When employee task runs it should read from the queue and process the
“Ticket id” posted by the manager task.
Use binary semaphore to synchronize between manger and employee task.
Binary semaphore to
achieve Synchronization
between an Interrupt &
a Task
Synchronizationbetween Interrupt& Task
The Binary semaphore is very handy and well
suited to achieve the synchronization between
an interrupt handler execution and the task
handler execution.
void interrupt_handler(void)
{
do_important_work(); /* this is very short code */
xSemaphoreGiveFromISR(&sem); /* Give means release the key */
} /* exit from the interrupt */
/* I am helper task for the interrupt ! I do time consuming work on behalf of interrupt handler*/
void helper_task(void)
{
/* if taking a key is un-successful then this task will be blocked until key is available */
while (xSemaphoreTake(&sem ) ) // GET means, trying to take the key
{
// it will come here, only if taking a key is successful .
/* Do time consuming work of the ISR */
}
}
A NA
A NA
Thesemaphoreis not
available
xSemaphoreTake()
Task
Thetaskis blockedwaiting
forthesemaphore
xSemaphoreTake()
Task
Interrupt!!!
xSemaphoreGiveFromISR()
An Interrupt occurs..that
‘gives’thesemaphore
Synchronization between an Interrupt and a Task
using Binary semaphore
1
Task is in blockedstate initially
2 Interrupt occurs
Thesemaphore is
available
A NA
A NA
Interrupt!!!
xSemaphoreGiveFromISR()
xSemaphoreTake()
Task
… whichunblocks thetask
( thesemaphoreis nowavailable)
xSemaphoreTake()
Task
Thetasknowsuccessfully‘takes’the
semaphore,so it is unavailableonce
more
3 Task Unblocked & tries to take the semaphore.
4 Task tookthe semaphore
Binary sema to Synchronize between
interrupt and task.
1.An interrupt occurred, when the task was in blocked state
2.The ISR executed and gave the semaphore ,due to that the task was
unblocked.
3.The Task executed and took the semaphore.
4.The task performed the intended work and tried to take the semaphore once
again
5.Entered the Blocked state again ,if the semaphore was not immediately
available.
Events Latching &
Processing using Counting
semaphore
A NA
A NA
Thesemaphoreis not
available
xSemaphoreTake()
Task
Thetaskis blockedwaiting
forthesemaphore
xSemaphoreTake()
Task
Interrupt!!!
xSemaphoreGiveFromISR()
An Interrupt occurs..that
‘gives’thesemaphore
Synchronization between an Interrupt and a Task
using Binary semaphore
A NA
A NA
Interrupt!!!
xSemaphoreGiveFromISR()
xSemaphoreTake()
Task
… whichunblocks thetask
( thesemaphoreis nowavailable)
xSemaphoreTake()
Task
Thetasknowsuccessfully‘takes’the
semaphore,so it is unavailableonce
more
A NA
A NA
Thesemaphoreis not
available
xSemaphoreTake()
Task
Thetaskis blockedwaiting
forthesemaphore
xSemaphoreTake()
Task
Interrupt!!!
xSemaphoreGiveFromISR()
An Interrupt occurs..that
‘gives’thesemaphore
Binary semaphore can latch at most 1 event
A NA
A NA
Interrupt!!!
xSemaphoreGiveFromISR()
xSemaphoreTake()
Task
… whichunblocks thetask
( thesemaphoreis nowavailable)
xSemaphoreTake()
Task
Thetasknowsuccessfully‘takes’the
semaphore,so it is unavailableonce
more
A NA
A NA
Interrupt!!!
xSemaphoreGiveFromISR()
Task
Thetaskis still processingthefirst
interrupt event
xSemaphoreTake()
Task
Whenprocessingof theoriginaleventcompletes thetaskcalls xSemaphoreTake()again.Because
anotherinterrupthas alreadyoccurredthesemaphoreis alreadyavailableso thetask takes the
semaphorewithout everenteringtheBlockedstate
Anotherinterrupt occurs whilethetaskis stillprocessing
thefirst event.TheISR ‘Gives’thesemaphoreagain,
effectivelylatching theeventso theevent is not lost
Concluding Points on Latching Events
1. When the interrupts/events happen relatively slow, the binary
semaphore can latch at most only one event
2. If multiple interrupts/events trigger back to back, then the
binary semaphore will not able to latch all the events. So some
events will be lost .
3. How to solve the above issue ? Welcome to the world of
“Counting Semaphore”
Counting semaphore to
latch multiple events
Thesemaphoreis not
available
xSemaphoreTake()
Task
Thetaskis blockedwaiting
forthesemaphore
xSemaphoreTake()
Task
Interrupt!!!
xSemaphoreGiveFromISR()
An Interrupt occurs..that
‘gives’thesemaphore
Counting semaphore can be used to latch multiple events
Semaphorecountis 0
Semaphorecountis 1
Interrupt!!!
xSemaphoreGiveFromISR()
xSemaphoreTake()
Task
… whichunblocks thetask
( thesemaphoreis nowavailable)
xSemaphoreTake()
Task
Thetasknowsuccessfully‘takes’the
semaphore,so it is unavailableonce
more
Semaphorecountis 1
Thesemaphoreis not
available
Semaphorecountis 0
Interrupt!!!
xSemaphoreGiveFromISR()
Task
Thetaskis still processingthefirst
interrupt event
xSemaphoreTake()
Task
Whenprocessingof thefirstevent completes,thetaskcalls xSemaphoreTake()again.Againtwo
semaphores arealready ‘available‘,oneis takenwithout thetaskeverenteringtheBlockedState,
leavingonemore‘latched’ semaphoreavailable.
Another2 interruptoccurwhilethetaskis stillprocessingthe
firstevent. TheISR ‘Gives’thesemaphoreeachtime. effectively
latchingboththeevents so neithereventis lost
Semaphorecountis 2
Semaphorecountis 1
Concluding points on Counting semaphore
You can use counting semaphore to count the events and process
them serially one by one using another task.
The counting semaphore can also be used for resource
management .That is to regulate access to multiple identical
resources
Exercise
Create 2 tasks.
1) Hander task
2) Periodic task
Periodic task priority must be higher than the handler task.
Use counting semaphore to process latched events(by handler
task) sent by fast triggering interrupts.
Use the counting semaphore to latch events from the interrupts
Mutual Exclusion using
Binary Semaphore
Access to a resource that is shared either between tasks or between tasks and
interrupts needs to be serialized using a some techniques to ensure data
consistency.
Usually a common code block which deals with global array , variable or
memory address, has the possibility to get corrupted , when many tasks or
interrupts are racing around it
Mutual Exclusion using Binary Semaphore
#define UART_DR *((unsigned long * ) (0x40000000) )
/* This is a common function which write to UART DR */
int UART_Write( uint32_t len , uint8_t *buffer)
{
for (uint32_ti=0;i < len ; i++)
{
/* if Data Register is empty write it */
while(! is_DR_empty() );
UART_DR = buffer[i];
}
}
This is Thread-Unsafe code
#define UART_DR *((unsigned long * ) (0x40000000) )
/* This is a common function which write to UART DR */
int UART_Write( uint32_t len , uint8_t *buffer)
{
for (uint32_ti=0;i < len ; i++)
{
/* if Data Register is empty write it */
while(! is_DR_empty() );
UART_DR = buffer[i];
}
}
This is Thread-Unsafe code
This codeis absolutelyfine in non-multitaskingscenario( onlyone taskexistsper
application).But in multi-taskingscenario, this functionis thread unsafe.That means,
there is a possibility of race conditionsincethe critical section codeis notprotected.
Mutual Exclusion by Binary semaphore
Mutual Exclusion by Binary semaphore
#define UART_DR *((unsigned long * ) (0x40000000) )
/* This is a common function which write to UART DR */
int UART_Write( uint32_t len , uint8_t *buffer)
{
for (uint32_t i=0;i < len ; i++)
{
/* if Data Register is empty write it */
while(! is_DR_empty() );
UART_DR = buffer[i];
}
}
2 ways we can Implement the mutual
exclusion in FreeRTOS
1. Using Binary semaphore APIs
2. Using Mutex APIs
Task-A
Task-B
bin_sema=1 ( available)
#define UART_DR *((unsigned long * ) (0x40000000) )
/* This is a common function which write to UART DR */
int UART_Write( uint32_t len , uint8_t *buffer)
{
for (uint32_t i=0;i < len ; i++)
{
sema_take_key(bin_sema );
/* if Data Register is empty write it */
while(! is_DR_empty() );
UART_DR = buffer[i]; //Critical section
sema_give_key( bin_sema );
}
}
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
Twotaskseachwant to access theresource,but a taskis not
permittedtoaccesstheresourceunlessit is thetokenholder
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
TaskA attempts totakethesemaphore,becausesemaphoreis availableTask
A successfully becomethesemaphoreholderso it is permittedtoaccess the
resource
xSemaphoreTake()
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
TaskB executes andattempts totakethesamesemaphore.TaskA stillhas the semaphore,
so theattempt fails andTaskB is not permittedto accesstheguardedresource!
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
TaskB opts toentertheblockedstateto wait forthesemaphore,allowing TaskA to run
again. TaskA finisheswiththeresourceso ‘gives’thesemaphoreback .
xSemaphoreTake()
xSemaphoreGive()
xSemaphoreTake()
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
TaskA givingthe semaphoreback causes TaskB to exittheblockedstate( thesemaphoreis nowavailable ). Task
B cannowsuccessfullyobtainthesemaphore,and havingdoneso is permittedto accesstheresource.
Task-A
Task-BA NA
Guarded
Resource
This resource is
Guarded by binary semaphore
Binary semaphore
Used to guard the resource
WhenTaskB finishes theresourceit toogives thesemaphoreback. Thesemaphoreis
nowonceagainavailable tobothtasks.
xSemaphoreTake()
xSemaphoreGive()
Advantages of Mutex over
Binary semaphore
Mutex-Intro
FreeRTOS Mutex Services
Mutex is derived from the phrase Mutual Exclusion !
Mutex is also kind of binary semaphore that include a priority inheritance
mechanism which minimizes the effect of Priority inversion .
Binary semaphores are the better choice for implementing synchronisation
(between tasks or between tasks and an interrupt), mutexes are the better
choice for implementing simple mutual exclusion
Advantages of Mutex Over Binary
semaphore.
Priority Inheritance
Mutexes and binary semaphores are very similar – the only major difference is
mutexes automatically provide a basic ‘priorityinheritance’ mechanism.
Priority inheritance is a technique by which mutex minimizes the negative effects
of priority inversion . Mutex can not able to fix the priority inversion problem
completely but it surely lessens its impact.
Advantages of Mutex Over Binary
semaphore.
Priority Inheritance
Most of the RTOS including FreeRTOS mutex implementation implements priority
inheritance feature.
Since mutex has all these features to avoid priority inversion, the memory
consumed by mutex serivce may be higher than the binary semaphore..
t1
LowPriority task[LP]
MediumPriority task[MP]
HighPriority task[HP]
TheHP taskattempts to takethe Mutexbut
can't becauseit is stillbeingheldby theLP task.
TheHP task enters theblockedstateto wait for
thesemaphoreto becomeavailable.
TheLP taskreturningthe mutexcauses theHP taskto exit
theblockedstateas themutexholder.WhentheHP task
has finishedwiththe mutexit gives it back.TheMP task
only executes when theHP taskreturns totheblocked
stateso theMP taskneverholds up theHP task.
The LP tasktakes a Mutexbefore
being preempted by theHP task.
TheLP taskis preventingtheHP taskfromexecutingso inherits thepriorityof the
HP task. TheLP taskcannotnowbe preemptedby theMP task.TheLP task
cannot nowbe preempted by theMP task, so theamountof timethat priority
inversionexists is minimized. WhentheLP taskgives the mutexback it returns its
original priority.!
Time
1
2
3
4
Priorityinheritance: Minimizingtheeffectofpriority
inversion
Mutex Disadvantage
If your system is very simple having small number of manageable
tasks or if you are working in memory constrained environment
then its better to avoid using mutex by opting out from the
compilation . Because mutex will surely eat up more CODE space
than binary semaphore.
Advantages of Mutex over
Binary semaphore
Crude way to protect
critical section
Ways to protect the Critical Section
1. Binary semaphore
2. Mutex
3. Crude way ( disabling interrupts of the
system, either globally, or up to a specific
interrupt priority level)
Advantages of Mutex Over Binary
semaphore.
Mutex automatically provides a basic ‘priorityinheritance’ mechanism.
Priorityinheritance is a technique by which mutex minimizes the negative
effects of priority inversion . Mutex can not able to fix the priority inversion
problem completely but it surely lessens its impact.
GoodTask
ArrogantTask
UART_DR
(shareddata)
I want to
access the
UART_DR
I too want
to access it
!!!
GoodTask
ArrogantTask
Alright ! Lets have an
agreement ! No one
accesses UART_DR
without acquiring the
mutex .
No ! I don’t
agree to this
agreement
UART_DR
(shareddata)
GoodTask
ArrogantTask
I will access
whenever I
wantHow to safeguard my data ??
UART_DR
(shareddata)
GoodTask
ArrogantTask
I will access
whenever I
want
Lets disable the Interrupt
of the whole system
Which also prevents pre-
emption !
UART_DR
(shareddata)
FreeRTOS Priority
0 1 2 3 4
Priority levels
Highest Lowest
ARM Cortex M Priority
FreeRTOS Priority
0
Lowest
4
Highest
Priority levels
Priority register and
priority levels in ARM
Cortex-M Processor
AT91SAM3X8E STM32F446RE
STAtmel
ARM Cortex M
M3 M4
Priority register in Cortex M3/M4
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
8-bit interrupt priorityregister
In CortexM basedProcessor everyinterruptandSystemexceptionhas 8 bitinterruptpriority
registerto configure its Priority
So , ideallythereare 2^8 ( 256) interruptpriority levelsfrom 0x00 to 0xff .
Where0x00 is the highestpriorityand 0xff is the lowestpriority
Priority Register
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Implemented Not implemented
Microcontroller Vendor XXX Microcontroller Vendor YYY
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Implemented Not implemented
8 Levels of Priority level 16 Levels of Priority level
Write has no effect Write has no effect
0x00,0x20,0x40,0x60,
0x80,0xA0,0xC0, 0xE0
0x00,0x10,0x20,0x30,0x40,0x50,
0x60,0x70,0x80,0x90,0xa0,0xb0,0xc0,0xd0,0xe0,0xf0
AT91SAM3X8ESTM32F4xxTM4C123G
Example 1 : Setting Priority
Let’s say you want to configure a priority of an interrupt number 8(IRQ8) to be 5.
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Implemented Not implemented
AT91SAM3X8E
Interrupt priority Register corresponding to IRQ8
So, Now you want to write value 5 into this
register.. How do you write ?
Example 1 : Setting Priority
Let’s say you want to configure a priority of an interrupt number 8(IRQ8) to be 5.
AT91SAM3X8E
Interrupt priority Register corresponding to IRQ8
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Implemented Not implemented
0 0 0 0 0 1 0 1
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
Implemented Not implemented
0 1 0 1 0 0 0 0
Priority_register = priority_value << ( 8 - __NVIC_PRIO_BITS)
Priority_register = priority_value
FreeRTOS:
Memory Management
FreeRTOS Memory
Allocation Schemes
FreeRTOS Stack and heap
RAM
Low High
Heap (configTOTAL_HEAP_SIZE)
Task -1
TCB
Stack
TCB1
STACK-1
Task -2
TCB
Stack
TCB-2
STACK-2
SCB
Semaphore
SCB
Queue
QCB
Item list
QCB
ITEMLIST
This RAM space is used for
Global data, arrays, static variables,
etc
Dynamically Created kernel objects
xTaskCreate() xTaskCreate() xSemaphoreCreateBinary()xQueueCreate()
FreeRTOS Heap management Scheme
FreeRTOS APIs and
Applications
heap_1.c heap_2.c heap_3.c heap_4.c heap_5.c
pvPortMalloc() pvPortMalloc()
vPortFree()
pvPortMalloc()
vPortFree()
pvPortMalloc()
vPortFree()
pvPortMalloc()
vPortFree()
Application uses any one of these Schemes according to its requirements
Your_own
_mem.c
pvPortMalloc()
vPortFree()
heap_1.c
• Simplest Implementation among all other heap
management implementations
• In this implementation you can only allocate Heap
memory but you can not free it
• Can be used if your application never deletes a
task, queue, semaphore, mutex, etc. (which
actually covers the majority of applications in
which FreeRTOS gets used).
• This implementation is always deterministic
(always takes the same amount of time to execute)
and cannot result in memory fragmentation.
heap_2.c
• Heap_2.c is implemented using “Best Fit” algorithm
• This scheme allows freeing of memory unlike heap_1.c
• Combining adjacent free blocks into a single large
blocks is not possible using this scheme
• This scheme is used when the application repeatedly
deletes tasks, queues, semaphores, mutexes, etc . With
the possibility of memory fragmentation.
• Should not be used if the memory being allocated and
freed is of a random size
• It is not deterministic , but this scheme is much more
efficient than most standard C library malloc
implementations.
heap_3.c
• Heap_3.c just implements a wrapper around your standard
library memory allocation functions such as malloc and free
• The wrapper simply makes the malloc() and free() functions
thread safe.
• This implementation requires the linker to setup a heap, and
the compiler library to provide malloc() and free()
implementations.
• Not deterministic
• Not optimized for Embedded Systems, so consumes more
Code space.
• the configTOTAL_HEAP_SIZE setting in FreeRTOSConfig.h has
no effect when heap_3 is used
heap_4.c
• This scheme uses a first fit algorithm and, unlike scheme 2,
it does combine adjacent free memory blocks into a single
large block
• Can be used even when the application repeatedly deletes
tasks, queues, semaphores, mutexes, etc
• Even when the memory being allocated and freed in
random size, it is less likely to result in a heap space that is
badly fragmented in to smaller useless blocks.
• Much more efficient than most standard C library malloc
implementations.
• heap_4.c is particularly useful for applications that want to
use the portable layer memory allocation schemes directly
in the application code (rather than just indirectly by calling
API functions that themselves call pvPortMalloc() and
vPortFree()).
heap_5.c
• This scheme uses the same first fit and memory
coalescence algorithms as heap_4, and allows the heap to
span multiple non adjacent (non-contiguous) memory
regions.
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging

Contenu connexe

Tendances

Arm7 Interfacing examples
Arm7   Interfacing examples Arm7   Interfacing examples
Arm7 Interfacing examples Dr.YNM
 
Real time operating systems (rtos) concepts 4
Real time operating systems (rtos) concepts 4Real time operating systems (rtos) concepts 4
Real time operating systems (rtos) concepts 4Abu Bakr Ramadan
 
ARM - Advance RISC Machine
ARM - Advance RISC MachineARM - Advance RISC Machine
ARM - Advance RISC MachineEdutechLearners
 
Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development FastBit Embedded Brain Academy
 
Part-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver developmentPart-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver developmentFastBit Embedded Brain Academy
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modulesEddy Reyes
 
Linux or unix interview questions
Linux or unix interview questionsLinux or unix interview questions
Linux or unix interview questionsTeja Bheemanapally
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecturehugo lu
 

Tendances (20)

FreeRTOS introduction
FreeRTOS introductionFreeRTOS introduction
FreeRTOS introduction
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
SystemC Ports
SystemC PortsSystemC Ports
SystemC Ports
 
Pcie basic
Pcie basicPcie basic
Pcie basic
 
Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0Linux Internals - Interview essentials - 1.0
Linux Internals - Interview essentials - 1.0
 
Arm7 Interfacing examples
Arm7   Interfacing examples Arm7   Interfacing examples
Arm7 Interfacing examples
 
sc vector
sc vectorsc vector
sc vector
 
Embedded linux network device driver development
Embedded linux network device driver developmentEmbedded linux network device driver development
Embedded linux network device driver development
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
 
Real time operating systems (rtos) concepts 4
Real time operating systems (rtos) concepts 4Real time operating systems (rtos) concepts 4
Real time operating systems (rtos) concepts 4
 
RTOS - Real Time Operating Systems
RTOS - Real Time Operating SystemsRTOS - Real Time Operating Systems
RTOS - Real Time Operating Systems
 
ARM - Advance RISC Machine
ARM - Advance RISC MachineARM - Advance RISC Machine
ARM - Advance RISC Machine
 
13 superscalar
13 superscalar13 superscalar
13 superscalar
 
Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development Part-1 : Mastering microcontroller with embedded driver development
Part-1 : Mastering microcontroller with embedded driver development
 
Part-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver developmentPart-2: Mastering microcontroller with embedded driver development
Part-2: Mastering microcontroller with embedded driver development
 
Linux kernel modules
Linux kernel modulesLinux kernel modules
Linux kernel modules
 
Linux or unix interview questions
Linux or unix interview questionsLinux or unix interview questions
Linux or unix interview questions
 
Qemu Pcie
Qemu PcieQemu Pcie
Qemu Pcie
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecture
 
Linux Device Tree
Linux Device TreeLinux Device Tree
Linux Device Tree
 

Similaire à PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging

Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
maXbox Starter 45 Robotics
maXbox Starter 45 RoboticsmaXbox Starter 45 Robotics
maXbox Starter 45 RoboticsMax Kleiner
 
Apache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing dataApache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing dataDataWorks Summit/Hadoop Summit
 
Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Databricks
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 
Monitoring MySQL with Prometheus and Grafana
Monitoring MySQL with Prometheus and GrafanaMonitoring MySQL with Prometheus and Grafana
Monitoring MySQL with Prometheus and GrafanaJulien Pivotto
 
OSMC 2017 | Monitoring MySQL with Prometheus and Grafana by Julien Pivotto
OSMC 2017 | Monitoring  MySQL with Prometheus and Grafana by Julien PivottoOSMC 2017 | Monitoring  MySQL with Prometheus and Grafana by Julien Pivotto
OSMC 2017 | Monitoring MySQL with Prometheus and Grafana by Julien PivottoNETWAYS
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustEvan Chan
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response timesYan Cui
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarMaarten Balliauw
 
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...netvis
 
Deep learning with kafka
Deep learning with kafkaDeep learning with kafka
Deep learning with kafkaNitin Kumar
 
Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Trayan Iliev
 
Open Source XMPP for Cloud Services
Open Source XMPP for Cloud ServicesOpen Source XMPP for Cloud Services
Open Source XMPP for Cloud Servicesmattjive
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringVMware Tanzu
 

Similaire à PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging (20)

Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
maXbox Starter 45 Robotics
maXbox Starter 45 RoboticsmaXbox Starter 45 Robotics
maXbox Starter 45 Robotics
 
Apache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing dataApache Beam: A unified model for batch and stream processing data
Apache Beam: A unified model for batch and stream processing data
 
Embedded systems
Embedded systemsEmbedded systems
Embedded systems
 
Mysql Latency
Mysql LatencyMysql Latency
Mysql Latency
 
Lab6 rtos
Lab6 rtosLab6 rtos
Lab6 rtos
 
Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...Building Continuous Application with Structured Streaming and Real-Time Data ...
Building Continuous Application with Structured Streaming and Real-Time Data ...
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practice
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Monitoring MySQL with Prometheus and Grafana
Monitoring MySQL with Prometheus and GrafanaMonitoring MySQL with Prometheus and Grafana
Monitoring MySQL with Prometheus and Grafana
 
OSMC 2017 | Monitoring MySQL with Prometheus and Grafana by Julien Pivotto
OSMC 2017 | Monitoring  MySQL with Prometheus and Grafana by Julien PivottoOSMC 2017 | Monitoring  MySQL with Prometheus and Grafana by Julien Pivotto
OSMC 2017 | Monitoring MySQL with Prometheus and Grafana by Julien Pivotto
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
Real time-embedded-system-lec-03
Real time-embedded-system-lec-03Real time-embedded-system-lec-03
Real time-embedded-system-lec-03
 
How to debug slow lambda response times
How to debug slow lambda response timesHow to debug slow lambda response times
How to debug slow lambda response times
 
Exploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinarExploring .NET memory management - JetBrains webinar
Exploring .NET memory management - JetBrains webinar
 
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...
The sFlow Standard: Scalable, Unified Monitoring of Networks, Systems and App...
 
Deep learning with kafka
Deep learning with kafkaDeep learning with kafka
Deep learning with kafka
 
Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9
 
Open Source XMPP for Cloud Services
Open Source XMPP for Cloud ServicesOpen Source XMPP for Cloud Services
Open Source XMPP for Cloud Services
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with Spring
 

Dernier

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 

Dernier (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging

  • 1. Mastering RTOS: Hands on FreeRTOS and STM32Fx with Debugging Learn Running/Porting FreeRTOS Real Time Operating System on STM32F4x and ARM cortex M based Mircocontrollers Created by : FastBit Embedded Brain Academy Visit www.fastbitlab.com for all online video courses on MCU programming, RTOS and embedded Linux PART-3
  • 2. FastBit Embedded Brain Academy is an online training wing of Bharati Software. We leverage the power of the internet to bring online courses at your fingertip in the domain of embedded systems and programming, microcontrollers, real-time operating systems, firmware development, Embedded Linux. All our online video courses are hosted in Udemy E-learning platform which enables you to exercise 30 days no questions asked money back guarantee. For more information please visit : www.fastbitlab.com Email : contact@fastbitlab.com About FastBitEBA
  • 3. Queues and its features
  • 4. So ,what are queues ? Item-4 Item-3 Item-2 Item-1 Item-5 Tail head Item-0 Enqueue dequeue
  • 5. So ,what are queues ? Tail Head Append (enqueue)
  • 6. Queue Task A Task B 15 Queue Task A Task B Whena Queueis createdit does not containanythingso it is empty TaskA writes a valuein to thequeue. Thevalueis sentto the front Sincethequeuewas previouslyempty,the valueis nowboththefirst andthelast valuein thequeue:
  • 7. 12 15 Queue Task A Task B 12 15 Queue Task A Task B TaskA sends another value. Thequeuenowcontains thepreviouslywrittenvalueandthis newly addedvalue.The previous value remains at the front of the queue while the new one is now at its back.Threespaces are stillavailable TaskB reads a valuein thequeue.It willreceivethevalue whichis in thefront of thequeue
  • 8. 12 Queue Task A Task B Task B has removedan item.Theseconditemis movedto be theoneinthefrontof thequeue. Thisis the valuetask 2 will readnext timeit tries to reada value. Fourspaces are nowavailable:
  • 9. Main Uses of Queues in RTOS 1. Synchronization between Tasks or Interrupts 2. Inter-task communication
  • 10. Queues in Synchronization and inter-Task communication Blocked while accessing the empty Queue I needsomedatatoconsume But waitingforTASKA to producesome datain thequeue Task A Task B Data Producer Empty Queue Data Consumer
  • 11. Queues in Synchronization and inter-Task communication I m unblocked Looks like Data available in the queue Task A Task B Queue Data Produced Unblocks Task B Data Producer Data Consumer
  • 13. FreeRTOS API to Create a Queue xQueueHandle xQueueCreate( unsigned portBASE_TYPE uxQueueLength, unsigned portBASE_TYPE uxItemSize );
  • 14. RAM Low High Heap (configTOTAL_HEAP_SIZE) Task -1 TCB Stack TCB1 STACK-1 Task -2 TCB Stack TCB-2 STACK-2 SCB Semaphore SCB Queue QCB Item list QCB ITEMLIST This RAM space is used for Global data, arrays, static variables, etc Dynamically Created kernel objects xTaskCreate() xTaskCreate() xSemaphoreCreateBinary()xQueueCreate()
  • 15.
  • 16. Sending data to the Queue
  • 17. Sending data to the queue xQueueSendToFront() xQueueSendToBack()
  • 18. xQueueSendToFront() portBASE_TYPE xQueueSendToFront( xQueueHandle xQueue, const void * pvItemToQueue, portTickType xTicksToWait );
  • 19.
  • 20. xQueueSendToBack() portBASE_TYPE xQueueSendToBack( xQueueHandle xQueue, const void * pvItemToQueue, portTickType xTicksToWait );
  • 21. Receiving data from the Queue
  • 22. Receiving data from the Queue xQueueReceive() xQueuePeek()
  • 23. xQueueReceive() portBASE_TYPE xQueueReceive(xQueueHandle xQueue, const void * pvBuffer, portTickType xTicksToWait );
  • 24. xQueuePeek() portBASE_TYPE xQueuePeek(xQueueHandle xQueue, const void * pvBuffer, portTickType xTicksToWait );
  • 25. Exercise Design a FreeRTOS application which implements the below commands LED_ON, LED_OFF, LED_TOGGLE_START LED_TOGGLE_STOP LED_STATUS_READ RTC_DATETIME_READ The command should be sent to the board via UART from the user.
  • 26. Command Format struct APP_CMD { uint8_t COMMAND_NUM; uint8_t COMMAND_ARGS[10]; }; /* Lets use this data structure to store command number and its associated arguments. */
  • 27.
  • 29. Use case Toggle the led for very 500ms . led_toggle();
  • 30. Hardware Vs Software Timers Hardware timers Software timers Handled by the TIMER peripheral of the MCU Handled by FreeRTOS kernel Code No FreeRTOS APIs . You have to create your own Function to manage the timer peripherals FreeRTOS APIs are availabe Micros/nano seconds resolutions are possible Resolution Depends on the RTOS_TICK_RATE_HZ
  • 32. PT PT PT ISR execution (an event) will be caught by counting semaphore HT HT HT Events will be processed by handler Task
  • 34. A semaphore is a kernel object or you can say kernel service, that one or more threads of execution can acquire or release for the purpose of synchronization or mutual exclusion.
  • 37. Manager Employee Meeting @ 11 o Clock Tomorrow
  • 38. Both are synchronized withthe time, hencethe One-on-One meeting runningas expected
  • 39. Manager Employee Meeting Tomorrow Wasting your time arriving sooner You are not yet arrived for the meeting
  • 40. Task-A producer Task-B Consumer t1 Task A runs first and it is waiting for data from Device driver t2 Task B runs that means Task A is pre-empted t3 Task A runs again and finds the device driver not yet given any data. t4 no data is available so it again doesn't take any action Task A and TaskB are not synchronizedfor the productionand consumptionof data
  • 41. Task-A producer Task-B Consumer t1 Task A runs first and it is waiting for data from Device driver t2 Task B runs that means Task A is pre-empted t3 Task A runs again and finds the device driver not yet given any data. t4 no data is available so it again doesn't take any action
  • 42. Kernel Objects which can be used for Synchronization Events (or Event Flags) Semaphores ( Counting and binary ) Queues and MessageQueues Pipes Mailboxes Signals (UNIXlike signals) Mutex FreeRTOS Supports Semaphores, Queues and Mutex
  • 43. Mutual Exclusion Shared Entity TASK-1 TASK-2 Task-2cannot accessthe sharedentityunless Task-1 withdraws theownership Global variable , data structure Common function which use some global data . Peripheral memory ,etc
  • 44. Concluding points Synchronization is nothing but aligning number of Tasks to achieve a desired behaviour. Where as mutual exclusion is avoiding a task to execute the critical section which is already owned by another task for execution. Typically Semaphores are used to implement the synchronization between tasks and between tasks and interrupts. Mutex are the best choice to implement the mutual exclusion. That is protecting access of a shared item. Semaphores also can be used to implement the mutual exclusion but it will introduce some serious design issues which we will see later.
  • 45. Lets see how we can use semaphores for Synchronization
  • 47. Creating a Semaphore SCB Value (Binary or a Count) Task-1 Task-2 Task-3 Task-Waiting-List ThisvalueDetermines howmany semaphoretokens are available. Keys or tokens Semaphore id or name
  • 48. Types of Semaphore 1 Binary semaphore 2 Counting semaphore
  • 49. Creating a Semaphore A single semaphore can be acquired a finite number of times by the tasks depending upon the how you first initializae the semaphore.
  • 51. Semaphore Semaphores are kernel objects, or you can say kernel services which you can use to achieve the synchronization and mutual exclusion in your project.
  • 52. Types of Semaphore 1. Binary semaphore 2. Counting semaphore
  • 53. Binary Semaphore as name indicates, this semaphore works on only 2 values that is 1 and 0.
  • 54. Binarysemaphore SCB Value Task-Waiting-List This“Value”eitherwillbe 0 or 1 Analogous toOnly 1 key Semaphore id or name Taskwaitinglistwill havethe Blocked tasks whichare waiting forthekey
  • 55. Binary semaphore use cases 1. Synchronization That is synchronization between tasks or synchronization between interrupts and tasks. 2. Mutual Exclusion Binary semaphore can also be used for Mutual Exclusion, that is to guard the critical section
  • 56. Counting semaphore SCB Value Task-Waiting-List This“Value”canbe any number. If youinitializeit to 5 forexample, thenit is analogous having5 keys. Analogous to having manykeys Semaphore id or name Taskwaitinglistwill havethe Blocked tasks whichare waiting forthekeys.
  • 57. Counting semaphore use cases 1. CountingEvents In this usage scenario an event handler will 'give' a semaphore each time an event occurs – causing the semaphores count value to be increment on each give. A handler task will 'take' a semaphore each time it processes an event – causing the semaphores count value to be decremented on each take. 2. ResourceManagement In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a, task must first obtain a semaphore – decrementing the semaphores count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back – incrementing the semaphores count value.
  • 58. Counting semaphore use cases Resource Management In this usage scenario the count value indicates the number of resources available. To obtain control of a resource a task must first obtain a semaphore by decrementing the semaphores count value. When the count value reaches zero there are no free resources. When a task finishes with the resource it 'gives' the semaphore back thus incrementing the semaphores count value.
  • 59. void interrupt_handler(void) { do_important_work(); /* this is very short code */ sema_give(&sem); /* Give means release the key */ } /* exit from the interrupt */ void task_function(void) { /* if taking a key is un-successful then this task will be blocked until key is available */ while ( sem_get(&sem ) ) // GET means, trying to take the key { // it will come here, only if taking a key is successful . /* Do time consuming work of the ISR */ } }
  • 60. Counting semaphore use cases Event/Interrupt counting & handling
  • 61. Binary Semaphore to achieve Synchronization between two tasks
  • 62. Lets first see how binary semaphore can be used for synchronization between 2 tasks. The main use of binary semaphore or counting semaphore is synchronization. The synchronization can be between tasks or between a task and an interrupt.
  • 63. Binary sema to Synchronize between Tasks Task-1 Data Producer Task-2 Data Consumer Sema_key Increments the key Whendatais produced Unblocks Task-B If it was blockeddueto Non-availabilityof key
  • 64. voidtask1_running(void) { if( TRUE== produce_some_data()) { /* This is a signallingforthetask2 towakeup if it is blockeddueto nonavailabilityof key*/ sema_give(&sema_key); // ‘GIVE’ operationwill incrementthesemaphorevalueby 1 } } voidtask2_running(void) { /* if sema_key is unavailable thentask2will be blocked.*/ /*if sema_key is available,thentask2will takeit and sema_key becomes unavailableagain */ while(sema_take(&sema_key) ) { //Taskwillcomehereonlywhenthe sem_take operationis successful. /* lets consumethe data*/ /*sincethe sem_keyvalueis zeroat this point,thenext timewhentask-2tries to take,it willbe blocked. */ } }
  • 65. /* declaring a semaphore object */ Semaphore sem_key; int main() { /* Create Task1 */ /* Create Task-2 */ /* Create a binarysemaphore*/ Sem_key = create_bin_sema(); /* schedule both the tasks */ }
  • 66. Exercise Create 2 tasks 1) Manager task 2) Employee task With manager task being the higher priority . When manager task runs it should create a “Ticket id” and post it to the queue and signal the employee task to process the “Ticket id”. When employee task runs it should read from the queue and process the “Ticket id” posted by the manager task. Use binary semaphore to synchronize between manger and employee task.
  • 67. Binary semaphore to achieve Synchronization between an Interrupt & a Task
  • 68. Synchronizationbetween Interrupt& Task The Binary semaphore is very handy and well suited to achieve the synchronization between an interrupt handler execution and the task handler execution.
  • 69. void interrupt_handler(void) { do_important_work(); /* this is very short code */ xSemaphoreGiveFromISR(&sem); /* Give means release the key */ } /* exit from the interrupt */ /* I am helper task for the interrupt ! I do time consuming work on behalf of interrupt handler*/ void helper_task(void) { /* if taking a key is un-successful then this task will be blocked until key is available */ while (xSemaphoreTake(&sem ) ) // GET means, trying to take the key { // it will come here, only if taking a key is successful . /* Do time consuming work of the ISR */ } }
  • 70. A NA A NA Thesemaphoreis not available xSemaphoreTake() Task Thetaskis blockedwaiting forthesemaphore xSemaphoreTake() Task Interrupt!!! xSemaphoreGiveFromISR() An Interrupt occurs..that ‘gives’thesemaphore Synchronization between an Interrupt and a Task using Binary semaphore 1 Task is in blockedstate initially 2 Interrupt occurs Thesemaphore is available
  • 71. A NA A NA Interrupt!!! xSemaphoreGiveFromISR() xSemaphoreTake() Task … whichunblocks thetask ( thesemaphoreis nowavailable) xSemaphoreTake() Task Thetasknowsuccessfully‘takes’the semaphore,so it is unavailableonce more 3 Task Unblocked & tries to take the semaphore. 4 Task tookthe semaphore
  • 72.
  • 73.
  • 74. Binary sema to Synchronize between interrupt and task. 1.An interrupt occurred, when the task was in blocked state 2.The ISR executed and gave the semaphore ,due to that the task was unblocked. 3.The Task executed and took the semaphore. 4.The task performed the intended work and tried to take the semaphore once again 5.Entered the Blocked state again ,if the semaphore was not immediately available.
  • 75. Events Latching & Processing using Counting semaphore
  • 76. A NA A NA Thesemaphoreis not available xSemaphoreTake() Task Thetaskis blockedwaiting forthesemaphore xSemaphoreTake() Task Interrupt!!! xSemaphoreGiveFromISR() An Interrupt occurs..that ‘gives’thesemaphore Synchronization between an Interrupt and a Task using Binary semaphore
  • 77. A NA A NA Interrupt!!! xSemaphoreGiveFromISR() xSemaphoreTake() Task … whichunblocks thetask ( thesemaphoreis nowavailable) xSemaphoreTake() Task Thetasknowsuccessfully‘takes’the semaphore,so it is unavailableonce more
  • 78. A NA A NA Thesemaphoreis not available xSemaphoreTake() Task Thetaskis blockedwaiting forthesemaphore xSemaphoreTake() Task Interrupt!!! xSemaphoreGiveFromISR() An Interrupt occurs..that ‘gives’thesemaphore Binary semaphore can latch at most 1 event
  • 79. A NA A NA Interrupt!!! xSemaphoreGiveFromISR() xSemaphoreTake() Task … whichunblocks thetask ( thesemaphoreis nowavailable) xSemaphoreTake() Task Thetasknowsuccessfully‘takes’the semaphore,so it is unavailableonce more
  • 80. A NA A NA Interrupt!!! xSemaphoreGiveFromISR() Task Thetaskis still processingthefirst interrupt event xSemaphoreTake() Task Whenprocessingof theoriginaleventcompletes thetaskcalls xSemaphoreTake()again.Because anotherinterrupthas alreadyoccurredthesemaphoreis alreadyavailableso thetask takes the semaphorewithout everenteringtheBlockedstate Anotherinterrupt occurs whilethetaskis stillprocessing thefirst event.TheISR ‘Gives’thesemaphoreagain, effectivelylatching theeventso theevent is not lost
  • 81. Concluding Points on Latching Events 1. When the interrupts/events happen relatively slow, the binary semaphore can latch at most only one event 2. If multiple interrupts/events trigger back to back, then the binary semaphore will not able to latch all the events. So some events will be lost . 3. How to solve the above issue ? Welcome to the world of “Counting Semaphore”
  • 82. Counting semaphore to latch multiple events
  • 83. Thesemaphoreis not available xSemaphoreTake() Task Thetaskis blockedwaiting forthesemaphore xSemaphoreTake() Task Interrupt!!! xSemaphoreGiveFromISR() An Interrupt occurs..that ‘gives’thesemaphore Counting semaphore can be used to latch multiple events Semaphorecountis 0 Semaphorecountis 1
  • 84. Interrupt!!! xSemaphoreGiveFromISR() xSemaphoreTake() Task … whichunblocks thetask ( thesemaphoreis nowavailable) xSemaphoreTake() Task Thetasknowsuccessfully‘takes’the semaphore,so it is unavailableonce more Semaphorecountis 1 Thesemaphoreis not available Semaphorecountis 0
  • 85. Interrupt!!! xSemaphoreGiveFromISR() Task Thetaskis still processingthefirst interrupt event xSemaphoreTake() Task Whenprocessingof thefirstevent completes,thetaskcalls xSemaphoreTake()again.Againtwo semaphores arealready ‘available‘,oneis takenwithout thetaskeverenteringtheBlockedState, leavingonemore‘latched’ semaphoreavailable. Another2 interruptoccurwhilethetaskis stillprocessingthe firstevent. TheISR ‘Gives’thesemaphoreeachtime. effectively latchingboththeevents so neithereventis lost Semaphorecountis 2 Semaphorecountis 1
  • 86. Concluding points on Counting semaphore You can use counting semaphore to count the events and process them serially one by one using another task. The counting semaphore can also be used for resource management .That is to regulate access to multiple identical resources
  • 87. Exercise Create 2 tasks. 1) Hander task 2) Periodic task Periodic task priority must be higher than the handler task. Use counting semaphore to process latched events(by handler task) sent by fast triggering interrupts. Use the counting semaphore to latch events from the interrupts
  • 89. Access to a resource that is shared either between tasks or between tasks and interrupts needs to be serialized using a some techniques to ensure data consistency. Usually a common code block which deals with global array , variable or memory address, has the possibility to get corrupted , when many tasks or interrupts are racing around it Mutual Exclusion using Binary Semaphore
  • 90. #define UART_DR *((unsigned long * ) (0x40000000) ) /* This is a common function which write to UART DR */ int UART_Write( uint32_t len , uint8_t *buffer) { for (uint32_ti=0;i < len ; i++) { /* if Data Register is empty write it */ while(! is_DR_empty() ); UART_DR = buffer[i]; } } This is Thread-Unsafe code
  • 91. #define UART_DR *((unsigned long * ) (0x40000000) ) /* This is a common function which write to UART DR */ int UART_Write( uint32_t len , uint8_t *buffer) { for (uint32_ti=0;i < len ; i++) { /* if Data Register is empty write it */ while(! is_DR_empty() ); UART_DR = buffer[i]; } } This is Thread-Unsafe code This codeis absolutelyfine in non-multitaskingscenario( onlyone taskexistsper application).But in multi-taskingscenario, this functionis thread unsafe.That means, there is a possibility of race conditionsincethe critical section codeis notprotected.
  • 92. Mutual Exclusion by Binary semaphore
  • 93. Mutual Exclusion by Binary semaphore #define UART_DR *((unsigned long * ) (0x40000000) ) /* This is a common function which write to UART DR */ int UART_Write( uint32_t len , uint8_t *buffer) { for (uint32_t i=0;i < len ; i++) { /* if Data Register is empty write it */ while(! is_DR_empty() ); UART_DR = buffer[i]; } }
  • 94. 2 ways we can Implement the mutual exclusion in FreeRTOS 1. Using Binary semaphore APIs 2. Using Mutex APIs
  • 96. #define UART_DR *((unsigned long * ) (0x40000000) ) /* This is a common function which write to UART DR */ int UART_Write( uint32_t len , uint8_t *buffer) { for (uint32_t i=0;i < len ; i++) { sema_take_key(bin_sema ); /* if Data Register is empty write it */ while(! is_DR_empty() ); UART_DR = buffer[i]; //Critical section sema_give_key( bin_sema ); } }
  • 97. Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource Twotaskseachwant to access theresource,but a taskis not permittedtoaccesstheresourceunlessit is thetokenholder Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource TaskA attempts totakethesemaphore,becausesemaphoreis availableTask A successfully becomethesemaphoreholderso it is permittedtoaccess the resource xSemaphoreTake()
  • 98. Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource TaskB executes andattempts totakethesamesemaphore.TaskA stillhas the semaphore, so theattempt fails andTaskB is not permittedto accesstheguardedresource! Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource TaskB opts toentertheblockedstateto wait forthesemaphore,allowing TaskA to run again. TaskA finisheswiththeresourceso ‘gives’thesemaphoreback . xSemaphoreTake() xSemaphoreGive() xSemaphoreTake()
  • 99. Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource TaskA givingthe semaphoreback causes TaskB to exittheblockedstate( thesemaphoreis nowavailable ). Task B cannowsuccessfullyobtainthesemaphore,and havingdoneso is permittedto accesstheresource. Task-A Task-BA NA Guarded Resource This resource is Guarded by binary semaphore Binary semaphore Used to guard the resource WhenTaskB finishes theresourceit toogives thesemaphoreback. Thesemaphoreis nowonceagainavailable tobothtasks. xSemaphoreTake() xSemaphoreGive()
  • 100. Advantages of Mutex over Binary semaphore
  • 102. FreeRTOS Mutex Services Mutex is derived from the phrase Mutual Exclusion ! Mutex is also kind of binary semaphore that include a priority inheritance mechanism which minimizes the effect of Priority inversion . Binary semaphores are the better choice for implementing synchronisation (between tasks or between tasks and an interrupt), mutexes are the better choice for implementing simple mutual exclusion
  • 103. Advantages of Mutex Over Binary semaphore. Priority Inheritance Mutexes and binary semaphores are very similar – the only major difference is mutexes automatically provide a basic ‘priorityinheritance’ mechanism. Priority inheritance is a technique by which mutex minimizes the negative effects of priority inversion . Mutex can not able to fix the priority inversion problem completely but it surely lessens its impact.
  • 104. Advantages of Mutex Over Binary semaphore. Priority Inheritance Most of the RTOS including FreeRTOS mutex implementation implements priority inheritance feature. Since mutex has all these features to avoid priority inversion, the memory consumed by mutex serivce may be higher than the binary semaphore..
  • 105. t1 LowPriority task[LP] MediumPriority task[MP] HighPriority task[HP] TheHP taskattempts to takethe Mutexbut can't becauseit is stillbeingheldby theLP task. TheHP task enters theblockedstateto wait for thesemaphoreto becomeavailable. TheLP taskreturningthe mutexcauses theHP taskto exit theblockedstateas themutexholder.WhentheHP task has finishedwiththe mutexit gives it back.TheMP task only executes when theHP taskreturns totheblocked stateso theMP taskneverholds up theHP task. The LP tasktakes a Mutexbefore being preempted by theHP task. TheLP taskis preventingtheHP taskfromexecutingso inherits thepriorityof the HP task. TheLP taskcannotnowbe preemptedby theMP task.TheLP task cannot nowbe preempted by theMP task, so theamountof timethat priority inversionexists is minimized. WhentheLP taskgives the mutexback it returns its original priority.! Time 1 2 3 4
  • 107. Mutex Disadvantage If your system is very simple having small number of manageable tasks or if you are working in memory constrained environment then its better to avoid using mutex by opting out from the compilation . Because mutex will surely eat up more CODE space than binary semaphore.
  • 108. Advantages of Mutex over Binary semaphore
  • 109. Crude way to protect critical section
  • 110. Ways to protect the Critical Section 1. Binary semaphore 2. Mutex 3. Crude way ( disabling interrupts of the system, either globally, or up to a specific interrupt priority level)
  • 111. Advantages of Mutex Over Binary semaphore. Mutex automatically provides a basic ‘priorityinheritance’ mechanism. Priorityinheritance is a technique by which mutex minimizes the negative effects of priority inversion . Mutex can not able to fix the priority inversion problem completely but it surely lessens its impact.
  • 112. GoodTask ArrogantTask UART_DR (shareddata) I want to access the UART_DR I too want to access it !!!
  • 113. GoodTask ArrogantTask Alright ! Lets have an agreement ! No one accesses UART_DR without acquiring the mutex . No ! I don’t agree to this agreement UART_DR (shareddata)
  • 114. GoodTask ArrogantTask I will access whenever I wantHow to safeguard my data ?? UART_DR (shareddata)
  • 115. GoodTask ArrogantTask I will access whenever I want Lets disable the Interrupt of the whole system Which also prevents pre- emption ! UART_DR (shareddata)
  • 117. 0 1 2 3 4 Priority levels Highest Lowest ARM Cortex M Priority FreeRTOS Priority 0 Lowest 4 Highest Priority levels
  • 118. Priority register and priority levels in ARM Cortex-M Processor
  • 120. Priority register in Cortex M3/M4 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 8-bit interrupt priorityregister In CortexM basedProcessor everyinterruptandSystemexceptionhas 8 bitinterruptpriority registerto configure its Priority So , ideallythereare 2^8 ( 256) interruptpriority levelsfrom 0x00 to 0xff . Where0x00 is the highestpriorityand 0xff is the lowestpriority
  • 121. Priority Register Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Implemented Not implemented Microcontroller Vendor XXX Microcontroller Vendor YYY Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Implemented Not implemented 8 Levels of Priority level 16 Levels of Priority level Write has no effect Write has no effect 0x00,0x20,0x40,0x60, 0x80,0xA0,0xC0, 0xE0 0x00,0x10,0x20,0x30,0x40,0x50, 0x60,0x70,0x80,0x90,0xa0,0xb0,0xc0,0xd0,0xe0,0xf0 AT91SAM3X8ESTM32F4xxTM4C123G
  • 122. Example 1 : Setting Priority Let’s say you want to configure a priority of an interrupt number 8(IRQ8) to be 5. Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Implemented Not implemented AT91SAM3X8E Interrupt priority Register corresponding to IRQ8 So, Now you want to write value 5 into this register.. How do you write ?
  • 123. Example 1 : Setting Priority Let’s say you want to configure a priority of an interrupt number 8(IRQ8) to be 5. AT91SAM3X8E Interrupt priority Register corresponding to IRQ8 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Implemented Not implemented 0 0 0 0 0 1 0 1 Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Implemented Not implemented 0 1 0 1 0 0 0 0 Priority_register = priority_value << ( 8 - __NVIC_PRIO_BITS) Priority_register = priority_value
  • 126. FreeRTOS Stack and heap RAM Low High Heap (configTOTAL_HEAP_SIZE) Task -1 TCB Stack TCB1 STACK-1 Task -2 TCB Stack TCB-2 STACK-2 SCB Semaphore SCB Queue QCB Item list QCB ITEMLIST This RAM space is used for Global data, arrays, static variables, etc Dynamically Created kernel objects xTaskCreate() xTaskCreate() xSemaphoreCreateBinary()xQueueCreate()
  • 127. FreeRTOS Heap management Scheme FreeRTOS APIs and Applications heap_1.c heap_2.c heap_3.c heap_4.c heap_5.c pvPortMalloc() pvPortMalloc() vPortFree() pvPortMalloc() vPortFree() pvPortMalloc() vPortFree() pvPortMalloc() vPortFree() Application uses any one of these Schemes according to its requirements Your_own _mem.c pvPortMalloc() vPortFree()
  • 128. heap_1.c • Simplest Implementation among all other heap management implementations • In this implementation you can only allocate Heap memory but you can not free it • Can be used if your application never deletes a task, queue, semaphore, mutex, etc. (which actually covers the majority of applications in which FreeRTOS gets used). • This implementation is always deterministic (always takes the same amount of time to execute) and cannot result in memory fragmentation.
  • 129. heap_2.c • Heap_2.c is implemented using “Best Fit” algorithm • This scheme allows freeing of memory unlike heap_1.c • Combining adjacent free blocks into a single large blocks is not possible using this scheme • This scheme is used when the application repeatedly deletes tasks, queues, semaphores, mutexes, etc . With the possibility of memory fragmentation. • Should not be used if the memory being allocated and freed is of a random size • It is not deterministic , but this scheme is much more efficient than most standard C library malloc implementations.
  • 130. heap_3.c • Heap_3.c just implements a wrapper around your standard library memory allocation functions such as malloc and free • The wrapper simply makes the malloc() and free() functions thread safe. • This implementation requires the linker to setup a heap, and the compiler library to provide malloc() and free() implementations. • Not deterministic • Not optimized for Embedded Systems, so consumes more Code space. • the configTOTAL_HEAP_SIZE setting in FreeRTOSConfig.h has no effect when heap_3 is used
  • 131. heap_4.c • This scheme uses a first fit algorithm and, unlike scheme 2, it does combine adjacent free memory blocks into a single large block • Can be used even when the application repeatedly deletes tasks, queues, semaphores, mutexes, etc • Even when the memory being allocated and freed in random size, it is less likely to result in a heap space that is badly fragmented in to smaller useless blocks. • Much more efficient than most standard C library malloc implementations. • heap_4.c is particularly useful for applications that want to use the portable layer memory allocation schemes directly in the application code (rather than just indirectly by calling API functions that themselves call pvPortMalloc() and vPortFree()).
  • 132. heap_5.c • This scheme uses the same first fit and memory coalescence algorithms as heap_4, and allows the heap to span multiple non adjacent (non-contiguous) memory regions.