Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
130 views

Embedded Programming

The document discusses embedded C programming, including defining embedded systems and their components. It covers interfacing memory and I/O devices to microprocessors using techniques like volatile and non-volatile memory. Programming embedded systems in C is also discussed.

Uploaded by

RAJI
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

Embedded Programming

The document discusses embedded C programming, including defining embedded systems and their components. It covers interfacing memory and I/O devices to microprocessors using techniques like volatile and non-volatile memory. Programming embedded systems in C is also discussed.

Uploaded by

RAJI
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Embedded C Programming

Course Objective: To introduce Interfacing I/O


devices to the Processor

Course Outcome: Write Embedded C Program

22/04/2024 Embedded C Programming 1


What is an embedded system?
• An embedded system is an application that contains at least one
programmable computer (typically in the form of a microcontroller, a
microprocessor or digital signal processor chip) and which is used by
individuals who are, in the main, unaware that the system is
computer-based.

• This type of embedded system is all around us. Use of embedded


processors in passenger cars, mobile phones, medical equipment,
aerospace systems and defence systems is widespread, and even
everyday domestic appliances such as dishwashers, televisions,
washing machines and video recorders now include at least one such
device.

22/04/2024 Embedded C Programming 2


22/04/2024 Embedded C Programming 3
Memory and I/O Devices Interfacing

22/04/2024 Embedded C Programming 4


Memory Interfacing
• When we are executing any instruction, the address of memory
location or an I/O device is sent out by the microprocessor. The
corresponding memory chip or I/O device is selected by a decoding
circuit.

• Memory requires some signals to read from and write to registers and
microprocessor transmits some signals for reading or writing data.

• The interfacing process includes matching the memory requirements


with the microprocessor signals. Therefore, the interfacing circuit
should be designed in such a way that it matches the memory signal
requirements with the microprocessor's signals.

22/04/2024 Embedded C Programming 5


22/04/2024 Embedded C Programming 6
Volatile vs. non-volatile memory
• Volatile memory can hold its stored information only as
long as it maintains its power supply. Non-volatile memory
keeps the stored information even when the power is off.

• When power is off, volatile memory loses its data. Random


access memory (RAM) is a type of volatile memory.

• Engineers use non-volatile memory in embedded systems to


store code and other data that the device always needs,
including after the system restarts. For example, non-
volatile memory often holds configuration settings for the
system.
22/04/2024 Embedded C Programming 7
Primary Memory for Embedded System

22/04/2024 Embedded C Programming 8


ROM
These are types of non-volatile memory that embedded systems can use:
• Masked ROM: With this memory, the manufacturers write data onto the memory chip,
which is then impossible to change. Masked ROM is extremely low cost. Companies
often use masked ROM in mass-produced devices that last for years.

The disadvantage of masked ROM is that no one can change the data on the chip.
• Programmable Read-Only Memory (PROM): These are programmable chips that you
purchase unprogrammed and program only one time. Companies use them to store
firmware and constants in source code.

“They can be used for storing serial numbers, radio configurations or some other data
that is not supposed to be changed by the user," .

Day says PROM is becoming obsolete, in part, because it requires high voltages to
program and operate. Day adds, "Most PROMs require the device manufacturer to
perform the one-time programming and (that) can be a logistical headache.” This can be
especially true for companies that buy and use the memory in their products.

22/04/2024 Embedded C Programming 9


Other memory options with features of both
volatile and non-volatile
• Electrically Erasable Programmable Read-Only Memory (EEPROM): You can erase these
chips and reprogram them through an electrical operation. Engineers often use EEPROM in a
product’s firmware or for storing firmware as they develop a product. It can be useful for
products that may need to update their firmware even after a customer purchases it. This is
still used widely,. EEPROM has a limited number of write-erase cycles—usually something like
10,000.

• Flash: Developers use flash memory in embedded systems more often than any other non-
volatile or hybrid memory. The memory is fast for a device to read and low-cost. Devices use
it for storing large files.
Like EEPROM, it is also electrically reprogrammable. But you erase and reprogram flash
memory one sector at a time, compared to byte-by-byte in EEPROM. Some System on a Chips
(SoCs) have flash memories built into them. For external storage, there are two main kinds of
flash memory:
• NAND flash: Engineers most commonly use this flash memory. It is small and often used in
USB flash drives and solid-state disks (SSDs).
• NOR flash: Faster than NAND, NOR flash is more expensive and doesn't last as long as NAND.
Engineers often use NOR flash for Execute-In-Place (XIP) code.

22/04/2024 Embedded C Programming 10


Conti..
• NVRAM, or non-volatile random access memory: This type of RAM doesn't lose data when
power is lost but can store it permanently. It is expensive but fast. Engineers use this when
startup time is crucial.
• Ferroelectric Random Access Memory (FRAM): Another type of RAM that doesn't lose data
when power is off, it is faster and offers many more write cycles and uses less power.
Engineers sometimes use it instead of EEPROM or flash memory.
• Phase Change Memory (PCM): Sometimes called PCRAM, this memory is non-volatile and
retains data when power is off. Engineers sometimes use it instead of flash memory. It has
faster write cycles and uses less power.
“PCM is a new technology that has very fast read/write performance approaching that of
SDRAM," . "And data is non-volatile for decades, if not longer."

Other types of external memory


• Engineers may also use these external memory options in an embedded system:
• SSD: Manufacturers often use these in embedded systems. Engineers build the device using
flash memory.
• Secure Digital Card (SD Card): Non-volatile memory that portable devices commonly use.

22/04/2024 Embedded C Programming 11


I/O interfacing
• As we know, keyboard and displays are used as communication channel with outside
world. Therefore, it is necessary that we interface keyboard and displays with the
microprocessor. This is called I/O interfacing. For this type of interfacing, we use latches
and buffers for interfacing the keyboards and displays with the microprocessor.
• But the main drawback of this interfacing is that the microprocessor can perform only
one function.
8279 Programmable Keyboard
• The Intel 8279 is a programmable keyboard interfacing device. Data input and display
are the integral part of microprocessor kits and microprocessor-based systems.
• 8279 has been designed for the purpose of 8-bit Intel microprocessors.
• 8279 has two sections namely keyboard section and display section.
• The function of the keyboard section is to interface the keyboard which is used as
input device for the microprocessor. It can also interface toggle or thumb switches.
• The purpose of the display section is to drive alphanumeric displays or indicator lights.
It is directly connected to the microprocessor bus.
• The microprocessor is relieved from the burden of scanning the keyboard or refreshing
the display.

22/04/2024 Embedded C Programming 12


22/04/2024 Embedded C Programming 13
Programming embedded systems in C
• We consider some important decisions that must
be made at the start of any embedded project:

 The choice of processor.


 The choice of programming language.
 The choice of operating system.

• Which processor should you use?

22/04/2024 Embedded C Programming 14


Which programming language should you use?
In order to identify a suitable language for embedded systems, we might
begin by making the following observations:
 Computers (such as microcontroller, microprocessor or DSP chips) only accept
instructions in ‘machine code’ (‘object code’). Machine code is, by definition,
in the language of the computer, rather than that of the programmer.
Interpretation of the code by the programmer is difficult and error prone.
 All software, whether in assembly, C, C++, Java or Ada must ultimately be
translated into machine code in order to be executed by the computer.
 There is no point in creating ‘perfect’ source code, if we then make use of a
poor translator program (such as an assembler or compiler) and thereby
generate executable code that does not operate as we intended.
 Embedded processors – like the 8051 – have limited processor power and very
limited memory available: the language used must be efficient.
 To program embedded systems, we need low-level access to the hardware:
this means, at least, being able to read from and write to particular memory
locations (using ‘pointers’ or an equivalent mechanism).

22/04/2024 Embedded C Programming 15


Of course, not all of the issues involved in language selection
are purely technical:

• No software company remains in business for very long if it generates new


code, from scratch, for every project. The language used must support the
creation of flexible libraries, making it easy to re-use (well-tested) code
components in a range of projects. It must also be possible to adapt complete
code systems to work with a new or updated processor with minimal difficulty.

• The language chosen should be in common use. This will ensure that you can
continue to recruit experienced developers who have knowledge of the
language. It will also mean that your existing developers will have access to
sources of information (such as books, training courses, WWW sites) which
give examples of good design and programming practice.

22/04/2024 Embedded C Programming 16


• Inevitably, therefore, we need to make compromises; there is no perfect
solution. All we can really say is that we require a language that is efficient,
high-level, gives low-level access to hardware, and is well defined. In addition
– of course – the language must be available for the platforms we wish to use.
Against all of these points, C scores well.
We can summarize C’s features as follows:
• It is ‘mid-level’, with ‘high-level’ features (such as support for functions and
modules), and ‘low-level’ features (such as good access to hardware via
pointers).
– ● It is very efficient.
– ● It is popular and well understood.
– ● Even desktop developers who have used only Java or C++ can soon understand
C syntax.
– ● Good, well-proven compilers are available for every embedded processor (8-bit
to 32-bit or more).
– ● Books, training courses, code samples and WWW sites discussing the use of the
language are all widely available.

22/04/2024 Embedded C Programming 17


A schematic representation of the BIOS/OS sandwich from a
desk-bound computer system running some word processor
software

Part of a simple Super Loop demonstration

void main(void)
{ // Prepare run function X
X_Init();
while(1) // ‘for ever’ (Super Loop)
{
X(); // Run function X()
}
}

22/04/2024 Embedded C Programming 18


How do you develop embedded software?
1. Build the hardware for the embedded system.
2. Transfer the executable code to the embedded hardware and test the
system.
• For programmers without experience of electronics, the process of
building embedded hardware is a daunting one. A typical approach used
to prototype small embedded applications is the ‘breadboard’.
• This allows the microcontroller and associated components to be
connected together, without soldering, in order to test and refine the
hardware and software design, there is now an alternative approach that
can be used by those starting out in this area:
– Create the executable code for the embedded system on a desktop PC using an
appropriate cross-compiler and related tools (as above).
– Use a software simulator (running on the desktop PC) to test the code.
– Repeat Step 1 and Step 2, as necessary, until the software operates as required.

22/04/2024 Embedded C Programming 19


• There are two fundamental differences between the embedded
systems we are concerned with in desktop computer systems:
1. The vast majority of embedded systems are required to run
only one program: this program will start running when the
microcontroller is powered up, and will stop running when the
power is removed.

2. Many of the facilities provided by the modern desktop OS –


such as the ability to display high-resolution graphics, printing
facilities and efficient disk access – are of little value in
embedded systems, where sophisticated graphics screens,
printers and disks are generally unavailable.

3. As a consequence, the simplest architecture in an embedded


system is typically a form of ‘Super Loop’

22/04/2024 Embedded C Programming 20


Need for RTOS
• Real-time operating systems (RTOS) are used in environments where a large
number of events, mostly external to the computer system, must be accepted
and processed in a short time or within certain deadlines. such applications
are industrial control, telephone switching equipment, flight control, and real-
time simulations.
• With an RTOS, the processing time is measured in tenths of seconds. This
system is time-bound and has a fixed deadline. The processing in this type of
system must occur within the specified constraints. Otherwise, This will lead to
system failure.
• Examples of real-time operating systems are airline traffic control systems,
Command Control Systems, airline reservation systems, Heart pacemakers,
Network Multimedia Systems, robots, etc.

22/04/2024 Embedded C Programming 21


Hard Real-Time Operating System:

• These operating systems guarantee that critical tasks


are completed within a range of time. For example, a
robot is hired to weld a car body.

• If the robot welds too early or too late, the car


cannot be sold, so it is a hard real-time system that
requires complete car welding by the robot hardly on
time., scientific experiments, medical imaging
systems, industrial control systems, weapon systems,
robots, air traffic control systems, etc.
22/04/2024 Embedded C Programming 22
Soft real-time operating system
• This operating system provides some relaxation in the time
limit. For example – Multimedia systems, digital audio systems,
etc. Explicit, programmer-defined, and controlled processes are
encountered in real-time systems.
• A separate process is changed by handling a single external
event. The process is activated upon the occurrence of the
related event signaled by an interrupt.
• Multitasking operation is accomplished by scheduling processes
for execution independently of each other. Each process is
assigned a certain level of priority that corresponds to the
relative importance of the event that it services.
• The processor is allocated to the highest-priority processes. This
type of schedule, called, priority-based preemptive scheduling is
used by real-time systems.
22/04/2024 Embedded C Programming 23
Firm Real-time Operating System:
RTOS of this type have to follow deadlines as well. In spite of its small
impact, missing a deadline can have unintended consequences, including a
reduction in the quality of the product.

Example: Multimedia applications.

Deterministic Real-time operating System:


Consistency is the main key in this type of real-time operating system. It
ensures that all the task and processes execute with predictable timing all the
time, which make it more suitable for applications in which timing accuracy is
very important.

Examples: INTEGRITY, PikeOS.

22/04/2024 Embedded C Programming 24


Advantages
• Maximum consumption: Maximum utilization of devices and systems. Thus
more output from all the resources.

• Task Shifting: Time assigned for shifting tasks in these systems is very less. For
example, in older systems, it takes about 10 microseconds. Shifting one task to
another and in the latest systems, it takes 3 microseconds.

• Focus On Application: Focus on running applications and less importance to


applications that are in the queue.

• Real-Time Operating System In Embedded System: Since the size of programs


is small, RTOS can also be embedded systems like in transport and others.

• Error Free: These types of systems are error-free.

• Memory Allocation: Memory allocation is best managed in these types of


systems.
22/04/2024 Embedded C Programming 25
Disadvantages
• Limited Tasks: Very few tasks run simultaneously, and their concentration is very
less on few applications to avoid errors.

• Use Heavy System Resources: Sometimes the system resources are not so good
and they are expensive as well.

• Complex Algorithms: The algorithms are very complex and difficult for the designer
to write on.

• Device Driver And Interrupt signals: It needs specific device drivers and interrupts
signals to respond earliest to interrupts.

• Thread Priority: It is not good to set thread priority as these systems are very less
prone to switching tasks.

• Minimum Switching: RTOS performs minimal task switching.


22/04/2024 Embedded C Programming 26
Real Time Operating Systems – Architecture

• A real time OS is a program that schedules execution in a timely manner, manages


system resources, provides a consistent foundation for developing application code.
• RTOS is a multi-tasking OS intended for real time applications to produce high and
guaranteed throughput on desired time.
• RTOS consists of kernel, which is the core supervisory software that provides minimal
logic, scheduling and resource management algorithm.
• RTOS can be a combination of various modules including file system, network
protocols, device drivers, device I/Os and other components required for particular
applications. Although many RTOS can scale up or down to meet application
requirements.
• The OS generally consist of two parts – Kernel space and User space. Kernel is the
smallest and central component of an OS. Its service include managing memory and
devices and also to provide an interface for software application to use the resources.
• Additional services such as managing protection of programs and multi-tasking may
be included depending on the architecture of OS.There are three broad categories of
kernel systems – Monolithic,Micro Kernel and Hybrid Kernel.

22/04/2024 Embedded C Programming 27


RTOS

22/04/2024 Embedded C Programming 28


22/04/2024 Embedded C Programming 29
KERNEL
• Monolithic Kernel : It runs all basic system services (MMU, interrupt handling, I/O
communication, file system etc ) in kernel space.
• Micro kernel : It runs only basic process communication and I/O control. The other
system services (file system, networking etc) resides in user space. Thus micro kernel
provides a smaller set of simple hardware abstractions.
• Hybrid Kernel : Hybrid Kernel is the combination of monolithic kernel and micro kernel.
• Minimalist kernel design is suitable for RTOS. All IO requires use of communication
through kernel,thus it is important that kernel overhead to minimum. Micro kernel are
minimal kernels which offer kernel services with minimum overheads.
• Kernel Objects:
The various kernel objects are Tasks, Task Scheduler, Interrupt Service Routines,
Semaphores, Mutexes, Mailboxes, Message Queues, Pipes, Timers etc.
Scheduler
The scheduler is the heart of every kernel. A scheduler provides the algorithms
needed to determine which task executes when.
schedulable entities: It is a kernel object that can compete for execution time on a
system based on predefined scheduling algorithm. Tasks and process are examples of
schedulable entities found in most kernel.
22/04/2024 Embedded C Programming 30
22/04/2024 Embedded C Programming 31
RTOS: Multiple tasks and Processes
• An RTOS becomes essential when there is processing and
servicing of multiple tasks and multiple devices with real time
constraints
OS and RTOS
• Real-Time Operating system (RTOS) is the operating system that
provides facilities for satisfying the real-time requirements.
• It also allocates resources by considering real time constraints
and with the help of real time algorithms it allocates resources
but in General operating system (OS) allocates resources based
on the criteria like fairness.
• It also allocates the process without regards to time which can
easily cause processes to miss their deadlines.
22/04/2024 Embedded C Programming 32
Task and process
• A process is a single execution of a program. If the same
process runs at different times, it is nothing but two
different processes are created.

• Every process has its own state and each state include
registers and memory. In many OSs each process is kept in a
separate address space by the memory management unit.

• Threads are processes, which will share same address


space, while a task is composed of several processes or
threads that have their own address space.

22/04/2024 Embedded C Programming 33


Release time and deadline:
• Depending on the application, processes will have timing
requirements.
• A scheduling policy which defines how processes are selected for
promotion from the ready state to the running state.
• It must define the timing requirements that it uses whether the
schedule is valid or not. The timing requirements are mainly divided
into release time and deadline.

Aperiodic and periodic :


• The period of a process is the time between successive executions.
Periodic processes have regular arrival times and hard deadlines.
• Aperiodic process have irregular arrival times and either soft or
hard deadlines. An aperiodic process is initiated by an event such as
external data arriving or data computed by another process.

22/04/2024 Embedded C Programming 34


Process Rate : It is the inverse of its period.
Release time – It is the time at which the process becomes
ready to execute. For aperiodic,the process is initiated by an event.
The release time for aperiodic is measured from that event
onwards.

In periodic process the release time will be determined in


two ways. For simpler system, the process will be ready at the start
of the period. In sophisticated systems , the release time will be set
at the arrival of data.

Deadline– It is the time at which the process must finish. For


aperiodic process the deadline is measured from the release time.
In case of periodic process it may occur at some time other than
the end of the period.
22/04/2024 Embedded C Programming 35
• Dead line frequency will occur in two ways i.e.
periodic and aperiodic.
• There are three types of deadlines as follows:
● Hard: failure to meet deadline causes system
failure.
● Soft: failure to meet deadline causes
degraded response.
● Firm: late response is useless but some late
responses can be tolerated.

22/04/2024 Embedded C Programming 36


Timing requirements on processes:
• In a multirate system each process executes at its own distinct rate. The most
common case for periodic processes is for the initiation interval to be equal to
the period.

• However, the overlapped execution of different instances of processes allows


the initiation interval to be less than the period.

• The various execution instances of program P1 have been subscripted to


distinguish their initiation time. In this example, there are four instances of the
processes given to four different processors with initiation interval is equal to
one fourth of the period. The fifth instance of the process is assigned back to
CPU 1.

• There will be a possibility of process initiation rate less than the period even in
case of single-CPU systems. If the process execution time is significantly less
than the period, the multiple copies of a program can be initiated in slightly
offset times.
22/04/2024 Embedded C Programming 37
A sequence of processes with high initiation rate

22/04/2024 Embedded C Programming 38


Process State and Scheduling

 The process will be in any one state. The states are


ready, executing and waiting states.
 Ready- A process goes into the ready state when it
receives its required data and when it enters a new
period.
 Waiting-A process goes into the waiting state when it
needs data that it has not yet received or when it has
finished all its work for the current period.
 Executing-A process can go into the executing state
only when it has all its data, that is ready to run.
22/04/2024 Embedded C Programming 39
22/04/2024 Embedded C Programming 40
Task
• A task is like a process or thread in an OS. In RTOS, task term is used for the
process. It consists of executable program (codes), state of which is controlled by
OS.
• Each task will have the task control block (TCB). The TCB will have data structure
information using which the OS controls the task state. The task will be any one of
these states – idle, ready, running, and blocked or finished .
The states are as follows:
1. Idle state
2. Ready State
•Running state •Blocked (waiting) state •Delayed for a preset period
3. Idle state- task has been created and memory is allotted to its structure, if it is not ready,
then task is not scheduled by kernel.
4. A task, also called a thread, is a simple program that thinks it has the CPU all to itself. The
design process for a real-time application involves splitting the work to be done into tasks
responsible for a portion of the problem.
• Each task is assigned a priority, its own set of CPU registers and its own stack area.
• In the specified time constraint, system must produce its correct output. If system
fail to meet the specified output, then the system is fail or quality decreases

22/04/2024 Embedded C Programming 41


Ready State – The created task is ready and is schedulable by the kernel but not running at present
as another higher priority task is scheduled to run and gets the system resources at this instance.

Run state-Executing the codes and getting the system resources at this instance. It will run till it
needs some IPC (input) or wait for an event or till it gets preempted by another higher priority task
than this one.

Blocked state- Execution of task codes suspends after saving the needed parameters into its
context. It needs some IPC (input) or it needs to wait for an event or wait for higher priority task to
block to enable running after blocking.

Deleted Task─ The created task has memory de-allotted to its structure. It frees the memory. Task
has to be re-created.

22/04/2024 Embedded C Programming 42


Task control Block

22/04/2024 Embedded C Programming 43


Task Characteristics for a single CPU in a system:

• Task is an independent one and it cannot call another task.


Each task is identified by a TCB. Each task has an ID just as
each function has a name.
• The ID, task ID is a byte if it is between 0 and 255. ID is also an
index of the task. Each task may have a priority parameter.
• If the priority is between 0 and 255, it is represented by a
byte. Multitasking operations are done by context switching
between the various tasks and it is performed by OS
Scheduler.
• Each task must be either a reentrant routine or it must have a
way to solve the shared data problem. A function is reentrant
if it can be invoked while the process is already executing.

22/04/2024 Embedded C Programming 44


RTOS Task Context Switching
• The scheduling algorithms of real-time operating systems (RTOS), we stated that
they can run tasks in such a way that leaves the impression of a multitasking
behavior. This is achieved by giving the RTOS the capability to interrupt a
currently executing task and to start executing another one.
• At some point in time, the interrupted task should resume its operation. When
that occurs the microprocessor must be put in the same state as it was the last
time the interrupted task was being executed. This is done using a mechanism
called context switching.
• Each task uses a specific set of resources when it is executing. These include CPU
registers, system status flags, access to memory (heap, stack), etc.. All these
resources are what we call a task state (aka task execution context).
• Context switching is a process of saving the task state (with the intention for it
to be restored at a later point in time) and switching it with another already
saved task state.
• Task context switching guarantees that each task sees the CPU as its own. This
mimics the behavior of real multitasking, where each task should have its own
dedicated CPU.
22/04/2024 Embedded C Programming 45
Context Switching Basics
• Context switching is not a mechanism used only in real-time operating
systems. Every microprocessor uses some form of context switching
when an exception occurs and a service routine has to be executed.
• In most modern CPU architectures the exception context switching is
usually handled partly by the hardware (some registers are
automatically saved) and partly by the compiler-generated code.
• Task context switching in real-time operating systems is implemented
as part of their source code.
• Although it is handled using software, context switching is hardware
dependent, as the resources needed may differ from one
microprocessor to another.
• This means that the code for task context switching must be ported
for each CPU architecture.

22/04/2024 Embedded C Programming 46


Memory Allocation
• RTOS kernel objects such as tasks, semaphores, etc. can
be allocated dynamically or statically (during
compilation). For task dynamic allocation, the RTOS
usually provides different schemes. For example:
• Allocating the space for the task once, and never freeing
it
• Once a task has completed its operation the space
allocated for it on the heap is freed
• The most suitable dynamic allocation scheme depends
on the application complexity and the resource
constraints of the embedded system.

22/04/2024 Embedded C Programming 47


RTOS task memory structure and placement in
heap memory

22/04/2024 Embedded C Programming 48


• Each created task should have a task control
information memory area and a stack memory
area. This is shown on the left side of Task control
information area has a fixed size and it may include:
 task’s name (a pointer to the C function implementing
the task)
 debug information
 the size of the task’s stack
 top of the stack pointer (address)
 task priority

22/04/2024 Embedded C Programming 49


Context Switching Flow
• As a final step let’s analyze a context switching flow using an example
involving two tasks – Task 1 and Task 2.
• Task 1 is currently running, while Task 2 which has a higher priority has just
become ready to run. This situation will require a context switch, and the
steps involved are the following:
• Task 1 is executing
• RTOS tick exception is generated
• The hardware automatically saves some registers onto the current task’s
stack. This depends on the CPU architecture.
– ARM Cortex-M automatically saves R0-R3, R12, LR(R14), return address and xPSR.
• An RTOS handler function for the tick exception stores any additional
registers that are part of the current task state (see Figure).
– For ARM Cortex-M this handler function should save registers R4-R11, R14.
• The stack pointer value (address of the last register pushed into the stack) is
saved in the task control information area.
22/04/2024 Embedded C Programming 50
CONTI…
• The handler checks if there is a higher priority task waiting to be run, in
our case, this is Task 2. The CPU stack pointer register is loaded with the
stack pointer value stored in Task 2’s information control memory area.
• We are still in the RTOS handler function for the tick exception, but now
the stack pointer is pointing to the last entry in Task 2 stack area.
• The context that is saved by this handler upon entry (step 4) into the
stack is now being restored. Note that the context for Task 1 was saved
upon exception entry, but now we are restoring the context for Task 2.
• When exiting the handler, the hardware automatically restores any data
saved during step 3 of the flow. Note again that the hardware is restoring
the context for Task 2, as the stack pointer is loaded with Task 2’s stack
address (step 6).
• Now we are out of the exception handling routine. The program will
continue regular execution but not on the task that was interrupted (Task
1), instead Task 2 will be executed. The context switch is complete!

22/04/2024 Embedded C Programming 51


Stack content before and after saving of
task state (context)

22/04/2024 Embedded C Programming 52


Thank You

22/04/2024 Embedded C Programming 53

You might also like