0% found this document useful (0 votes)
12 views54 pages

EIOT Unit-2

The document outlines the curriculum for the Embedded Systems and IoT course at Surya Group of Institutions, focusing on embedded C programming, memory and I/O device interfacing, and the need for Real-Time Operating Systems (RTOS). It covers topics such as memory organization in the 8051 microcontroller, interfacing external memory, and the differences between microprocessors and microcontrollers. Additionally, it emphasizes the importance of embedded C in programming electronic devices and provides insights into the structure and functionality of embedded systems.

Uploaded by

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

EIOT Unit-2

The document outlines the curriculum for the Embedded Systems and IoT course at Surya Group of Institutions, focusing on embedded C programming, memory and I/O device interfacing, and the need for Real-Time Operating Systems (RTOS). It covers topics such as memory organization in the 8051 microcontroller, interfacing external memory, and the differences between microprocessors and microcontrollers. Additionally, it emphasizes the importance of embedded C in programming electronic devices and provides insights into the structure and functionality of embedded systems.

Uploaded by

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

SURYA GROUP OF INSTITUTIONS

SCHOOL OF ENGIONEERING AND TECHNOLOGY


G.S.T Road, Vikiravandi-605602. Villupuram Dist.
Ph: 04146-263221, 263122 Website: www.suryagroup.edu.in
(Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai)
Subject Name : EMBEDDED SYSTEMS AND IOT
Subject code : CS3691
Regulation : 2021
Year/Semester : III/VI
Branch : CSE
UNIT II EMBEDDED C PROGRAMMING

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.1 Memory and I/O Interfacing


Several memory chips and I/O devices are connected to a microprocessor. The following figure shows a
schematic diagram to interface memory chips and I/O devices to a microprocessor.

Fig: 2.1 Memory and I/O Interfacing


2.1.1 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.

2.1.2 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.

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.

Von Neumann Architecture


 Von Neumann Architecture or Princeton Architecture is a Computer Architecture, where the
Program i.e., the Instructions and the Data are stored in a single memory.
 Since the Instruction Memory and the Data Memory are the same, the Processor or CPU cannot
access both Instructions and Data at the same time as they use a single bus.
 This type of architecture has severe limitations to the performance of the system as it creates a
bottleneck while accessing the memory.

Fig: 2.2 Von Neumann 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.

2.1.4.1 Program Memory (ROM) of 8051 Microcontroller

 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.

Fig: 2.4 8051 Program Memory


4
 Almost all modern 8051 Microcontrollers, like 8052 Series, have 8KB of Internal Program
Memory (ROM) in the form of flash memory and the option of reprogramming the memory.
 In case of 4KB of Internal ROM, the address space is 0000H to 0FFFH.

 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.

Fig: 2.5 Internal and External Program Memory


 There is another way to fetch the instructions: ignore the Internal ROM and fetch all the
instructions only from the External Program Memory (External ROM).
 For this scenario, the EA Pin must be connected to GND. In this case, the memory addresses of
the external ROM will be from 0000H to FFFFH.

Fig: 2.6 External Program Memory


2.1.4.2 Data Memory (RAM) of 8051 Microcontroller
 The Data Memory or RAM of the 8051 Microcontroller stores temporary data and intermediate
5
results that are generated and used during the normal operation of the microcontroller.
 Original Intel’s 8051 Microcontroller had 128B of internal RAM.

Fig: 2.7 Register Banks


 But almost all modern variants of 8051 Microcontroller have 256B of RAM. In this 256B, the
first 128B i.e., memory addresses from 00H to 7FH is divided in to Working Registers (organized
as Register Banks), Bit – Addressable Area and General Purpose RAM (also known as
Scratchpad area).
 In the first 128B of RAM (from 00H to 7FH), the first 32B i.e., memory from addresses 00H to
1FH consists of 32 Working Registers that are organized as four banks with 8 Registers in each
Bank.

 The 4 banks are named as Bank0, Bank1, Bank2 and Bank3.

 Each Bank consists of 8 registers named as R0 – R7.

 Each Register can be addressed in two ways: either by name or by address.

 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.

Fig: 2.8 Interfacing External Memory with 8051


 An important point to remember when interfacing external memory with 8051 Microcontroller
isthat Port 0 (P0) cannot be used as an IO Port as it will be used for multiplexed address and data
bus (A0 – A7 and D0 – D7).
 Not always, but Port 2 may be used as higher byte of the address bus.

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:

Fig: 2.9 Block diagram of Embedded System Programming

2.2.1 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.

 The extension in C language is known as embedded C programming language.

 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>

Basic Embedded C Programming Steps


Let's see the block diagram representation of Embedded C Programming Steps:

Fig: 2.11 Embedded C Programming Steps


The microcontroller programming is different for each type of operating system. Even though there are
many operating system is existed such as Windows, Linux, RTOS, etc but RTOS has several
advantages for embedded system development.

2.2.2 Basics of Embedded C Program

 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.

 An Embedded System is more of an application-oriented system i.e. it is dedicated to perform a


single task (or a limited number of tasks, but all working for a single main aim).

 An example for embedded system, which we use daily, is a Wireless Router.

 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.

Fig: 2.12 Washing Machine


 It takes some inputs from the user like wash cycle, type of clothes, extra soaking and
rinsing, spin rpm, etc., performs the necessary actions as per the instructions and finishes
washing and drying the clothes.
 If no new instructions are given for the next wash, then the washing machines repeats the same
set of tasks as the previous wash.

 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.

2.2.3 Programming Embedded Systems


 As mentioned earlier, Embedded Systems consists of both Hardware and Software. If we
consider a simple Embedded System, the main Hardware Module is the Processor.
 The Processoris the heart of the Embedded System and it can be anything like a Microprocessor,
Microcontroller, DSP, CPLD (Complex Programmable Logic Device) or an FPGA (Field
Programmable Gated Array).

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.

2.2.4 Factors for Selecting the Programming Language


The following are few factors that are to be considered while selecting the Programming
Language for the development of Embedded Systems.

 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

 Earlier Embedded Systems were developed mainly using Assembly Language.


 Even though Assembly Language is closest to the actual machine code instructions and
produces small size hex files, the lack of portability and high amount of resources (time and man
power) spent on developing the code, made the Assembly Language difficult to work with.

 There are other high-level programming languages that offered the above mentioned features but
none were close to C Programming Language.

Some of the benefits of using Embedded C as the main Programming Language:

 Significantly easy to write code in C


 Consumes less time when compared to Assembly
 Maintenance of code (modifications and updates) is very simple
 Make use of library functions to reduce the complexity of the main code
 You can easily port little modifications

2.2.5 Embedded System and Its Real Time Applications


 Embedded System and its Real Time Applications. Focuses on different topics like What
is an Embedded System, What are the Real Time Applications of Embedded Systems,
What is the Future of Embedded Systems, etc.
 The World is filled with Embedded Systems. The development of Microcontroller
has paved path for several Embedded System application and they play a significant role
(and will continue to play in the future as well) in our modern day life in one way or the
other.
 Starting from consumer electronics like Digital Cameras, DVD Players to high end
and advanced systems like Flight Controllers and Missile Guidance Systems, embedded
systems are omnipresent and became an important part of our life.
 The way we live our life has been significantly improved with the utilization of
Embedded Systems and they will continue to be an integral part of our lives even
tomorrow.
 Another important concept we are hearing these days is Real – Time Systems. In a
real time system, Real Time Computing takes place, where a computer (an Embedded
System) must generate response to events within certain time limits.
 Before going in to the details of Real Time Applications of Embedded Systems, we
will first see what an Embedded System is, what is a real time system and what is real
timeoperating system.

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.

2.2.7 Introduction to Embedded C Programming Language


 Before going in to the details of Embedded C Programming Language and basics of Embedded C
Program, we will first talk about the C Programming Language.

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.

 Embedded C Programming Language, which is widely used in the development of Embedded


Systems, is an extension of C Program Language. The Embedded C Programming Language uses
the same syntax and semantics of the C Programming Language like main function, declaration of
datatypes, defining variables, loops, functions, statements, etc.

 The extension in Embedded C from standard C Programming Language include I/O Hardware
Addressing, fixed point arithmetic operations, accessing address spaces, etc.

2.2.7.1 Difference between C and Embedded C


 There is actually not much difference between C and Embedded C apart from few extensions and the
operating environment. Both C and Embedded C programming are ISO Standards that have almost
same syntax, datatypes, functions, etc.

 Embedded C is basically an extension to the Standard C Programming Language with additional


features like Addressing I/O, multiple memory addressing and fixed-point arithmetic, etc.

 C Programming Language is generally used for developing desktop applications, whereas Embedded
C is used in the development of microcontroller based applications.

2.2.7.2 Keywords in Embedded C


A Keyword is a special word with a special meaning to the compiler (a C Compiler for example, is a
software that is used to convert program written in C to Machine Code). For example, if we take the
Keil’s Cx51 Compiler (a popular C Compiler for 8051 based Microcontrollers) the following are some
of the keywords:
2.2.7.2.1 bit
2.2.7.2.2 sbit
2.2.7.2.3 sfr
2.2.7.2.4 small
2.2.7.2.5 large
The following table lists out all the keywords associated with the Cx51 C Compiler.
_at_ alien bdata
bit code compact
data far idata
interrupt large pdata
_priority_ reentrant sbit
sfr sfr16 small
_task_ using xdata

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

Basic Structure of an Embedded C Program (Template for Embedded C Program)


The next thing to understand in the Basics of Embedded C Program is the basic structure or Template of
Embedded C Program. This will help us in understanding how an Embedded C Program is written.
The following part shows the basic structure of an Embedded C Program.

2.2.7.2.9.1 ........................ Multiline Comments Denoted using /*……*/


2.2.7.2.9.2 ........................... Single Line Comments Denoted using //
2.2.7.2.9.3 ............................ Preprocessor Directives #include<…> or #define
2.2.7.2.9.4 ...................Global Variables Accessible anywhere in the program
2.2.7.2.9.5 .......................... Function Declarations Declaring Function
2.2.7.2.9.6 ............... Main Function Main Function, execution begins here
{
Local Variables .......... Variables confined to main function
Function Calls .......... Calling other Functions

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.

2.2.7.3 Different Components of an Embedded C Program


Comments: Comments are readable text that are written to help us (the reader) understand the code
easily. They are ignored by the compiler and do not take up any memory in the final code (after
compilation).

There are two ways you can write comments: one is the single line comments denoted by // and the
other is multiline comments denoted by /*….*/.

Preprocessor Directive: A Preprocessor Directive in Embedded C is an indication to the compiler that


it must look in to this file for symbols that are not defined in the program.

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.

Basic Embedded C Program


Till now, we have seen a few Basics of Embedded C Program like difference between C and Embedded
C, basic structure or template of an Embedded C Program and different components of the Embedded C
Program.

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.

#include<reg51.h> // Preprocessor Directive void delay (int); // Delay Function Declarationvoid


main(void) // Main Function
{
P1 = 0x00;
/* Making PORT1 pins LOW. All the LEDs are OFF.
* (P1 is PORT1, as defined in reg51.h) */
while(1) // infinite loop
{

P1 = 0xFF; // Making PORT1 Pins HIGH i.e. LEDs are ON.


delay(1000);

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
{

unsigned int i=0; // Local Variable. Accessible only in this function.


/* This following step is responsible for causing delay of 1000mS
* (or as per the value entered while calling the delay function) */
for(; d>0; d–)
{
for(i=250; i>0; i – -);
for(i=248; i>0; i – -);
}
}

2.2.7.4 LED Blinking using 8051 Microcontroller


LED is a semiconductor device used in many electronic devices, mostly used for indication purposes.
It is used widely as indicator during test for checking the validity of results at different stages.

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++);
}

2.3.1 Structure of a real – time system


Discuss about the structure of real time systems.

 Time constraints are the key parameter in real time systems.


 It controls autonomous system such as robots, satellites, air traffic control and hydroelectric dams.
 When user gives an input to the system, it must process within the time limit and result is sent
back.
 Real time system fails if it does not give results within the time limits.

 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.

 Real time systems are clock based or event based.


 Interactive is one more category of real time system.
 Synchronization between the external processes and internal actions (tasks) carried out by the
computer may be defined in terms of the passage of time or the actual time of delay, in which case
the system is said to be "Clock-based system".
 It may be defined in terms of events and the system is said to be "Event-based system".
 If the relationship between the actions in the computer and the system is much more loosely
defined, then the system is said to be an "interactive system".

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.

 A Real-Time Operating System (RTOS) is an operating system intended to serve real-time


application process data as it comes in, typically without buffering delays.
 In general, an operating system is responsible for managing the hardware resources of a
computer and hosting applications that run on the computer.
 An RTOS performs these tasks with precise timing and a high degree of reliability.
 This can be especially important in measurement and automation systems where downtime is
costly or a program delay could cause a safety hazard.
 An RTOS can guarantee that a program will run with very consistent timing.

RTOS kernel services:


 A real-time kernel is software that manages the time and resources, of a microprocessor,
microcontroller or Digital Signal Processor (DSP) and provides indispensable services to your
applications.
 Along with objects, most kernels provide services that help developers create applications for real-
time embedded systems.
1. Timers
2. Device I/0 supervisor
3. Dynamic memory allocation
4. Intertask communication and synchronization
5. Task management.

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.

 Task is a set of related jobs which jointly provide some function.


 A job is a unit of work that is scheduled and executed by a system.
 Real time tasks get generated in response to some events that may either be external or
internal to the system.
 When a task get generated, it is said to have arrived.
 Every real time system usually consists of a number of real time tasks.
 A task T = {J1, J2, …. Jn} is a set of related jobs that together perform some operation.
 Jobs execute on a processor and may depend on some resources.
 A scheduling algorithm describes how jobs execute.

 Processors are active devices on which jobs are scheduled.


 For example: Threads scheduled on a CPU, data scheduled on transmission link.

 A resource (R) is a passive entity on which jobs may depend.


 Resources have different types or sizes, but have no speed attribute and are not consumed by
use.
 Jobs compete for resources and can block if a resource is in use.

1. Clock based tasks:


 Clock based tasks are also called cyclic or periodic tasks.
 All jobs of a periodic task  i have a regular inter arrival time Ti , we call  i the period of the

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 .

 Example of periodic task is monitoring temperature of a patient. It is time driven method.


 Each task is repeated at a regular interval and maximum execution time is the same for each
period.
 Arrival time is usually the start of the period and deadline is usually the end.
 Periodic tasks are mutually independent.
 Static scheduling is used for scheduling periodic tasks.
Plant time constant  Sampling time (Ts)  Interrupt
 The completion of the operations within the specified time is dependent on
26
 the number of operations to be performed, and
 the speed of the computer.
 Synchronization is usually obtained by adding a clock to the computer system.

2. Event based tasks:


 Event based task is also called aperiodic tasks.
 Actions are to be performed not at particular times or time intervals but in response to some
event.
 The system must respond within a given maximum time to a particular event.
 Events occur at non-deterministic intervals and event-based tasks are referred to as "aperiodic"
task.
 Aperiodic tasks is a stream of job arriving at irregular intervals i.e., each task can arrive at any
time.
 These tasks are event driven. Example of this type of task is task activated upon detecting
change in patient’s condition.
 Dynamic scheduling is used to schedule both periodic and aperiodic tasks.

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.

3. Hard Real Time Systems


 A hard real-time system is one where the response time is specified as an absolute value.
This time is normally dictated by the environment.

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.

4. Soft Real Time System


 A soft real-time system is one where the response time is normally specified as an average
value.
 This time is normally dictated by the business or market.
 A single computation arriving late is not significant to the operation of the system, though
many late arrivals might be.
 Example: Airline reservation system - If a single computation is late, the system's response
time may lag. However, the only consequence would be a frustrated passenger.

Estimating program run times


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)

 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.

Figure 2.14 Example definitions of release times and deadlines.


 A rate requirement specifies how quickly processes must be initiated.
 The period of a process is the time between successive executions. For example, the period of a
digital filter is defined by the time interval between successive input samples.

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.

Figure 2.15 A sequence of processes with a high initiation rate.


 The order of execution of processes may be constrained when the processes pass data between
each other.
 Figure 2.15 shows a set of processes with data dependencies among them.
 Before a process can become ready, all the processes on which it depends must complete and send
their data to it.
 The data dependencies define a partial ordering on process execution - P1 and P2 can execute in
any order (or in interleaved fashion).
 But, must both complete before P3, and P3 must complete before P4.
 All processes must finish before the end of the period.

 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.

Figure 2.16 Data dependencies among Figure 2.17 Communication among


processes. processes at different rates.

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

3.2 Task Assignment and Scheduling


Explain Task Assignment and Scheduling of real time systems. (or)
What is the purpose of Priority based scheduling? Discuss in detail with appropriate diagrams.
(or)
(Dec 2022, Jan 2023, May 2023, Dec 2023)
Explain in detail about different types of scheduling policies. (April 2013)

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.

 Evaluating the utilization of the CPU is performed over a finite period


o It should cover all possible combinations of process executions.
 Hyperperiod:
o The length of time for periodic processes.
o It is the least-common multiple of the periods of all the processes.

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.

 These different tasks are part of the system’s functionality.


 A process is a single execution of a program.
 If we run the same program two different times, we have created two different processes.
 Each process has its own state that includes its registers and all of its memory.
 In some OSs, the memory management unit is used to keep each process in a separate address space.
 In others, particularly lightweight RTOSs, the processes run in the same address space.
 Processes that share the same address space are often called threads.

 We will use the terms tasks and processes interchangeably.


 To be more accurate, task can be composed of several processes or threads.
 A task is an implementation concept and process more of an implementation concept.

 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.

 It is easy to create irregular, ungainly code to solve this problem.


 A more smart solution is to
 create a queue of output bits
 these bits will be removed from the queue and sent to the serial port in 8-bit sets.
 The need is to create a clean data structure which simplifies the control structure of the code.
 It must be ensured that we process the inputs and outputs at the proper rates.
 For example, spending too much time in packaging and emitting output characters, may drop the input
characters.
 Solving timing problems is a more challenging problem.

 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.

 They also use a multimode control scheme.


 For example,
o one mode may be used for engine warm-up,
o another for cruise, and
o yet another for climbing steep hills,
and so forth.
 The larger number of sensors and modes increases the number of discrete tasks.

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 Preemptive real Time Operating systems


Discuss in detail about Preemptive real time operating systems.
(Dec 2007, May 2012, Nov 2017, May 2019)
 A RTOS executes processes based upon timing constraints provided by the system designer.
 The most reliable way to meet timing constraints accurately is
o to build a preemptive OS, and
o to use priorities to control what process runs at any given time.
 Using these two concepts, a fundamental Real-Time Operating System (RTOS) will be constructed.
 FreeRTOS.org could be used and this OS runs on many different platforms.

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.

 The assembly language is used to switch between processes.


37
 The timer interrupt causes control to change from the currently executing process to the kernel;
assembly language can be used to save and restore registers.
 The assembly language can be used to restore registers not from the process that was interrupted by the
timer.
 The set of registers that define a process are known as its context and switching from one process’s
register set to another is known as context switching.
 The data structure that holds the state of the process is known as the process control block.

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).

Example 2.2 shows how priorities can be used to schedule processes.


===========================================================================
Example 2.2
Priority-driven scheduling
For this example, we will adopt the following simple rules:
 Each process has a fixed priority that does not vary during the course of execution.
 The ready process with the highest priority (Priority 1) is selected for execution.
 A process continues execution until it completes or it is preempted by a higher-priority process.

 Let’s define a simple system with three processes as seen below.

 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.

2.4.3 Processes and Context


 The best way to understand processes and context is to dive into an RTOS implementation.
 We will use the FreeRTOS.org kernel as an example; Version 4.7.0 for the ARM7 AT91 platform.
 A process is known in FreeRTOS.org as a task.
 Higher numbers denote higher priorities and the priority 0 task is the idle task.

FIGURE 2.20 Sequence diagram for freeRTOS.org context switch.


 To understand the basics of a context switch, let’s assume that the set of tasks is in steady state.
 Everything has been initialized, the OS is running, and we are ready for a timer interrupt.
 Figure 2.20 shows a sequence diagram for a context switch in freeRTOS.org.
 This diagram shows the application tasks, the hardware timer, and all the functions in the kernel that are
involved in the context switch:
39
 vPreemptiveTick() is called when the timer ticks.
 portSAVE_CONTEXT() swaps out the current task context.
 vTaskSwitchContext ( ) chooses a new task.
 portRESTORE_CONTEXT() swaps in the new context.

Here is the code for vPreemptiveTick() in the file portISR.c:

 vPreemptiveTick() has been declared as a naked function.


 Because the function is naked, the registers for the process that was interrupted are still available.
 vPreemptiveTick() doesn’t have to go to the procedure call stack to get their values.

 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:

Here is the assembly language code for portRESTORE_CONTEXT:

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.

FIGURE 2.21 An active class in UML.


 Figure 2.21 shows an example of a UML active class.
 It has all the normal characteristics of a class, including a name, attributes, and operations.
 It also provides a set of signals that can be used to communicate with the process.
 A signal is an object that is passed between processes for asynchronous communication.

FIGURE 2.22 A collaboration diagram with active and normal objects.

 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.

2.5 Priority based scheduling


Briefly explain about priority based scheduling and its types. (Dec 2006, Dec 2007, Dec 2009,
May 2012, May 2023, Dec 2023)
 The Priority based scheduling deals with priority-based context switching mechanism.
 Then, it is must to determine an algorithm to assign priorities to processes.
 After assigning priorities, the OS takes care of the rest by choosing the highest-priority ready process.
 There are two major ways to assign priorities:
o static priorities that do not change during execution, and
o dynamic priorities that do change.
2.5.1 Rate-Monotonic Scheduling
 Rate-monotonic scheduling (RMS) was introduced by Liu and Layland.
 It was one of the first scheduling policies developed for real-time systems.
 It is still very widely used.
 RMS is a static scheduling policy.
 The theory underlying RMS is known as rate-monotonic analysis (RMA).
 This theory uses a relatively simple model of the system.
■ All processes run periodically on a single CPU.
■ Context switching time is ignored.
■ There are no data dependencies between processes.
■ The execution time for a process is constant.
■ All deadlines are at the ends of their periods.
■ The highest-priority ready process is always selected for execution.
 The major result of RMA is a relatively simple scheduling policy.
 It is optimal under certain conditions.
 Priorities are assigned by rank order of period, with the process with the shortest period being assigned
the highest priority.
 This fixed-priority scheduling policy is the optimum assignment of static priorities to processes.
 It provides the highest CPU utilization while ensuring that all processes meet their deadlines.
 Example 2.3 illustrates RMS.
===========================================================================
Example 2.3
Rate-monotonic scheduling
 Here is a simple set of processes and their characteristics.
44
 Process Execution time Period

 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.

 All three periods start at time zero.


 P1’s data arrive first.
 Since P1 is the highest-priority process, it can start to execute immediately.
 After one time unit, P1 finishes and goes out of the ready state until the start of its next period.
 At time 1, P2 starts executing as the highest-priority ready process.
 At time 3, P2 finishes and P3 starts executing.
 P1’s next iteration starts at time 4, at which point it interrupts P3.
 P3 gets one more time unit of execution between the second iterations of P1 and P2, but P3 does not get
to finish until after the third iteration of P1.
 Consider the following different set of execution times for these processes, keeping the same deadlines.

 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)

 Which scheduling policy is better: RMS or EDF?


 EDF can extract higher utilization out of the CPU, where RMS achieves lower CPU utilization.
 In some applications, it may be acceptable for some processes to occasionally miss deadlines.

 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.

2.5.4 A Closer Look at Our Modeling Assumptions


 The analyses of RMS and EDF have made some strong assumptions.
 In all of the discussions, it is assumed that each process is totally self-contained.
 A process may need a system resource, such as an I/O device or the bus, to complete its work.
 Scheduling the processes without considering the resources those processes require can cause priority
inversion.
 In priority inversion, a low-priority process blocks execution of a higher priority process by keeping
hold of its resource.
 Example 2.5 illustrates priority inversion.
===========================================================================
Example 2.5
Priority inversion
 Consider a system with two processes: the higher-priority P1 and the lower-priority P2.
48
 Each uses the microprocessor bus to communicate to peripherals.
 When P2 executes, it requests the bus from the operating system and receives it.
 If P1 becomes ready while P2 is using the bus, the OS will preempt P2 for P1, leaving P2 with control of
the bus.
 When P1 requests the bus, it will be denied the bus, since P2 already owns it.
 Unless P1 has a way to take the bus from P2, the two processes may deadlock.
===========================================================================
 Rate-monotonic scheduling assumes that there are no data dependencies between processes.
 Example 2.6 shows that knowledge of data dependencies can help use the CPU more efficiently.
===========================================================================
Example 2.6
Data dependencies and scheduling
Data dependencies imply that certain combinations of processes can never occur. Consider the simple
example below.

 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

UNIT II EMBEDDED C PROGRAMMING

1. Define process. (Nov/Dec 2013)


A process is defined as a single execution of a program. A running of the same program two
different times leads to creation of two different processes. Each process has its own state that includes
its register and memory.

2. What are the states of a process?


The states of a process are
a. Running
b. Ready
c. Waiting

3. What is the function in ready state?


Processes which are ready to run but are not currently using the processor are said to be in the
'ready' state.

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.

5. What is scheduling policy?


Scheduling policy describes the way in which processes are chosen to get promotion from ready
state to running state.

6. Define hyper period.


Hyper period is the least-common multiple of the periods of all the processes. It is a finite
period that covers all possible combinations of process executions.

7. What is schedulability?
Schedulability indicates, any execution schedule is there for a collection of process in the system's
functionality.

8. What are the types of scheduling? (May/June 2013)


The types of scheduling are
1. Time division multiple access scheduling.
2. Round robin scheduling.
3. Cyclostatic scheduling.

9. What is cyclostatic scheduling?


Cyclostatic scheduling is a type of scheduling in which schedules are separated into equal sized
time slots.
10. Define round robin scheduling.
Round robin scheduling is a type of scheduling which employs the hyperperiod as an interval. In
this scheduling, the processes run in the given order.
11. What is scheduling overhead?
Scheduling overhead is the time of execution needed to select the next execution process.
50
12. What is meant by context switching? [April 2014, Dec 2013, Dec 2012, April 2018]
 A context switch is the computing process of storing and restoring of a CPU, where execution can
be resumed from the same point at a later time.
 The context switching is an essential feature of multitasking operation system.
13. Define priority scheduling.
Priority scheduling is defined as a scheduling which maintains a priority queue of processes that
are in the runnable state.

14. What is rate monotonic scheduling?


Rate monotonic scheduling is an approach that is used to assign task priority for a preemptive
System.

15. What is critical instant?


Critical instant is the situation in which the process or task posses’ highest response time.

16. What is critical instant analysis?


Critical instant analysis is used to know about the schedule of a system. It’s says that, based on
the periods given, the priorities to the processes has to be assigned.

17. Define earliest deadline first scheduling.


Earliest deadline first scheduling is a type of scheduling which applies task priority policy that
uses the nearest deadline as the criterion for assigning the task priority.

18. What is use of IDC mechanism?


IDC (Inter Domain Communication) mechanism is necessary for a 'process to get communicate
with other process' in order to attain a specific application in an operating system.

19. What are the two types of communication?


The two types of communication are
1. Blocking communication
2. Non-blocking communication

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.

21. What does a scheduler do in an operating system environment? (Nov/Dec 2012)


In an operating system, the scheduling process is carried out by software called scheduler.
22. List out the types of scheduler.
The types of scheduler are:
 Short term scheduler
 Mid- term scheduler
 Long term scheduler.

23. What is Task?


A task is an independent process that takes control of the CPU, when scheduled at an OS. Every
task has a TCB (Task Control Block).

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.

25. Define inter process communication.


An output from one task (or process) passed to another task through the scheduler. It uses signals,
exceptions, semaphores, queues, mailboxes, pipes, sockets and remote procedure call. This is known as
inter process communication.

26. Define Semaphore.


Semaphore is a special variable or function that is used to take note of certain actions to prevent
another task or process from proceeding.

27. What is shared data problem?


If a variable is used in two different processes (tasks) and another task, if it interrupts without
before the operation on that is completed, then the shared data problem arises.

28. What is priority inversion problem? How it can be solved?


A problem in which a low priority task does not release the process for a higher priority task. An
operating system can take care of this by appropriate provisions. This problem can be solved
temporarily by boosting the low priority task to higher priority task. This is called as priority
inheritance.

29. Briefly discuss about Deadlock situation.


Deadlock is a situation in which the processes wait for the other resource which is occupied by
another process in a loop. For example take processes P1 and P2 and resources
 R1 and R2 in the deadlock condition. P1 -R1 waits for R2
 P2 -R2 waits for R1 so both processes waits for the other resource to get free for their complete
operation.

30. What is Message Queue?


A task sending the multiple FIFO or priority message into a queue for use by another task using
queue message as an input is said to be message queue.

31. What is Socket?


Socket provides the logical link. It is using a protocol between the tasks in a client server or peer-to-
peer environment.

32. What is Remote Procedure Call?


Remote Procedure Call (RPC) is a protocol that one program can use to request a service from a
program located in another computer on a network without having to understand the network's details.
A procedure call is also sometimes known as a function call or a subroutine call.

33. Define Thread.


Thread is a minimum unit for a scheduler to schedule the CPU and other system resources. A
process may consist of multiple threads. A thread has an independent process control block like a task
control block. A thread also executes codes under the control of a scheduler.

34. Give the uses of Task Control Block (TCB).


Task control block is a memory block which holds information of program counter, memory map,
the signal (message) dispatch table, signal mask, task ID,CPU state (registers etc.) and a kernel stack
(for executing system calls, etc.).

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.

37. What is release time and deadline of a process?


The release time is the time at which the process becomes ready to execute. A deadline specifies
when a computation must be finished. The deadline for an aperiodic process is generally measured
from the release time, since that is the only reasonable time reference.

38. What is the period and rate of a process?


The period of a process is the time between successive executions. The process’s rate is the Inverse
of its period.

39. What is a task graph?


A set of processes with data dependencies is called a task graph.

40. Define CPU utilization.


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.

41. What is the response time of a process?


The response time of a process is the time at which the process finishes its execution.

42. Define preemption.


Preemption is the act of forcing a process out of execution i.e. making a context switch.

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

44. What are the benefits of multithreaded programming?


The benefits of multithreaded programming can be broken down into four major categories:
 Responsiveness
 Resource sharing
53
 Economy
 Utilization of multiprocessor architectures

45. What is a Dispatcher?


The dispatcher is the module that gives control of the CPU to the process selected by the short-term
scheduler. This function involves:
 Switching context
 Switching to user mode
 Jumping to the proper location in the user program to restart that program.

46. What is dispatch latency?


The time taken by the dispatcher to stop one process and start another running is known as dispatch
latency.

47. What are the various scheduling criteria for CPU scheduling?
The various scheduling criteria are
 CPU utilization
 Throughput
 Turnaround time
 Waiting time
 Response time

48. Define throughput.


Throughput in CPU scheduling is the number of processes that are completed per unit time. For
long processes, this rate may be one process per hour. For short transactions, throughput might be 10
processes per second.

UNIT II EMBEDDED C PROGRAMMING

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

You might also like