EIOT Unit-2
EIOT Unit-2
Memory And I/O Devices Interfacing – Programming Embedded Systems in C – Need For RTOS – Multiple
Tasks and Processes – Context Switching – Priority Based Scheduling Policies.
2.1 Memory And I/O Devices Interfacing
2.1.1. Memory Interfacing
2.1.2. I/O interfacing
2.1.3. Types of Computer Architecture
2.1.4. 8051 Microcontroller Memory Organization
2.1.4.1 Program Memory (ROM) of 8051 Microcontroller
2.1.4.2 Data Memory (RAM) of 8051 Microcontroller
2.1.5 Interfacing External Memory with 8051 Microcontroller
2.2 Programming Embedded Systems in C
2.2.1 Embedded System Programming
2.2.2 Basics of Embedded C Program
2.2.3 Programming Embedded Systems
2.2.4 Factors for Selecting the Programming Language
2.2.5 Embedded System and Its Real Time Applications
2.2.6 Components of Embedded System
2.2.7 Introduction to Embedded C Programming Language
2.3 Need For RTOS
2.3.1 What is an RTOS?
2.3.2 RTOS scheduling
2.3.3 The use of RTOS in embedded designs
2.3.4 Introducing the Zephyr RTOS
2.3.5 Real-time operating system (RTOS): Components, Types, Examples
2.3.6 Terms used in RTOS
2.3.7 Components of RTOS
2.3.8 Features of RTOS
2.3.9 Difference between in GPOS and RTOS
2.3.10 Types of Real Time Operating Systems
2.3.11 Advantages of Real Time Operating System (RTOS)
2.3.12 Disadvantages of Real Time Operating System (RTOS)
2.3.13 Comparison of Regular and Real-Time operating systems
2.4 Multiple Tasks and Processes
2.5 Context Switching
2.6 Priority Based Scheduling Policies.
Prepared by : T.Manochandar,AP/ECE
Explain in detail about Memory and I/O Interfacing.
2
Differences between microprocessor and microcontroller
The main difference can be stated as on-chip memory i.e., a Microcontroller has both Program
Memory (ROM) and Data Memory (RAM) on the same chip (IC), whereas a Microprocessor
hasto be externally interfacing with the memory modules.
Hence, it is clear that the memory is an important part of the 8051 Microcontroller Architecture
(for that matter, any Microcontroller).
So, it is important for us to understand the 8051 Microcontroller Memory Organization i.e.,
how memory is organized, how the processor accesses each memory and how to interface
external memory with 8051 Microcontroller.
2.1.3 Types of Computer Architecture
Basically, Microprocessors or Microcontrollers are classified based on the two types of Computer
Architecture: Von Neumann Architecture and Harvard Architecture.
Harvard Architecture
Harvard Architecture, in contrast to Von Neumann Architecture, uses separate memory for
Instruction (Program) and Data.
Since the Instruction Memory and Data Memory are separate in a Harvard Architecture, their
signal paths i.e., buses are also different and hence, the CPU can access both Instructions and
Data at the same time.
Almost all Microcontrollers, including 8051 Microcontroller implement Harvard Architecture.
3
Fig:2.3 Harvard Architecture
2.1.4 8051 Microcontroller Memory Organization
The 8051 Microcontroller Memory is separated in Program Memory (ROM) and Data Memory
(RAM).
The Program Memory of the 8051 Microcontroller is used for storing the program to be
executed i.e., instructions.
The Data Memory on the other hand, is used for storing temporary variable data and
intermediate results.
8051 Microcontroller has both Internal ROM and Internal RAM. If the internal memory is
inadequate, you can add external memory using suitable circuits.
In 8051 Microcontroller, the code or instructions to be executed are stored in the Program
Memory, which is also called as the ROM of the Microcontroller.
The original 8051 Microcontroller by Intel has 4KB of internal ROM.
Some variants of 8051 like the 8031 and 8032 series doesn’t have any internal ROM (Program
Memory) and must be interfaced with external Program Memory with instructions loaded in it.
If the address space i.e., the program addresses exceed this value, then the CPU will
automatically fetch the code from theexternal Program Memory.
For this, the External Access Pin (EA Pin) must be pulled HIGH i.e., when the EA Pin is high,
the CPU first fetches instructions from the Internal Program Memory in the address range of
0000H to 0FFFFH and if the memory addresses exceed the limit, then the instructions are
fetched from the external ROM in the address range of 1000H to FFFFH.
To address the register by name, first the corresponding Bank must be selected. In order to select
the bank, we have to use the RS0 and RS1 bits of the Program Status Word (PSW) Register
(RS0and RS1 are 3rd and 4th bits in the PSW Register).
When addressing the Register using its address i.e., 12H for example, the corresponding Bank
may or may not be selected. (12H corresponds to R2 in Bank2).
The next 16B of the RAM i.e., from 20H to 2FH are Bit – Addressable memory locations.
There are totally 128 bits that can be addressed individually using 00H to 7FH or the entire byte
can be addressed as 20H to 2FH.
6
2.1.5 Interfacing External Memory with 8051 Microcontroller
It is always good to have an option to expand the capabilities of a Microcontroller, whether it is
in terms of Memory or IO or anything else.
Such expansion will be useful to avoid design throttling. We have seen that a typical 8051
Microcontroller has 4KB of ROM and 128B of RAM (most modern 8051 Microcontroller
variants have 8K ROM and 256B of RAM).
The designer of an 8051 Microcontroller based system is not limited to the internal RAM and
ROM present in the 8051 Microcontroller.
There is a provision of connecting both external RAM and ROM i.e., Data Memory and
Program.
The reason for interfacing external Program Memory or ROM is that complex programs written
in high – level languages often tend to be larger and occupy more memory.
Another important reason is that chips like 8031 or 8032, which doesn’t have any internal ROM,
have to be interfaced with external ROM.
A maximum of 64KB of Program Memory (ROM) and Data Memory (RAM) each can be
interface with the 8051 Microcontroller.
The following image shows the block diagram of interfacing 64KB of External RAM and 64KB of
External ROM with the 8051 Microcontroller.
7
2.2 Embedded C Programming with Keil Language
Embedded C is most popular programming language in software field for developing electronic
gadgets.
Each processor used in electronic system is associated with embedded software.
Embedded C programming plays a key role in performing specific function by the processor.
In day-to-day life we used many electronic devices such as mobile phone, washing machine,
digital camera, etc.
These all device working is based on microcontroller that are programmed by embedded C.
In embedded system programming C code is preferred over other language. Due to the following
reasons:
o Easy to understand
o High Reliability
o Portability
o Scalability
Let's see the block diagram representation of embedded system programming:
Basic Declaration
Let's see the block diagram of Embedded C Programming development:
8
Fig: 2.10 Block diagram of Embedded C Programming
Function is a collection of statements that is used for performing a specific task and a collection
of one or more functions is called a programming language.
Every language is consisting ofbasic elements and grammatical rules.
The C language programming is designed for function with variables, character set, data types,
keywords, expression and so on are used for writing a C program.
As compared to above the embedded programming in C is also have some additional features
like data types, keywords and header file etc is represented by
#include<microcontroller name.h>
Embedded C is one of the most popular and most commonly used Programming Languages in
the development of Embedded Systems.
So, we will see some of the Basics of Embedded C Program and the Programming Structure of
Embedded C.
9
2.2.2.1 What is an Embedded System?
An Embedded System is a combination of Hardware and Software.
My desktop computer also has hardware and software.
Does that mean a desktop computer is also an Embedded System? NO. A desktop computer is
considered a general- p u r p o s e system as it can do many different tasks that too
simultaneously.
Some common tasks are playing videos, working on office suites, editing images (or videos),
browsing the web, etc.
In order to get wireless internet connectivity on our mobile phones and laptops, we often use
routers.
The task of a wireless router is to take the signal from a cable and transmit it wirelessly. And
take wirelessdata from the device (like a mobile) and send it through the cable.
We use washing machines almost daily but wouldn’t get the idea that it is an embedded system
consisting of a Processor (and other hardware as well) and software.
Embedded Systems can not only be stand-alone devices like Washing Machines but also be
apart of a much larger system.
10
An example for this is a Car.
A modern day Car has several individual embedded systems that perform their specific tasks
with the aim of making a smooth and safe journey.
Some of the embedded systems in a Car are Anti-lock Braking System (ABS), Temperature Monitoring
System, Automatic Climate Control, Tire Pressure Monitoring System, Engine Oil Level Monitor, etc.
All these devices have one thing in common: they are programmable i.e., we can write a program(which
is the software part of the Embedded System) to define how the device actually works.
Embedded Software or Program allow Hardware to monitor external events (Inputs / Sensors)
and control external devices (Outputs) accordingly.
During this process, the program for an Embedded System may have to directly manipulate the
internal architecture of the Embedded Hardware (usually the processor) such as Timers, Serial
Communications Interface, Interrupt Handling, and I/O Ports etc.
From the above statement, it is clear that the Software part of an Embedded System is equally
important as the Hardware part. There is no point in having advanced Hardware Components
with poorly written programs (Software).
There are many programming languages that are used for Embedded Systems like Assembly
(low-level Programming Language), C, C++, JAVA (high-level programming languages),
VisualBasic, JAVA Script (Application level Programming Languages), etc.
In the process of making a better embedded system, the programming of the system plays a vital
role and hence, the selection of the Programming Language is very important.
Size: The memory that the program occupies is very important as Embedded
Processors like Microcontrollers have a very limited amount of ROM (Program
Memory).
Speed: The programs must be very fast i.e., they must run as fast as possible.
Thehardware should not be slowed down due to a slow running software.
Portability: The same program can be compiled for different processors.
Ease of Implementation
11
Ease of Maintenance
Readability
There are other high-level programming languages that offered the above mentioned features but
none were close to C Programming Language.
12
Fig: 2.13 Embedded Systems
2.2.6 Components of Embedded System
An Embedded System consists of four main components. They are the Processor (Microprocessor or
Microcontroller), Memory (RAM and ROM), Peripherals (Input and Output) and Software (main
program).
Processor: The heart of an Embedded System is the Processor. Based on the functionality of the
system, the processor can be anything like a General Purpose Processor, a single purpose processor,
an Application Specific Processor, a microcontroller or an FPGA.
Memory: Memory is another important part of Embedded System. It is divided in to RAM and ROM.
Memory in an Embedded System (ROM to be specific) stores the main program and RAM stores the
program variables and temporary data.
Peripherals: In order to communicate with the outside world or control the external devices, an
Embedded System must have Input and Output Peripherals. Some of these peripherals include Input /
Output Ports, Communication Interfaces, Timers and Counters, etc.
Software: All the hardware work according to the software (main program) written. Softwarepart of
an Embedded System includes initialization of the system, controlling inputs and outputs, error handling
etc.
NOTE: Many Embedded Systems, usually small to medium scaled systems, generally consists of a
Microcontroller as the main processor. With the help of a Microcontroller, the processor, memory and
few peripherals will be integrated in to a single device.
13
The C Programming Language became so popular that it is used in a wide range of applications
ranging from Embedded Systems to Super Computers.
The extension in Embedded C from standard C Programming Language include I/O Hardware
Addressing, fixed point arithmetic operations, accessing address spaces, etc.
C Programming Language is generally used for developing desktop applications, whereas Embedded
C is used in the development of microcontroller based applications.
14
Data Types in Embedded C
Data Types in C Programming Language (or any programming language for that matter) help us
declaring variables in the program.
There are many data types in C Programming Language like signed int, unsigned int, signed
char, unsigned char, float, double, etc. In addition to these there few more data types in
Embedded C.
The following are the extra data types in Embedded C associated with the Keil’s Cx51 Compiler.
2.2.7.2.6 bit
2.2.7.2.7 sbit
2.2.7.2.8 sfr
2.2.7.2.9 sfr16
The following table shows some of the data types in Cx51 Compiler along with their ranges.
Data Type Bits Range
(Bytes)
bit 1 0 or 1 (bit addressable part of RAM)
signed int 16 (2) -32768 to +32767
unsigned int 16 (2) 0 to 65535
signed char 8 (1) -128 to +127
unsigned 8 (1) 0 to 255
float 32 (4) ±1.175494E-38 to ±3.402823E+38
double 32 (4) ±1.175494E-38 to ±3.402823E+38
sbit 1 0 or 1 (bit addressable part of RAM)
sfr 8 (1) RAM Addresses (80h to FFh)
sfr16 16 (2) 0 to 65535
15
Infinite Loop .......... Like while(1) or for(;;)
Statements . . . . .
….
….
}
2.2.7.2.9.7 ........................ Function Definitions Defining the Functions
{
Local Variables .......... Local Variables confined to this Function
Statements . . . . .
….
….
}
Before seeing an example with respect to 8051 Microcontroller, we will first see the different
components in the above structure.
There are two ways you can write comments: one is the single line comments denoted by // and the
other is multiline comments denoted by /*….*/.
Global Variables: Global Variables, as the name suggests, are Global to the program i.e., they can be
accessed anywhere in the program.
Local Variables: Local Variables, in contrast to Global Variables, are confined to their respective
function.
Main Function: Every C or Embedded C Program has one main function, from where the execution of
the program begins.
16
Example of Embedded C Program
The following image shows the circuit diagram for the example circuit. It contains an 8051 based
Microcontroller (AT89S52) along with its basic components (like RESET Circuit, Oscillator Circuit,
etc.) and components for blinking LEDs (LEDs and Resistors).
In order to write the Embedded C Program for the above circuit, we will use the Keil C
Compiler. This compiler is a part of the Keil µVision IDE. The program is shown below.
17
/* Calling Delay function with Function parameter as 1000.
* This will cause a delay of 1000mS i.e. 1 second */
P1 = 0x00; // Making PORT1 Pins LOW i.e. LEDs are OFF.
delay(1000);
}
}
void delay (int d) // Delay Function Definition
{
It is very cheap and easily available in variety of shape, color and size. The LEDs are also used in
designing of message display boards and traffic control signal lights etc.
Consider the Proteus Software based simulation of LED blinking using 8051 Microcontroller is
shown below:-
18
In above Proteus based simulation the LEDs are interfaced to the PORT0 of the 8051
microcontr
oller.
Let's see the Embedded C Program for generating the LED output sequence as shownbelow:
00000001
00000010
00000100.....
.... And so on up to 10000000.#include<reg51.h>
void main()
{
unsigned int k; unsigned char l,b;while(1)
{
P0=0x01;b=P0;
for(l-0;l<3000;l++);for(k=0;k<8;k++)
{
b=b<<1;
19
P0=b;
}
}
}
Consider the Embedded C Program for generating the LED output sequence as shownbelow
is:-
00000001
00000011
00000111.....
.... And so on up to 11111111.
#include<reg51.h>void main()
{
unsigned int i; unsigned char j,b;while(1)
{
P0=0x01;
b=P0;
for(j-
0;j<3000;j++)
;
for(j=0;j<8;j+
+)
{
bb=b<<1;b=0x01; P0=b;
}
}
}
Displaying Number on 7-Segment Display using 8051 Microcontroller
Electronic display used for displaying alphanumeric character is known as 7-Segment display itis used
in many systems for displaying the information.
It is constructed using eight LEDs which are connected in sequential way so as to display digits from 0
to 9, when certain combinations of LEDs are switched on. It displays only one digit at a time.
Consider the Proteus software based simulation of displaying number on 7-segment display using
8051 microcontroller is:-
20
Consider the program for displaying the number from '0 to F' on 7-segment display is:- 10s
#include<reg51.h>
sbit a= P3^0;sbit x= P3^1;
sbit y=
P3^2;
sbit z=
P3^3;
void
main()
{
unsigned char m[10]={0?40,0xF9,0?24,0?30,0?19,0?12,0?02,0xF8,0xE00,0?10};
unsigned int i,j;a=x=y=z=1; while(1)
{
for(i=0;i<10;i++)
{
P2=m[i];
for(j=0;j<60000;j++);
}
}
}
Consider the program for displaying numbers from '00 to 10' on a 7segment display is:-
#include<reg51.h>sbit x= P3^0;
sbit y= P3^1;
void display1();
21
void display2();void delay(); void main()
{
unsigned char m[10]={0?40,0xF9,0?24,0?30,0?19,0?12,0?02,0xF8,0xE00,0?10};
unsigned int i,j;ds1=ds2=0; while(1)
{
for(i=0,i<20;i++)display1(); display2();
}
}
void display1()
{
x=1;
y=0;
P2=m
[ds1];
delay(
);
x=1;
y=0;
P2=m
[ds1];
delay(
);
}
void display2()
{
ds1++;
if(ds1>=10)
{
ds1=0; ds2++; if(ds2>=10)
{
ds1=ds2=0;
}
}
}
void delay()
{
unsigned int k;
22
for(k=0;k<30000;k++);
}
A real-time system is any information processing system which has to respond to externally
generated input stimuli within a finite and specified period.
A real time system is NOT a system that runs quickly. Real time system meets the temporal
constraints.
Examples of temporal constraints are as follows :
a. Few milliseconds for radar systems.
b. One second for machine-man interfaces (in an aircraft).
c. Hours for some chemical reactions.
d. 24 hours for the weather forecast.
e. Several months or years for some space crafts.
23
Real time system is an example of a general purpose operating system.
Sensors are used to bring the data in computer.
Computers analyze the data and possibly regulate controls for the modification of seniors input.
Real-time systems are those systems in which the overall correctness of the system depends on
both the functional correctness and the timing correctness.
Real time systems also have a substantial knowledge of the system it controls and the applications
running on it. These are deadline dependent.
A RTS is any information processing system that has to respond to externally generated signal
within a finite and specified period.
A RTS is a computer system where the correct functioning of the system depends on the results
produced and the time at which they are produced.
24
RTOS generally contains a real-time kernel and other higher-level services such as file
management, protocol stacks a graphical user interface and other components. Most additional
services revolve around I/0 devices.
Explain the characteristics and classification of RTOS.
Characteristics of RTOS
RTOS are characterized by these main features
1. Determinism
2. Responsiveness
3. User control
4. Reliability
1. Determinism: Operations are performed at fixed, predetermined times or within predetermined
time intervals.
2. Responsiveness: How long, after acknowledgment, the operating system takes to service the
interrupt. It includes the time to begin execution of the Interrupt Service Routine (ISR). If a
context switch is necessary, the delay is longer than an ISR executed within the context of the
current process.
3. User control: User should be able to,
a. Specify paging or process swapping.
b. Decide which processes must reside in main memory.
c. Establish the rights of processes.
d. Fine-gained control over task priorities.
e. Select algorithms for disks scheduling.
4. Reliability: Real time system must be reliable. Reliability means that system should not fail.
The mean time between the failures should be very high.
5. Fail-soft operation: It is ability of a system to fail in such a way as to preserve as much
capability and data as possible.
Classification of Real-time Systems
Real time systems are of clock based or event based.
Interactive is one more category of real time system.
Clock-based system: Synchronization between the external processes and internal actions
(tasks) carried out by the computer is defined in terms of the actual time delay.
Event-based system: The relationship between the actions in the computer and the system is
defined in terms of the status of events.
25
Interactive system: The relationship between the actions in the computer and the system is
much more loosely defined.
periodic task i .
If a job for a periodic task i arrives at time t, then the next job of task i must arrive at t i .
3. Interactive systems:
The system responds at a time determined by the internal state of the computer and without any
reference to the environment.
Interactive systems: The combination of clock based system and event based system which
gives the importance of average execution time of the task.
This covers the systems like automatic teller machine, reservation system for hotels, etc.
This system receives the input from the plant or operator and initiates the task and executes
within the average response time.
For example
if you want draw cash from ATM when you put your card then it processes the task of
giving the money out.
In this case the response time depends on the network traffic and internal processing
time and it does not bother about other atmospheric changes.
27
A system is called a hard real-time
o if tasks must finish execution before their deadlines, or
o if messages always can be delivered within a specified time interval.
Hard real-time is often associated with safety critical applications.
A failure (e.g. missing a deadline) can lead to loss of human life or severe economic damage.
Missing a deadline may be catastrophic. Critical deadline is called a hard deadline.
Hard real time means strict about adherence to each task deadline.
When an event occurs, it should be serviced within the predictable time at all times.
The preemption period for the hard real time task in worst case should be less than a few
seconds.
Automobile engine control system and antilock brake are the examples of hard real time
systems.
Processes can have several different types of timing requirements imposed on them by the
application.
The timing requirements on a set of processes strongly influence the type of scheduling.
A scheduling policy must define the timing requirements that it uses to determine whether a
schedule is valid.
Figure 2.14 illustrates different ways in which two important requirements on processes can be
defined: release time and deadline.
28
The release time is the time at which the process becomes ready to execute; this is not necessarily
the time at which it actually takes control of the CPU and starts to run.
An aperiodic process is by definition initiated by an event, such as external data arriving or data
computed by another process.
The release time is generally measured from that event, although the system may want to make the
process ready at some interval after the event itself.
For a periodically executed process, there are two common possibilities.
o In simpler systems, the process may become ready at the beginning of the period.
o In more sophisticated systems, such as those with data dependencies between
processes.
A deadline specifies when a computation must be finished.
The deadline for an aperiodic process is generally measured from the release time.
The deadline for a periodic process may in general occur at some time other than the end of the
period.
Some scheduling policies make a simple assumption that the deadline occurs at the end of the
period.
29
The process’s rate is the inverse of its period.
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, pipelined execution of processes allows the initiation interval to be less than the period.
Figure 2.15 illustrates process execution in a system with four CPUs.
The various execution instances of program P1 have been subscripted to distinguish their initiation
times. In this case, the initiation interval is equal to one fourth of the period.
It is possible for a process to have an initiation rate less than the period even in single- CPU
systems.
Even if the modules are functionally correct, their improper behavior in timing can introduce major
execution errors.
Application Example 2.15 describes a timing problem in space shuttle software that caused the
delay of the first launch of the shuttle.
The data dependencies must form a directed acyclic graph (DAG) - a cycle in the data
dependencies is difficult to interpret in a periodically executed system.
A set of processes with data dependencies is known as a task graph.
30
Some of the component of the task graph is considered (a set of nodes connected by data
dependencies) as a task and the complete graph as the task set.
The figure also shows a second task with two processes. The two tasks ({P1, P2, P3, P4}and {P5,
P6}) have no timing relationships between them.
Communication among processes that run at different rates cannot be represented by data
dependencies
Because, there is no one-to-one relationship between data coming out of the source process and
going into the destination process.
Yet, communication among processes of different rates is very common.
Figure 2.16 illustrates the communication required among three elements of an MPEG audio/video
decoder.
Data come into the decoder in the system format, which multiplexes audio and video data.
The system decoder process demultiplexes the audio and video data and distributes it to the
appropriate processes.
Multirate communication is necessarily one way - for example, the system process writes data to
the video process, but a separate communication mechanism must be provided for communication
from the video process back to the system process.
31
CPU usage metrics
A basic measure of the efficiency with usage of CPU. The simplest and most direct measure is
utilization.
CPU time for useful work
Utilization, U= ------------------------------------
Total available CPU time
Utilization is the ratio of the CPU time that is being used for useful computations to the total available
CPU time.
This ratio ranges between 0 and 1, with 1 meaning that all of the available CPU time is being used for
system purposes.
The utilization is often expressed as a percentage
Scheduling
The first job of the OS is to determine the process which runs next.
The work of choosing the order of running processes is known as scheduling.
The OS considers a process to be in one of three basic scheduling states: waiting, ready, or executing.
There is at most one process executing on the CPU at any time.
If there is no useful work to be done, an idling process may be used to perform a null operation.
Any process that could execute is in the ready state; the OS chooses among the ready processes to select
the next executing process.
A process may not, however, always be ready to run.
For instance, a process may be waiting for data from an I/O device or another process, or it may be set to
run from a timer that has not yet expired.
Such processes are in the waiting state.
32
Figure 2.18 Scheduling states of a process.
Figure 2.18 shows the possible transitions between states available to a process.
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.
A process goes into the ready state when it receives its required data and when it enters a new period.
A process can go into the executing state only when it has all its data, is ready to run, and the scheduler
selects the process as the next process to run.
Scheduling Policies
A scheduling policy defines how processes are selected for promotion from the ready state to the running
state.
Every multitasking OS implements some type of scheduling policy.
Choosing the right scheduling policy ensures that the system will meet all its timing requirements.
Schedulability means whether there exists a schedule of execution for the processes in a system that
satisfies all their timing requirements.
In general, it is necessary to construct a schedule to show schedulability.
But in certain cases, simple tests can identify and eliminate some sets of processes as unschedulable.
CPU Utilization is one of the key metrics in evaluating a scheduling policy.
33
2.3.3 Multiple Tasks and Multiple Processes
Discuss in detail about multiple tasks and multiple processes. (or)
Write short notes on multiple tasks and multiple processes (May 2008)
Embedded systems require functionality and timing.
This is too complex to embody in a single program.
The system is broken into multiple tasks to manage when things happen.
2.3.3.1Tasks and Processes
Explain about Tasks and processes.
Embedded computing systems do more than one thing.
It causes the embedded system to behave differently.
For example, when designing a telephone answering machine, the recording of a phone call and
operating the user’s control panel are defined as distinct tasks.
Because they perform logically distinct operations and they must be performed at very different rates.
Let us understand why the separation of an application into tasks may be reflected in the program
structure.
Consider building a stand-alone compression unit.
34
FIGURE 2.19 An on-the-fly compression box.
As shown in Figure 2.19, this device is connected to serial ports on both ends.
The input to the box is an uncompressed stream of bytes.
Based on a predefined compression table, the box emits a compressed string of bits on the output serial
line.
Such a box may be used to compress data being sent to a modem.
The program’s need to receive and send data at different rates (for example, the program may emit 2 bits
for the first byte and then 7 bits for the second byte) will be reflected in the structure of the code.
The text compression box provides a simple example of rate control problems.
2.3.3.2 Multirate Systems
Briefly explain about multirate systems with an example. (May2011)
Handling multiple rates of computation adds complexity to the implementation of code that meets timing
requirements.
Multirate embedded computing systems are very common, including automobile engines, printers, and
cell phones.
35
In all these systems, certain operations must be executed periodically, and each operation is executed at
its own rate.
Application Example 2.1 describes why automobile engines require multirate control.
==========================================================================
Application Example 2.1
Automotive engine control
Consider the simplest automotive engine controllers, such as the ignition controller of a motorcycle
engine.
It performs only one task - timing the firing of the spark plug.
The spark plug must be fired at a certain point in the combustion cycle.
But to obtain better performance, the phase relationship between the piston’s movement and the spark
should change as a function of engine speed.
A microcontroller sensing the engine crankshaft position allows the spark timing to vary with engine
speed.
Firing the spark plug is a periodic process (Note: the period depends on the engine’s operating speed).
The control algorithm for a modern automobile engine is much more complex, making the need for
microprocessors that much greater.
Automobile engines must meet strict requirements on both emissions and fuel economy.
Automobile engine controllers use additional sensors, including the gas pedal position and an oxygen
sensor used to control emissions.
36
The engine controller takes a variety of inputs that determine the state of the engine.
It controls two basic engine parameters: the spark plug firings and the fuel/air mixture.
===========================================================================
2.4.1 Preemption
Preemption is an alternative to the C function call, as a way to control execution.
CPU is to be shared between two processes.
The kernel is the part of the OS that determines what process is running
Kernel manages process execution in the operating system.
Timer activates the kernel periodically.
The length of the timer period is known as the time quantum which is the smallest unit controlling CPU
activity.
The kernel determines what process will run next and causes that process to run.
On the next timer interrupt, the kernel may pick the same process or another process to run.
2.4.2 Priorities
A mechanism that executes quickly is needed.
If we assign each task a numerical priority, then the kernel can simply look at the processes and their
priorities.
Priority decides which ones actually want to execute (some may be waiting for data or for some event),
and select the highest priority process that is ready to run.
This mechanism is both flexible and fast.
The priority is a non-negative integer value.
The exact value of the priority is not as important as the relative priority of different processes.
Generally use priority 1 as the highest priority (as FreeRTOS.org does).
We assume that P2 is ready to run when the system is started, P1 is released at time 15, and P3 is
released at time 18.
38
===========================================================================
When the system begins execution, P2 is the only ready process, so it is selected for execution.
At time 15, P1 becomes ready; it preempts P2 and begins execution since it has a higher priority.
Since P1 is the highest-priority process in the system, it is guaranteed to execute until it finishes.
P3’s data arrive at time 18, but it cannot preempt P1.
Even when P1 finishes, P3 is not allowed to run.
P2 is still ready and has higher priority than P3.
Only after both P1 and P2 finish can P3 execute.
The first thing that this routine must do is save the context of the task that was interrupted.
To do this, it uses the routine portSAVE_CONTEXT(), which saves all the context of the stack.
It then performs some housekeeping, such as incrementing the tick count.
The tick count is the internal timer that is used to determine deadlines.
After the tick is incremented, some tasks may have become ready as they passed their deadlines.
Next, the OS determines which task to run next using the routine vTaskSwitchContext().
It uses port RESTORE_CONTEXT() to restore the context of the task that was selected by
vTaskSwitchContext().
The action of portRESTORE_CONTEXT() causes control to transfer to that task.
The code for portSAVE_CONTEXT(), in the file portmacro.h, is defined as a macro and not as a C
function.
It is structured in this way so that it doesn’t disturb the register values that need to be saved.
40
The asm statement allows assembly language code to be introduced in-line into the C program.
The keyword volatile tells the compiler that the assembly language may change register values.
The code uses ulCriticalNestingand pxCurrentTCB simply to avoid compiler warnings.
The asm statement requires that the assembly language be entered as strings, one string per line, which
makes the code hard to read.
The fact that the code is included in a #define makes it even harder to read. Here is a cleaned-up version
of the assembly language code from the asm volatile( ) statement:
Here is the code for vTaskSwitchContext( ), which is defined in the file tasks.c:
41
This function is relatively straightforward—it walks down the list of tasks to identify the highest-priority
task.
The list of tasks that is checked is determined by the variable uxTopReadyPriority.
The portRESTORE_CONTEXT() routine is also defined in portmacro.h.
Here is the macro with the line continuations and assembly language code removed:
42
2.4.4 Processes and Object-Oriented Design
We need to design systems with processes as components.
UML often refers to processes as active objects. That is, objects that have independent threads of control.
The class that defines an active object is known as an active class.
We can mix active objects and normal objects when describing a system.
43
Figure 2.22 shows a simple collaboration diagram in which an object is used as an interface between two
processes: p1 uses the w object to manipulate its data before the data is sent to the master process.
Applying the principles of RMA, we give P1 the highest priority, P2 the middle priority, and P3 the
lowest priority.
To understand all the interactions between the periods, we need to construct a time line equal in length to
hyperperiod, which is 12 in this case.
In this case, we can show that there is no feasible assignment of priorities that guarantees scheduling.
Even though each process alone has an execution time significantly less than its period, combinations of
processes can require more than 100% of the available CPU cycles.
For example, during one 12 time-unit interval, we must execute P1 three times, requiring6 units of CPU
time; P2 twice, costing 6 units of CPU time; and P3 one time, requiring 3 units of CPU time.
The total of 6 + 6 + 3 = 15 units of CPU time is more than the 12 time units available, clearly exceeding
the available CPU capacity.
45
===========================================================================
2.5.2 Earliest-Deadline-First Scheduling
Earliest deadline first (EDF) is another well-known scheduling policy that was also studied by Liu and
Layland.
It is a dynamic priority scheme—it changes process priorities during execution based on initiation times.
As a result, it can achieve higher CPU utilizations than RMS.
The EDF policy is also very simple: It assigns priorities in order of deadline.
The highest-priority process is the one whose deadline is nearest in time, and the lowest priority process
is the one whose deadline is farthest away.
Clearly, priorities must be recalculated at every completion of a process.
However, the final step of the OS during the scheduling procedure is the same as for RMS - the highest-
priority ready process is chosen for execution.
Example 2.4 illustrates EDF scheduling in practice.
===========================================================================
Earliest-deadline-first scheduling
Consider the following processes:
The hyperperiod is 60. In order to be able to see the entire period, we write it as a table:
46
47
There is one time slot left at t = 30, giving a CPU utilization of 59/60.
===========================================================================
2.5.3 RMS vs. EDF
Compare RMS versus EDF (Dec 2018)
What if your set of processes is unschedulable but need to guarantee that they complete their deadlines?
There are several possible ways to solve this problem:
■ Get a faster CPU.
■ Redesign the processes to take less execution time.
■ Rewrite the specification to change the deadlines.
We know that P1 and P2 cannot execute at the same time, since P1 must finish before P2 can begin.
Furthermore, we also know that because P3 has a higher priority, it will not preempt both P1 and P2 in a
single iteration.
If P3 preempts P1, then P3 will complete before P2 begins; if P3 preempts P2, then it will not interfere
with P1 in that iteration.
Because we know that some combinations of processes cannot be ready at the same time.
49
TWO MARKS QUESTIONS & ANSWERS
4. Define scheduling.
Scheduling is defined as the work of choosing the order of running process. It is a process of
selection which says that a process has the right to use the processor at given time.
7. What is schedulability?
Schedulability indicates, any execution schedule is there for a collection of process in the system's
functionality.
20. Give the different styles of inter process communication. (April 2014)
The different styles of inter process communication are
1. Shared memory communication.
2. Message passing.
51
24. What is Task State?
A state of a task that changes on scheduler directions. A task at an instance can be in one of the
four states such as idle, ready, blocked and running. It is controlled by the scheduler.
52
35. What are the problems that may arise while using semaphores?
The problems that may arise while using semaphores are,
(i) Sharing of two semaphores creates a deadlock problem.
(ii) Without a timeout an ISR worst-case latency may exceed the deadline.
(iii) A semaphore not taken, and another task use a shared variable.
(iv) When using multiple semaphores, if an unintended task takes the semaphore, it creates a
problem.
(v) It may introduce priority inversion problem.
36. What are multi rate systems? and give two examples(April/May 2023)
Multirate embedded computing systems are very common, including automobile engines, printers
and cell phones. In all these systems, certain operations must be executed periodically, and each
operation is executed at its own rate. Examples are automobile engines, printers and cell phones.
43. If your set of processes is un-schedulable and you need to guarantee that they complete their
deadlines, give possible ways to solve this problem?
The techniques available are as follows
(a) Get a faster CPU.
(b) Redesign the processes to take less execution time c. Rewrite the specification to change the
deadlines
47. What are the various scheduling criteria for CPU scheduling?
The various scheduling criteria are
CPU utilization
Throughput
Turnaround time
Waiting time
Response time
QUESTION BANK
1. Discuss about estimating program run times /Enumerate the need for host based systems for stages of
simulation, porting kernels and estimating program run times in embedded application deployment.
(Dec 2022)
2. What is the purpose of EDF & Round Robin scheduling? Discuss in detail with appropriate
diagrams. (Dec 2022, Jan 2023, May 2023, Dec 2023)
3. Write short notes on multiple tasks and multiple processes (May 2008, May 2011)
4. Discuss in detail about Preemptive real time operating systems. (Dec 2007, May 2012, Nov 2017,
May 2019)
5. Explain in detail about Programming Embedded systems in C.
6. Explain in detail about Memory and I/O devices Interfacing.
7. Briefly explain about priority based scheduling and its types. (Dec 2006, Dec 2007, Dec 2009,
May 2012, May 2023, Dec 2023)
54