Unit-2
Unit-2
P1 P0 D0-D7
EA A0
| ROM/
8051 LATCH A7 EPROM
ALE
clock
A8 Address
P3 | lines
A15
PSEN OE
P1 D0 data
P0 | lines
D7
RAM
8051 LATCH A0
ALE clock |
A7 address
lines
RD P3 P2
1
LINEAR AND ABSOLUTE DECODING
i. Absolute Decoding
all higher address lines : decoded to select memory chip for
specific logic levels.
for other logic levels memory chip is disabled.
generally used in large memory systems.
figure below shows memory interfacing using absolute decoding.
Vss
P0.7 D7-D0
EA |
P0.0
74LS373 A7-A0
ALE G OC 16k x 8
8051 RAM
P2.0
| A8-A13
P2.5
P2.6
P2.7 CS
PSEN
P3.6 WR
P3.7 RD
ALE G OC 16 x 8
8051 RAM
P2.0
| A8-A13
P2.5
P2.6 CS (A14)
P2.7 A15
PSEN
P3.6 WR
P3.7 RD
2
Address Mapping(Memory Map)
i. Absolute Decoding
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0000H
end 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3FFFH
ii. Linear Decoding
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0000H
end x 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3FFFH
Comparison between Full address(Absolute) & Partial address (Linear) Decoding.
-----------------------------------------------------------------------
Full Adress(Absolute) | Partial Address(Linear
Decoding | Decoding
-----------------------------------------------------------------------
i. all higher address lines are |i. few or individual address lines
decoded to select memory or | are decoded to select memory or
I/O device. | I/O device.
ii. more hardware : decoding |ii. less hardware : decoding logic.
logic. | (sometimes none.)
iii. decoding circuit : higher |iii. decoding circuit : less cost.
cost. |
iv. No multiple addresses. |iv. multiple addresses possible.
v. used in large systems. |v. used in small systems.
-----------------------------------------------------------------------
Solved Examples:
Example 1: Design a µController system using 8051.Interface the external RAM
of size 16k x 8.
Solution: Given, Memory size: 16k
that means we require 2n=16k :: n address lines
here n=14 :: A0 to A13 address lines are required.
A14 and A15 are connected through OR gate to CS pin of external RAM.
when A14 and A15 both are low (logic ‘0’), external data memory(RAM) is
selected.
Address Decoding(Memory Map)for 16k x 8 RAM.
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
ALE G OC 16k x 8
8051 RAM
P2.0
| A8-A13
P2.5
P2.6
P2.7 CS
PSEN
P3.6 WR
P3.7 RD
ALE G OC 4k x 8
8051 ROM
P2.0
| A8-A11
P2.5
P2.6
P2.7 WR
PSEN CS
P3.6
P3.7 RD
Example 3: Design a µController system using 8051, 16k bytes of ROM & 32k
bytes of RAM. Interface the memory such that starting address for ROM is
0000H & RAM is 8000H.
Solution: Given, Memory size- ROM : 16k
that means we require 2n=16k :: n address lines
here n=14 :: A0 to A13 address lines are required.
4
Address Decoding(Memory Map)for 16k x 8 ROM.
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0000H
end 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3FFFH
Address Decoding(Memory Map)for 32k x 8 RAM.
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8000H
end 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 FFFFH
Vcc Vcc
Vss
P0.7 D7-D0 D7-D0
EA |
P0.0
74LS373 A7-A0 A7-A0
Example 4:Design a µController system using 8051, 8k bytes of program ROM &
8k bytes of data RAM. Interface the memory such that starting address for
ROM is 0000H & RAM is E000H.
Solution: Given, Memory size- ROM : 8k
that means we require 2n=8k :: n address lines
here n=13 :: A0 to A12 address lines are required.
A13,A14,A15 NANDed CS
5
Address Decoding(Memory Map)for 8k x 8 ROM.
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0000H
end 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1FFFH
Address Decoding(Memory Map)for 8k x 8 RAM.
Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 HEX
adrs.
starting 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 E000H
end 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 FFFFH
Vcc Vcc
Vss
P0.7 D7-D0 D7-D0
EA |
P0.0
74LS373 A7-A0 A7-A0
ALE G OC 8k x 8 8k x 8
8051 ROM RAM
P2.0
| A8-A12 A8-A12
P2.4 To
P2.7
P2.5
To
P2.6 CS P2.6 CS
P2.7 To
PSEN P2.5
P3.6 RD
WR RD
P3.7
6
I/O interfacing
1. 8255 Programmable Peripheral Interface-
Features:
* widely used programmable parallel I/O device.
* TTL compatible & compatible with all Intel & most other processors.
* can be programmed to transfer data- simple I/O, Interrupt I/O.
* three 8 bit ports- port A, port B and port C.
* bit set/reset mode: setting/resetting of individual bits of port c.
* can operate in I/O modes-
i. Mode 0
ii. Mode 1
iii. Mode 2
port A programmed as input or output : with or without handshaking
signals.
or as a bidirectional
port.
(PC4-PC7) (PC0-PC3)
PC
Bidirectional Group A
data bus
Data Port C PC7-PC4
Bus upper(4)
D7-D0 buffer
WR
Read/
A0 Write
control
A1 logic PB
Group B
Reset Group B
Control Port B PB7-PB0
(8)
CS
7
above figure shows internal block diagram of 8255.
consist of data bus buffer, control logic- group A and group B.
DATA BUS BUFFERS-
tri-state bidirectional buffer.
interfaces internal databus of 8255 to the system databus.
i/p or o/p instructions executed by the CPU either read data from or write
data into buffer.
data from & to CPU always passed through buffer.
CONTROL LOGIC-
accepts control bus signals, i/ps from address bus & issues command to the
individual group control blocks.(Group A & Group B control)
it issues appropriate enabling signals to the access required data/control
words or status words.
following are the inputs for the control logic section,
Group A and Group B control-
receives control words from CPU & issues appropriate commands to
ports associated with it.
Group A controls the Port A and Port C upper part i.e. PC7-PC4.
Group B controls the Port B and Port C lower part i.e. PC3-PC0.
Port A-8 bit latched inputs.
8 bit latched & buffered output.
can be programmed in 3 modes viz. mode 0, mode 1 and mode 2.
Port B-8 bit data input buffer.
8 bit data I/O latch/buffer.
can be programmed in mode 0 & mode 1.
Port C-8 bit unlatched input buffer.
8 bit output latch/buffer.
divide into two parts- each one used as control signal for port A
& B in handshake mode.
can be programmed for bit set/reset operation.
8255 PIN DIAGRAM
PA3 1 40 PA4
2 39
PA2 PA5
PA1 3 38 PA6
PA0 4 37 PA7
RD 5 36 WR
GND 7 34 D0
A1 8 33 D1
A0 9 32 D2
PC7 10 31 D3
PC6 11 30 D4
PC5 12 8255 29 D5
PC4 13 28 D6
PC0 14 27 D7
PC1 15 26 Vcc
PC2 16 25 PB7
PC3 17 24 PB6
PB0 18 23 PB5
PB1 19 22 PB4
PB2 20 21 PB3
FIGURE 9 PIN DIAGRAM OF 8255.
8
figure above shows the pin diagram of 8255.
PA0-PA7 (Port A)
8 bit bidirectional I/O pins.
to send/receive data to & from I/O devices.
functions as 8 bit data i/p buffer, 8 bit data o/p buffer/latch.
D0-D7 (Data Bus)
8 bit bidirectional, tri-state data bus.
connected to system data bus.
used to transfer data & control word from processor to 8255 or to
receive data/status word from 8255 to processor.
PB0-PB7 (Port B)
8 bit bidirectional I/O pins.
to send/receive data to & from I/O devices.
functions as 8 bit data i/p buffer, 8 bit data o/p buffer/latch.
PC0-PC7 (Port C)
8 bit bidirectional I/O pins.
PC U PC L
(PC7-PC4) (PC3-PC0)
for handshaking purpose.
to send receive data in & out.
RD (Read)
when low, CPU can read the data in port or status word through
buffer.
WR (Write)
when low, CPU can write the data on ports or in control registers
through buffers.
CS (Chip Select)
when low, chip is activated/enabled for data transfer between CPU
and 8255.
RESET
active high input to reset 8255.
when RESET= 1 :: control register is cleared & all ports are set
to input mode.
usually RESET OUT from processor is used to reset 8255.
A0 & A1 selects specific ports & control register.
-----------------------------------------------------------------
9
Operating Modes
Bit Set Reset Mode (BSR mode)
individual bits of port C can be set or reset by sending out single OUT
instruction to the control register, whenever port C is used for
control/status operation.
I/O modes-
1. Mode 0: simple Input/ Output
Port A & B :: two simple 8 bit I/O ports.
Port C :: two 4 bit ports.
port(any) can be programmed to function as simply input or output port.
I/O features are as follows-
i. outputs are latched.
ii. inputs are buffered, not latched.
iii. ports don’t have handshake or interrupt capability.
2. Mode 1: Input/ Output with handshake.
i/p or o/p data transfer is controlled by handshaking signals.
Features-
i. Port A & B- 8 bit I/O ports :: either input or output port.
ii. Port C-3 lines for handshaking signals &
2 lines for I/O functions.
iii. input and output data are latched.
iv. interrupt logic is supported.
3. Mode 2: Bidirectional I/O data transfer.
allows bidirectional data transfer.
loaded 8 bit pattern decides I/O functions of each port & mode of
operation of port.
1. Bit set/ reset mode:
bit set/ reset control word format is shown below.
BSR word – written for each bit that is to be set or reset.
also used for enabling/ disabling interrupt signals by setting/
resetting the associated bits of interrupts.
10
D7 D6 D5 D4 D3 D2 D1 D0
D7 D6 D5 D4 D3 D2 D1 D0
P2.7 CHIP
SELECT CS
|
P2.0 LOGIC PA
PB
PC
ALE
8255
8051 G
D0 WR RD
D0
as seen earlier, for external memory interfacing to 8051 port 0 & port
2 are used as multiplexed address/data bus & higher order data bus
respectively.
if circuit needs on-chip peripherals(e.g. serial I/O & interrupts) then
only port is available for I/O.
11
in such situation, I/O expansions is necessary & it is achieved by
using 8255.
data bus of 8255 is connected to the port 0.
address line A0 & A1, after latches are connected to A0 & A1 of the
8255.
INTERFACING TO µCONTROLLER 8051
1. Interfacing Push button switches(Keys & LEDs)
Vcc
pull up
resistors
P1.0
PORT 1 P1.1
P1.2
P1.3
P1.4
8051
P1.5
P1.6
P1.7
P0.0
P0.1
P0.3
P0.4
8051 P0.5
P0.6
P0.7
PROGRAMMING STEPS
i. check if key is pressed.
ii. wait for key debounce.
iii. identify the key in binary format.
iv. display the key condition using 8 LEDs.
---------------------------------------------------------------------
SAMPLE PROGRAM: key_led.asm
labels mnemonics comments
---------------------------------------------------------------------
mov p1, #0ffh ;make p1 as input port.
start: MOV A, P1 ;read the data from P1.
cjne a, #0ffh, check ;key pressed- branched to check1.
sjmp start ;branch to start.
check: acall delay ;call delay.
mov a, p1 ;read data from port 1.
cpl a ;complement a.
mov p0, a ;send data to LED.
ajmp start ;branch to start.
delay: mov r6, #20h ;delay routine. load r6 with 20h.
next: mov r7, #0ffh ;load r6 with 20h.
here: djnz r7, here ;wait until r7 becomes 0.
djnz r6, next ;wait until r6 becomes 0.
ret ;return to next instruction.
end ;end address of program.
-----------------------------------------------------------------------
2. Interfacing Seven Segment Display
100Ω a a
P0.7
100Ω b b
P0.6
100Ω c
P0.5 c
PORT 0
P0.0
74ALS244
100Ω h
8 8 h
PORT 2
P2.4 1-2
DECODER
1k
1k . .
FIGURE 14 8051 PORT 0 CONNECTION TO 7 SEGMENT DISPLAY.
Coil 1
ROTOR
ROTOR
Coil 4 Coil 2
Coil 3
STATOR STATOR
(14-b 1)
(14-a)
Coil 1
Coil 1
Coil 1
Coil 4 Coil 2 Coil 4 Coil 2 Coil 4 Coil 2
Coil 3
Coil 3
Coil 3
(14-b 2) (14-b 3) (14-b 4)
Coil 3
Coil 3
Coil 3
(15.4) (15.5) (15.6)
Coil 1
Coil 1
Coil 1
Coil 3
Coil 3
Coil 3
T1
D1
Vcc
+Vcc
+Vcc
PORT 2
T3
D3
+Vcc
T4
D4
15
PROGRAMMING STEPS:
i. port 2 is used as output port for interfacing the stepper motor.
--------------------------------------------------------------------------
SAMPLE PROGRAM: steppermotor_interfacing.asm
Labels Mnemonics Comments
--------------------------------------------------------------------------
ORG 0000H ; start address of program.
LOOP: MOV P2, #03H ; load step sequence 03h.
ACALL DELAY ; call delay.
MOV P2, #09H ; load step sequence 09h.
ACALL DELAY ; call delay.
MOV P2, #0CH ; load step sequence 0ch.
ACALL DELAY ; call delay.
MOV P2, #06H ; load step sequence 06h.
ACALL DELAY ; call delay.
AJMP LOOP ; repeat.
DELAY: MOV R0, #0FFH ; load r5 with 0ffh.
DELAY1: MOV R1, #0FFH ; load r7 with 0ffh.
HERE: DJNZ R1, HERE ; wait until r1=0.
DJNZ R0, DELAY1 ; wait until r0=0.
RET ; return to main program.
END ; end address of program.
-----------------------------------------------------------------------
the step sequence is described below,
depending on no. of steps the step sequence is given below.
1 0 0 1 1 03H
clockwise
2 1 0 0 1 09H Anti-
3 1 1 0 0 0CH
4 0 1 1 0 06H
-----------------------------------------------------------------------
b. normal 8 step sequence-
-----------------------------------------------------------------------
Step A B C D Hex Equivalent
-----------------------------------------------------------------------
1 0 0 1 1 03H
3 1 0 0 1 09H
4 1 0 0 0 08H
5 1 1 0 0 0CH
6 0 1 0 0 04H
7 0 1 1 0 06H
8 0 0 1 0 02H
-----------------------------------------------------------------------
4. Interfacing Relay
µC: pins at output provides Max. 1.32mA current.
relay coil needs around 10mA.
hence µC lacks sufficient driving current for relay.
relay driver – ULN2803 or power transistors employed for this purpose.
figure below shows the connection of relay driver ULN2803 between µC &
relay.
16
+12V
µC 8051
P1.0
T3
Zero Fan
8051 Voltage
ckt
P1.0
17
Programming Embedded Systems in C
Embedded C is the most popular programming language in the software field for
developing electronic gadgets.
❏ Each processor used in an electronic system is associated with embedded
software.
❏ Embedded C programming plays a key role in performing specific functions by
the
processor.
❏ In day-to-day life we used many electronic devices such as mobile phones,
washing
machines, digital cameras, etc. These all devices working are based on
microcontrollers that are programmed by embedded C.
❏Let's see the block diagram representation of embedded system programming:
The Embedded C code written in the above block diagram is used for blinking the
● Easy to understand
● High Reliability
● Portability
● Scalability
Basic Declaration
#include<microcontroller name.h>
Whenever the conventional 'C' Language and its extensions are used for programming
embedded systems, it is referred as 'Embedded C’ programming. Programming in
'Embedded C' is quite different from conventional Desktop application development using 'C'
language for a particular OS platform.
Desktop computers contain working memory in the range of Megabytes (Nowadays Giga
bytes) and storage memory in the range of Giga bytes. For a desktop application developer,
the resources available are surplus in quantity and they can be very lavish in the usage of
RAM and ROM and no restrictions are imposed at all. This is not the case for embedded
application developers.
Almost all embedded systems are limited in both storage and working memory resources.
Embedded application developers should be aware of this fact and should develop
applications in the best possible way which optimizes the code memory and working memory
usage as well as performance.
In other words, the hands of an embedded application developer are always tied up in the
memory usage context.
Identifiers are user defined names and labels. Identifiers can contain letters of English
alphabet (both upper and lower case) and numbers. The starting character of an identifier
should be a letter. The only special character allowed in identifier is underscore ( _ ).
Ex: Root, _getchar, _sin, x_1, x1, If
Data Types:
Data type represents the type of data held by a variable. The various data types supported,
their storage space (bits) and storage capacity for 'C' language are tabulated below.
Arithmetic and Relational Operations:
Logical Operations:
Logical operations are usually performed for decision making and program control transfer.
Looping Instructions:
Looping instructions are used for executing a particular block of code repeatedly till a
condition is met or wait till an event is fired.
Embedded programming often uses the looping instructions for checking the status of certain
I/O ports, registers, etc. and also for producing delays. Certain devices allow write/read
operations to and from some registers of the device only when the device is ready and the
device ready is normally indicated by a status register or by setting/clearing certain bits of
status registers.
Hence the program should keep on reading the status register till the device ready indication
comes. The reading operation forms a loop. The looping instructions supported by are listed
below.
Looping Instructions:
//while statement
While (expression)
{
Body of while loop
}
//do while statement
do
{
Body of do loop
}
While (expression)
//for loop
for (initialization; test for condition; update variable)
{
Body of for loop
}
The elements of an array are accessed by using the array index or subscript.
The index of the first element is '0'. For the above example the first element is accessed by
arr[0], second element by arr[1], and so on. In the above example, the array starts at memory
location 0x8000 (arbitrary value taken for illustration) and the address of the first element is
0x8000.
The `address of operator (&) returns the address of the memory location where the variable is
stored. Hence &arr[0] will return 0x8000 and &arr[1] will return 0x8001, etc.. The name of
the array itself with no index (subscript) always returns the address of the first element. If we
examine the first element arr[0] of the above array, we can see that the variable arr[0] is
allocated a memory location 0x8000 and the contents of that memory location holds the value
for arr[0].
Pointers:
Pointer is a flexible at the same time most dangerous feature, capable of creating potential
damages leading to firmware crash, if not used properly.
Pointer is a memory pointing based technique for variable access and modification. Pointers
are very helpful in
1. Accessing and modifying variables
2. Increasing speed of execution
3. Accessing contents within a block of memory
4. Passing variables to functions by eliminating the use of a local copy of variables
5. Dynamic memory.
Some real life examples of embedded systems may involve ticketing machines, vending
machines, temperature controlling unit in air conditioners etc. Microcontrollers are nothing
without a Program in it.
One of the important part in making an embedded system is loading the software/program we
develop into the microcontroller. Usually it is called “burning software” into the controller.
Before “burning a program” into a controller, we must do certain prerequisite operations with
the program. This includes writing the program in assembly language or C language in a text
editor like notepad, compiling the program in a compiler and finally generating the hex code
from the compiled program. Earlier people used different softwares/applications for all these
3 tasks. Writing was done in a text editor like notepad/WordPad, compiling was done using a
separate software (probably a dedicated compiler for a particular controller like 8051),
converting the assembly code to hex code was done using another software etc. It takes lot of
time and work to do all these separately, especially when the task involves lots of error
debugging and reworking on the source code.
Keil MicroVision is free software which solves many of the pain points for an embedded
program developer. This software is an integrated development environment (IDE), which
integrated a text editor to write programs, a compiler and it will convert your source code to
hex files too.
Here is simple guide to start working with Keil uVision which can be used for
Writing programs in C/C++ or Assembly language
Compiling and Assembling Programs
Debugging program
Creating Hex and Axf file
Testing your program without Available real Hardware (Simulator Mode)
This is simple guide on Keil uVision 4 though also applicable on previous versions also.
These are the simple steps to get off the mark your inning!
Step 1: After opening Keil uV4, Go to Project tab and
Create new uVision project
Now Select new folder and give name to Project.
Step 2: After Creating project now Select your device model. Example.NXP-LPC2148
[You can change it later from project window.]
Step 3: so now your project is created and Message window will appear to add startup file of
your Device click on Yes so it will be added to your project folder
Step 4: Now go to File and create new file and save it with .C extension if you will write
program in C language or save with .asm for assembly language.
i.e., Led.c
Step 5: Now write your program and save it again. You can try example given at end of this
tutorial.
Step 6: After that on left you see project window [if it’s not there….go to View tab and click
on project window]
Now come on Project window.
Right click on target and click on options for target
Here you can change your device also.
Click output tab here & check create Hex file if you want to generate hex file
Now click on ok so it will save changes
Step 7: Now Expand target and you will see source group
Right click on group and click on Add files to source group
Now add your program file which you have written in C/assembly.
Step 8: Now Click on Build target.You can find it under Project tab or in toolbar.It can also
be done by pressing F7 key.
Step 9: you can see Status of your program in Build output window
[If it’s not there go to view and click on Build output window]
As we saw in Chapter 3, control of the 8051 ports is carried out using 8-bit latches (SFRs).
We can send some data to Port 1 as follows:
After the 8051 microcontroller is reset, the port latches all have the value 0xFF (11111111 in
binary): that is, all the port-pin latches are set to values of ‘1’. It is tempting to assume that
writing data to the port is therefore unnecessary, and that we can get away with the following
version:
The problem with this code is that, in simple test programs it works: this can lull the
developer into a false sense of security. If, at a later date, someone modifies the program to
include a routine for writing to all or part of the same port, this code will not generally work
as required:
In most cases, initialization functions are used to set the port pins to a known state at the start
of the program. Where this is not possible, it is safer to always write ‘1’ to any port pin
before reading from it.
;Toggle all bits of continuously.
MOV A,#55
BACK: MOV P2,A
ACALL DELAY
CPL A ;complement(inv) reg.A
SJMP BACK
We might also have input and output devices connected to the other pins on Port 1.
These pins may be used by totally different parts of the same system, and the code to
access them may be produced by other team members, or other companies.
It is therefore essential that we are able to read-from or write-to individual port pins
without altering the values of other pins on the same port.
We provided a simple example to illustrates how we can read from Pin 1.1, and write
to Pin 2.1, without disrupting any other pins on this (or any other) port.
#include<reg51.h>
sbit Led = P2^1; //pin connected to toggle Led
sbit Switch =P1^1; //Pin connected to toggle led
void main(void)
{
Led = 0; //configuring as output pin
Switch = 1; //Configuring as input pin
while(1) //Continuous monitor the status of the switch.
{
if(Switch == 0)
{
Led =1; //Led On
}
else
{
Led =0; //Led Off
}
}
return 0;
}
SWITCH BOUNCE:
In an ideal world, this change in voltage obtained by connecting a switch to the port pin of an
8051 microcontroller would take the form illustrated in Figure 4.8 (top). In practice, all
mechanical switch contacts bounce (that is, turn on and off, repeatedly, for a short period of
time) after the switch is closed or opened. As a result, the actual input waveform looks more
like that shown in Figure 4.8 (bottom). Usually, switches bounce for less than 20 ms:
however large mechanical switches exhibit bounce behaviour for 50 ms or more.
When you turn on the lights in your home or office with a mechanical switch, the switches
will bounce. As far as humans are concerned, this bounce is imperceptible.
However, as far as the microcontroller is concerned, each ‘bounce’ is equivalent to one press
and release of an ‘ideal’ switch. Without appropriate software design, this can give rise to a
number of problems, not least:
APPLICATIONS:
Program:
#include<reg51.h> // special function register declarations
sbit LED = P2^0; // Defining LED pin
void Delay(void); // Function prototype declaration
void main (void)
{
while(1) // infinite loop
{
LED = 0; // LED ON
Delay();
LED = 1; // LED OFF
Delay();
}
}
void Delay(void)
{
int j;
int i;
for(i=0;i<10;i++)
{
for(j=0;j<10000;j++)
{
}
}
}
Program:
#include<REG51.H>
#define LEDPORT P1
void delay(unsigned int);
void main(void)
{
LEDPORT =0x00;
while(1)
{
LEDPORT = 0X00;
delay(250);
LEDPORT = 0xff;
delay(250);
}
}
void delay(unsigned int itime)
{
unsigned int i,j;
for(i=0;i<itime;i++)
{
for(j=0;j<250;j++);
}
}
4X4 MATRIX KEYPAD INTERFACING WITH 8051 MICROCONTROLLER:
Keypads/Keyboards are widely used input devices being used in various electronics and
embedded projects. They are used to take inputs in the form of numbers and alphabets, and
feed the same into system for further processing. In this tutorial we are going to interface a
4x4 matrix keypad/Keyboard with 8051 microcontroller.
Before we interface the keypad with microcontroller, first we need to understand how it
works. Matrix keypad consists of set of Push buttons, which are interconnected. Like in our
case we are using 4X4 matrix keypad, in which there are 4 push buttons in each of four rows.
And the terminals of the push buttons are connected according to diagram. In first row, one
terminal of all the 4 push buttons are connected together and another terminal of 4 push
buttons are representing each of 4 columns, same goes for each row. So we are getting 8
terminals to connect with a microcontroller.
Now the question is how to get the location of the pressed button? I am going to explain this
in below steps and also want you to look at the code:
1. First we have made all the Rows to Logic level 0 and all the columns to Logic level 1.
2. Whenever we press a button, column and row corresponding to that button gets shorted
and makes the corresponding column to logic level 0. Because that column becomes
connected (shorted) to the row, which is at Logic level 0. So we get the column no. See
main() function.
3. Now we need to find the Row no., so we have created four functions corresponding to each
column. Like if any button of column one is pressed, we call function row_finder1(), to find
the row no.
4. In row_finder1() function, we reversed the logic levels, means now all the Rows are 1 and
columns are 0. Now Row of the pressed button should be 0 because it has become connected
(shorted) to the column whose button is pressed, and all the columns are at 0 logic. So we
have scanned all rows for 0.
5. So whenever we find the Row at logic 0, means that is the row of pressed button. So now
we have column no (got in step 2) and row no., and we can print no. of that button using
lcd_data function.
Same procedure follows for every button press, and we are using while(1), to continuously
check, whether button is pressed or not.
Code:
#include<reg51.h>
#define display_port P2 //Data pins connected to port 2 on microcontroller
sbit rs = P3^0; //RS pin connected to pin 2 of port 3
sbit rw = P3^1; // RW pin connected to pin 3 of port 3
sbit e = P3^2; //E pin connected to pin 4 of port 3
if(R1==0)
lcd_data('7');
if(R2==0)
lcd_data('4');
if(R3==0)
lcd_data('1');
if(R4==0)
lcd_data('N');
}
if(R1==0)
lcd_data('8');
if(R2==0)
lcd_data('5');
if(R3==0)
lcd_data('2');
if(R4==0)
lcd_data('0');
}
void row_finder3() //Function for finding the row for column 3
{
R1=R2=R3=R4=1;
C1=C2=C3=C4=0;
if(R1==0)
lcd_data('9');
if(R2==0)
lcd_data('6');
if(R3==0)
lcd_data('3');
if(R4==0)
lcd_data('=');
}
if(R1==0)
lcd_data('%');
if(R2==0)
lcd_data('*');
if(R3==0)
lcd_data('-');
if(R4==0)
lcd_data('+');
}
void main()
{
lcd_init();
while(1)
{
msdelay(30);
C1=C2=C3=C4=1;
R1=R2=R3=R4=0;
if(C1==0)
row_finder1();
else if(C2==0)
row_finder2();
else if(C3==0)
row_finder3();
else if(C4==0)
row_finder4();
}
This is how to interface a seven segment LED display to an 8051 microcontroller. 7 segment
LED display is very popular and it can display digits from 0 to 9 and quite a few characters.
Knowledge about how to interface a seven segment display to a micro controller is very
essential in designing embedded systems. Seven segment displays are of two types, common
cathode and common anode.
In common cathode type , the cathode of all LEDs are tied together to a single terminal which
is usually labeled as ‘com‘ and the anode of all LEDs are left alone as individual pins
labeled as a, b, c, d, e, f, g & h (or dot) .
In common anode type, the anodes of all LEDs are tied together as a single terminal and
cathodes are left alone as individual pins.
Program:
In this, we will have brief discussion on how to interface 16×2 LCD module to P89V51RD2,
which is an 8051 family microcontroller. We use LCD display for the displaying messages in
a more interactive way to operate the system or displaying error messages etc. Interfacing
16×2 LCD with 8051 microcontroller is very easy if you understanding the working of LCD.
16×2 Liquid Crystal Display which will display the 32 characters at a time in two rows (16
characters in one row). Each character in the display is of size 5×7 pixel matrix.
PIN
NAME FUNCTION
NO
1 VSS Ground pin
2 VCC Power supply pin of 5V
3 VEE Used for adjusting the contrast commonly attached to the
potentiometer.
4 RS RS is the register select pin used to write display data to the LCD
(characters), this pin has to be high when writing the data to the
LCD. During the initializing sequence and other commands this pin
should low.
5 R/W Reading and writing data to the LCD for reading the data R/W pin
should be high (R/W=1) to write the data to LCD R/W pin should be
low (R/W=0)
7 DB0 DB0-DB7 Data pins for giving data(normal data like numbers
characters or command data) which is meant to be displayed
Program:
#include<reg51.h>
sbit rs=P3^0;
sbit rw=P3^1;
sbit en=P3^2;
void lcdcmd(unsigned char);
void lcddat (unsigned char);
void delay();
void main()
{
P2=0x00;
while(1)
{
lcdcmd(0x38);
delay();
lcdcmd(0x01);
delay();
lcdcmd(0x10);
delay();
lcdcmd(0x0c);
delay();
lcdcmd(0x81);
delay();
lcddat('I');
delay();
lcddat('A');
delay();
lcddat('R');
delay();
lcddat('E');
delay();
}
}
void lcdcmd(unsigned char val)
{
P2=val;
rs=0;
rw=0;
en=1;
delay();
en=0;
}
void lcddat(unsigned char val)
{
P2=val;
rs=1;
rw=0;
en=1;
delay();
en=0;
}
void delay()
{unsigned int i;
for(i=0;i<6000;i++);
}
This section will show how to interface a DAC (digital-to-analog converter) to the 8051.
Then we demonstrate how to generate a sine wave on the scope using the DAC.
Therefore, an 8-input DAC such as the DAC0808 provides 256 discrete voltage (or current)
levels of output. Similarly, the 12-bit DAC provides 4096 discrete voltage levels. There are
also
16-bit DACs, but they are more expensive.
𝐷7 𝐷6 𝐷5 𝐷4 𝐷3 𝐷2 𝐷1 𝐷0
𝐼𝑜𝑢𝑡 = 𝐼𝑟𝑒𝑓 ( 2 + + + 16 + 32 + 64 + 128 + 256)
4 8
Where DO is the LSB, D7 is the MSB for the inputs, and Iref is the input current that must be
applied to pin 14. The Iref current is generally set to 2.0 mA. Figure shows the generation of
current reference (setting Iref = 2 mA) by using the standard 5-V power supply and IK and
1.5K-ohm standard resistors. Some DACs also use the zener diode (LM336), which
overcomes any fluctuation associated
Ideally we connect the output pin Iout to a resistor, convert this current to voltage, and monitor
the output on the scope. In real life, however, this can cause inaccuracy since the input
resistance of the load where it is connected will also affect the output voltage. For this reason,
the Iref current output is isolated by connecting it to an op-amp such as the 741 with Rf = 5K
ohms for the feedback resistor. Assuming that R = 5K ohms, by changing the binary input,
the output voltage changes.
Vout of DAC for various angles is calculated and shown in Table 13-7. See Example 13-5 for
verification of the calculations.
0 0 5 128
30 0.5 7.5 192
60 0.866 9.33 238
90 1.0 10 255
120 0.866 9.33 238
150 0.5 7.5 192
180 0 5 128
210 -0.5 2.5 64
240 -0.866 0.669 17
270 -1.0 0 0
300 -0.866 0.669 17
330 -0.5 2.5 64
360 0 5 128
Program:
#include <reg51.h>
sfr DACDATA = Pl;
void main ()
{
unsigned char WAVEVALUE [12]={128,192,238,255, 238,192,128,64, 17,0,17,64} ;
unsigned char x ,
while (1)
{
for(x=0;x<12;x++)
{
DACDATA = WAVEVALUE[x];
}
}
}
Figure: Angle vs. Voltage Magnitude for Sine Wave
The advantage of interrupts is that the microcontroller can serve many devices (not all at the
same time, of course); each device can get the attention of the microcontroller based on the
priority assigned to it.
The polling method cannot assign priority since it checks all devices in a round robin fashion.
• Its bit sequence and their meanings are shown in the following figure.
It disables all interrupts.
EA IE.7 When EA = 0 no interrupt will be acknowledged and
When EA = 1 enables the interrupt individually.
Since IBM PC/compatible computers are so widely used to communicate with 8051-based
systems, serial communications of the 8051 with the COM port of the PC will be
emphasized. To allow data transfer between the PC and an 8051 system without any error,
we must make sure that the baud rate of the 8051 system matches the baud rate of the PC‟s
COM port.
The 8051 transfers and receives data serially at many different baud rates. Serial
communications of the 8051 is established with PC through the COM port. It must make sure
that the baud rate of the 8051 system matches the baud rate of the PC's COM port/ any
system to be interfaced. The baud rate in the 8051 is programmable. This is done with the
help of Timer. When used for serial port, the frequency of timer tick is determined by
(XTAL/12)/32 and 1 bit is transmitted for each timer period (the time duration from timer
start to timer expiry).
The Relationship between the crystal frequency and the baud rate in the 8051 is that the 8051
divides the crystal frequency by 12 to get the machine cycle frequency which is shown in
figure1. Here the oscillator is XTAL = 11.0592 MHz, the machine cycle frequency is 921.6
kHz. 8051's UART divides the machine cycle frequency of 921.6 kHz by 32 once more
before it is used by Timer 1 to set the baud rate. 921.6 kHz divided by 32 gives 28,800 Hz.
Timer 1 must be programmed in mode 2, that is 8-bit, auto-reload.
In serial communication if data transferred with a baud rate of 9600 and XTAL used is
11.0592 then following is the steps followed to find the TH1 value to be loaded.
Baud rate is selected by timer1 and when Timer 1 is used to set the baud rate it must be
programmed in mode 2 that is 8-bit, auto-reload. To get baud rates compatible with the PC,
we must load TH1 with the values shown in Table 1.
Table.1 Timer 1 THI register values for different baud rates
The fifth bit is TB8 which is used by modes 2 and 3 for the 8-bit transmission. When mode 1
is used the pin TB8 should be cleared. The sixth bit RB8 is used by modes 2 and 3 for the
reception of bit 8. It is used by mode1 to store the stop bit. The seventh bit is TI which is the
Transmit Interrupt. When 8051 finishes the transfer of the 8-bit character, it sets TI to ''1'' to
indicate that it is ready to transfer the next character. The TI is raised at the beginning of the
stop bit. The last bit is the RI which is the receive interrupt. When 8051 receives a
character,the UART removes start bit and stop bit. The UART puts the 8-bit character in
SBUF. RI is set to „1‟ to indicate that a new byte is ready to be picked up in SBUF.RI is
raised halfway through the stop bit
Program to receive bytes of data serially, and put them in P2, set the baud rate at 9600,
8-bit data, and 1 stop bit:
MOV TMOD, #20H ; timer 1,mode 2(auto reload)
MOV TH1, #-3 ; 9600 baud rate
MOV SCON, #50H ; 8-bit, 1 stop, REN enabled
SETB TR1 ; start timer 1
HERE: JNB RI, HERE ; wait for char to come in
MOV A, SBUF ; saving incoming byte in A
MOV P2, A ; send to port 1
CLR RI ; get ready to receive next byte
SJMP HERE ; keep getting data
Importance of the RI flag bit:
It receives the start bit, next bit is the first bit of the character about to be received. When
the last bit is received, a byte is formed and placed in SBUF. when stop bit is received, it
makes RI = 1 indicating entire character byte has been received and can be read before
overwritten by next data. When RI=1, received byte is in the SBUF register, copy SBUF
contents to a safe place. After the SBUF contents are copied the RI flag bit must be
cleared to 0.
Increasing the baud rate:
PCON
It is 8-bit register. When 8051 is powered up, SMOD is zero. By setting the SMOD, baud rate
can be doubled. If SMOD = 0 (which is its value on reset), the baud rate is 1/64 the oscillator
frequency. If SMOD = 1, the baud rate is 1/32 the oscillator frequency.
The key difference between an operating system such as Windows and an RTOS
often found in embedded systems is the response time to external events. An
ordinary OS provides a non-deterministic response to events with no guarantee
with respect to when they will be processed, albeit while trying to stay responsive.
The user perceiving the OS to be responsive is more important than handling
underlying tasks. On the other hand, an RTOS' goal is fast and more deterministic
reaction.
Developers used to OS‘s such as Windows or Linux will be quite familiar with the
characteristics of an embedded RTOS. They are designed to run in systems with
limited memory, and to operate indefinitely without the need to be reset.
Many embedded programmers shy away from using an RTOS because they
suspect that it adds too much complexity to their application, or it is simply
unknown territory. An RTOS typically requires anything up to 5% of the CPU‘s
resources to perform its duties. While there will always be some resource penalties,
an RTOS can make up for it in areas such as simplified determinism, ease of use
though HW abstraction, reduced development time and easier debugging.
Using an RTOS means you can run multiple tasks concurrently, bringing in the
basic connectivity, privacy, security, and so on as and when you need them. An
RTOS allows you to create an optimized solution for the specific requirements of
your project.
REAL TIME OPERATING SYSTEM (RTOS)
A Real Time Operating Systems which strictly adheres to the timing constraints for
a task.
A Hard Real Time system must meet the deadlines for a task without any
slippage
Missing any deadline may produce catastrophic results for Hard Real Time
Systems, including permanent data lose and irrecoverable damages to the
system/users
Air bag control systems and Anti-lock Brake Systems (ABS) of vehicles are
typical examples of Hard Real Time Systems
As a rule of thumb, Hard Real Time Systems does not implement the virtual
memory model for handling the memory. This eliminates the delay in swapping in
and out the code corresponding to the task to and from the primary memory
The presence of Human in the loop (HITL) for tasks introduces un- expected
delays in the task execution. Most of the Hard Real Time Systems are automatic
and does not contain a ‗human in the loop‘
These operating systems guarantee that critical tasks be completed within a range
of time.
For example, a robot is hired to weld a car body. If the robot welds too early or too
late, the car cannot be sold, so it is a hard real-time system that requires complete
car welding by robot hardly on the time., scientific experiments, medical imaging
systems, industrial control systems, weapon systems, robots, air traffic control
systems, etc
2. Soft real-time operating system:
Real Time Operating Systems that does not guarantee meeting deadlines, but, offer
the best effort to meet the deadline
Missing deadlines for tasks are acceptable if the frequency of deadline missing
is within the compliance limit of the Quality of Service(QoS)
A Soft Real Time system emphasizes on the principle ‗A late answer is an
acceptable answer, but it could have done bit faster’
Soft Real Time systems most often have a ‗human in the loop (HITL)‘
An audio video play back system is another example of Soft Real Time
system. No potential damage arises if a sample comes late by fraction of a second,
for play back.
ADVANTAGES:
The advantages of real-time operating systems are as follows-
1. Maximum consumption –
Maximum utilization of devices and systems. Thus more output from all the
resources.
2. Task Shifting –
Time assigned for shifting tasks in these systems is very less. For example, in
older systems, it takes about 10 microseconds. Shifting one task to another and
in the latest systems, it takes 3 microseconds.
3. Focus On Application –
Focus on running applications and less importance to applications that are in
the queue.
5. Error Free –
These types of systems are error-free.
6. Memory Allocation –
Memory allocation is best managed in these types of systems.
DISADVANTAGES:
The disadvantages of real-time operating systems are as follows-
1. Limited Tasks –
Very few tasks run simultaneously, and their concentration is very less on few
applications to avoid errors.
3. Complex Algorithms –
The algorithms are very complex and difficult for the designer to write on.
5. Thread Priority –
It is not good to set thread priority as these systems are very less prone to
switching tasks.
The terms ‗Task‘, ‗job‘ and ‗Process‘ refer to the same entity in the Operating
System context and most often they are used interchangeably
A process requires various system resources like CPU for executing the
process, memory for storing the code corresponding to the process and associated
variables, I/O devices for information exchange etc
A process mimics a processor in properties and holds a set of registers, process
status, a Program Counter (PC) to point to the next executable instruction of the
process, a stack for holding the local variables associated with the process and the
code corresponding to the process
A process, which inherits all the properties of the CPU, can be considered as a
virtual processor, awaiting its turn to have its properties switched into the physical
processor.
When the process gets its turn, its registers and Program counter register
becomes mapped to the physical registers of the CPU
Memory organization of Processes:
The memory occupied by the process is segregated into three regions namely;
Stack memory, Data memory and Code memory.
The Stack memory holds all temporary data such as variables local to the process
Data memory holds all global data for the process
The Code memory contains the program code (instructions) corresponding to the
process
Process States & State Transition
The creation of a process to its termination is not a single step operation
The process traverses through a series of states during its transition from the
newly created state to the terminated state
The cycle through which a process changes its state from ‗newly created‘ to
‗execution completed‘ is known as ‗Process Life Cycle‘. The various states through
which a process traverses through during a Process Life Cycle indicates the current
status of the process with respect to time and also provides information on what it
is allowed to do next
Process States & State Transition:
Running State: The state where in the source code instructions corresponding
to the process is being executed is called ‗Running State‘. Running state is the state
at which the process execution happens
When a process changes its state from Ready to running or from running to
blocked or terminated or from blocked to running, the CPU allocation for the
process may also change
Threads
Different threads, which are part of a process, share the same address space;
meaning they share the data memory, code memory and heap memory area
Threads maintain their own thread status (CPU register values), Program
Counter (PC) and stack
MULTIPLE TASKS AND MULTIPLE PROCESSES
The text compression box provides a simple example of rate control problems. A
control panel on a machine provides an example of a different type of rate con-
troll problem, the asynchronous input. The control panel of the compression box
may, for example, include a compression mode button that disables or enables
com- pression, so that the input text is passed through unchanged when
compression is disabled. We certainly do not know when the user will push the
compression modebutton— the button may be depressed a synchronously relative
to the arrival of characters for compression. We do know, however, that the button
will be depressed at a much lower rate than characters will be received, since it is
not physically possible for a person to repeatedly depress a button at even slow
serial line rates. Keeping up with the input and output data while checking on the
button can introduce some very complex control code in to the program. Sampling
the button‘s state too slowly can cause the machine to miss a button depression
entirely, but sampling it too frequently and duplicating a data value can cause the
machine to in correctly compress data.
This is the sort of control that processes allow. The above two examples illustrate
how requirements on timing and execution rate can create major problems in
programming. When code is written to satisfy several different timing
requirements at once, the control structures necessary to get any sort of solution
become very complex very quickly. Worse, such complex control is usually quite
difficult to verify for either functional or timing properties.
• Tasks are units of sequential code implementing the system actions and executed
concurrently by an OS.
• Real time systems require that tasks be performed within a particular time frame.
Task is related to the performance of the real time systems.
• A task, also called a thread, is a simple program that thinks it has the CPU all to
itself. The design process for a real-time application involves splitting the work to
be done into tasks responsible for a portion of the problem.
• Each task is assigned a priority, its own set of CPU registers and its own stack
area.
• In the specified time constraint, system must produce its correct output. If system
fail to meet the specified output, then the system is fail or quality decreases.
• Real time systems are used for space flights, air traffic control, high speed
aircraft, telephone switching, electricity distribution, industrial processes etc.
• Real time system must be 100 % responsive 100 % of the time. Response time is
measured in fractions of second, but this is an ideal not often achieved in the field.
• Real time database is updated continuously. In aircraft example, flight data is
continuously changing so it is necessary to update. It includes speed, direction,
location, height etc.
• A process is a sequential program in execution. Terms like job and task are also
used to denote a process.
• A process is a dynamic entity that executes a program on a particular set of data.
Multiple processes may be associated with one program.
• Task is a single instance of an executable program.
Context switching refers to the switching of execution context from task to other
• Input and output of the compressor box is serial ports. It takes uncompressed data
and processes it. Output of the box is compressed data. Given data is compressed
using predefined compression table. Modem is used such type of box.
• The program's need to receive and send data at different rates. It is an example of
rate control problems. It uses asynchronous input. You can provide a button for
compressed mode and uncompressed mode.
• When user press uncompressed mode, the input data is passed through
unchanged.
• The button will be depressed at a much lower rate than characters will be
received, since it is not physically possible for a person to repeatedly depress a
button at even slow serial line rates.
• Keeping up with the input and output data while checking on the button can
introduce some very complex control code into the program.
• Sampling the button's state too slowly can cause the machine to miss a button
depression entirely, but sampling it too frequently and duplicating a data value can
cause the machine to incorrectly compress data.
• This problem is solved by maintaining counter.
Multitasking – Context Switching:
Task Scheduling:
In a multitasking system, there should be some mechanism in place to share the
CPU among the different tasks and to decide which process/task is to be executed
at a given point of time
The scheduling policies are implemented in an algorithm and it is run by the
kernel as a service
Depending on the scheduling policy the process scheduling decision may take
place when a process switches its state to
‗Ready‘ state from ‗Running‘ state
‗Blocked/Wait‘ state from ‗Running‘ state
‗Ready‘ state from ‗Blocked/Wait‘ state
‗Completed‘ state
• Turnaround Time: It is the amount of time taken by a process for completing its
execution. It includes the time spent by the process for waiting for the main
memory, time spent in the ready queue, time spent on completing the I/O
operations, and the time spent in execution. The turnaround time should be a
minimum for a good scheduling algorithm.
• Waiting Time: It is the amount of time spent by a process in the ‗Ready‘ queue
waiting to get the CPU time for execution. The waiting time should be minimal for
a good scheduling algorithm.
• Response Time: It is the time elapsed between the submission of a process and
the first response. For a good scheduling algorithm, the response time should be as
least as possible.
It is same as any real world application where queue systems are used; E.g.
Ticketing
Drawbacks:
Favors monopoly of process. A process, which does not contain any I/O
operation, continues its execution until it finishes its task
In general, FCFS favors CPU bound processes and I/O bound processes may
have to wait until the completion of CPU bound process, if the currently executing
process is a CPU bound process. This leads to poor device utilization.
The average waiting time is not minimal for FCFS scheduling algorithm
LCFS scheduling is also known as Last In First Out (LIFO) where the process,
which is put last into the ‗Ready‘ queue, is serviced first
Drawbacks:
Favors monopoly of process. A process, which does not contain any I/O
operation, continues its execution until it finishes its task
In general, LCFS favors CPU bound processes and I/O bound processes may
have to wait until the completion of CPU bound process, if the currently executing
process is a CPU bound process. This leads to poor device utilization.
The average waiting time is not minimal for LCFS scheduling algorithm
The average waiting time for a given set of processes is minimal in SJF
scheduling
Drawbacks:
A process whose estimated execution completion time is high may not get a
chance to execute if more and more processes with least estimated execution time
enters the ‗Ready‘ queue before the process with longest estimated execution time
starts its execution
May lead to the ‗Starvation‘ of processes with high estimated completion time
Difficult to know in advance the next shortest process in the ‗Ready‘ queue for
scheduling since new processes with different estimated execution time keep
entering the ‗Ready‘ queue at any point of time.
The priority of a task is expressed in different ways, like a priority number, the
time required to complete the execution etc.
The priority is assigned to the task on creating it. It can also be changed
dynamically (If the Operating System supports this feature)
The non-preemptive priority based scheduler sorts the ‗Ready‘ queue based on
the priority and picks the process with the highest level of priority for execution.
Drawbacks:
Similar to SJF scheduling algorithm, non-preemptive priority based algorithm
also possess the drawback of ‗Starvation‘ where a process whose priority is low
may not get a chance to execute if more and more processes with higher priorities
enter the ‗Ready‘ queue before the process with lower priority starts its execution.
The technique of gradually raising the priority of processes which are waiting
in the ‗Ready‘ queue as time progresses, for preventing ‗Starvation‘, is known as
‗Aging‘.
Preemptive scheduling:
Employed in systems, which implements preemptive multitasking model
Every task in the ‗Ready‘ queue gets a chance to execute. When and how often
each process gets a chance to execute (gets the CPU time) is dependent on the type
of preemptive scheduling algorithm used for scheduling the processes
When to pre-empt a task and which task is to be picked up from the ‗Ready‘
queue for execution after preempting the current task is purely dependent on the
scheduling algorithm
A task which is preempted by the scheduler is moved to the ‗Ready‘ queue. The
act of moving a ‗Running‘ process/task into the ‗Ready‘ queue by the scheduler,
without the processes requesting for it is known as‗Preemption‘
If the execution time of the new process is less, the currently executing process
is
preempted and the new process is scheduled for execution
Always compares the execution completion time (ie the remaining execution
time for the new process) of a new process entered the ‗Ready‘ queue with the
remaining time for completion of the currently executing process and schedules the
process with shortest remaining time for execution.
Once each process in the ‗Ready‘ queue is executed for the pre-defined time
period, the scheduler comes back and picks the first process in the ‗Ready‘ queue
again for execution.
Round Robin scheduling is similar to the FCFS scheduling and the only
difference is that a time slice based preemption is added to switch the execution
between the processes in the ‗Ready‘ queue
Preemptive scheduling – Priority based Scheduling
Same as that of the non-preemptive priority based scheduling except for the
switching of execution between tasks
In preemptive priority based scheduling, any high priority process entering the
‗Ready‘ queue is immediately scheduled for execution whereas in the non-
preemptive scheduling any high priority process entering the ‗Ready‘ queue is
scheduled only after the currently executing process completes its execution or
only when it voluntarily releases the CPU
EXAMPLE: Three processes with process IDs P1, P2, P3 with estimated
completion time 10, 5, 7 milliseconds and priorities 1, 3, 2 (0- highest priority, 3
lowest priority) respectively enters the ready queue together. A new process P4
with estimated completion time 6ms and priority 0 enters the ‗Ready‘ queue after
5ms of start of execution of P1. Assume all the processes contain only CPU
operation and no I/O operations are involved.
Solution: At the beginning, there are only three processes (P1, P2 and P3)
available in the ‗Ready‘ queue and the scheduler picks up the process with the
highest priority (In this example P1 with priority 1) for scheduling. Now process
P4 with estimated execution completion time 6ms and priority 0 enters the ‗Ready‘
queue after 5ms of start of execution of P1. The processes are re-scheduled for
execution in the following order
The waiting time for all the processes are given as
Waiting Time for P1 = 0 + (11-5) = 0+6 =6 ms (P1 starts executing first and gets
Preempted by P4 after 5ms and again gets the CPU time after completion of P4)
Waiting Time for P4 = 0 ms (P4 starts executing immediately on entering the
‗Ready‘ queue, by preempting P1)
Waiting Time for P3 = 16 ms (P3 starts executing after completing P1 and P4)
Waiting Time for P2 = 23 ms (P2 starts executing after completing P1, P4 and P3)
Average waiting time = (Waiting time for all the processes) / No. of Processes
= (Waiting time for (P1+P4+P3+P2)) / 4
= (6 + 0 + 16 + 23)/4 = 45/4
= 11.25 milliseconds
Turn Around Time (TAT) for P1 = 16 ms (Time spent in Ready Queue + Execution Time)
Turn Around Time (TAT) for P4 = 6ms (Time spent in Ready Queue + Execution Time
= (Execution Start Time – Arrival Time) + Estimated Execution Time = (5-5) + 6 = 0 + 6)
Turn Around Time (TAT) for P3 = 23 ms (Time spent in Ready Queue + Execution Time) Turn
Around Time (TAT) for P2 = 28 ms (Time spent in Ready Queue + Execution Time) Average
Turn Around Time= (Turn Around Time for all the processes) / No. of Processes
= (Turn Around Time for (P2+P4+P3+P1)) / 4
= (16+6+23+28)/4 = 73/4
= 18.25 milliseconds
PRIORITY SCHEDULING
The processes with higher priority should be carried out first, whereas jobs with
equal priorities are carried out on a round-robin or FCFS basis. Priority depends
upon memory requirements, time requirements, etc.
Preemptive Scheduling
In Preemptive Scheduling, the tasks are mostly assigned with their priorities.
Sometimes it is important to run a task with a higher priority before another lower
priority task, even if the lower priority task is still running. The lower priority task
holds for some time and resumes when the higher priority task finishes its
execution.
Non-Preemptive Scheduling
In this type of scheduling method, the CPU has been allocated to a specificprocess.
The process that keeps the CPU busy, will release the CPU either byswitching
context or terminating. It is the only method that can be used forvarious hardware
platforms. That’s because it doesn’t need special hardware(for example, a timer)
like preemptive scheduling.
Consider following five processes P1 to P5. Each process has its unique
priority,burst time, and arrival time.
Step 0) At time=0, Process P1 and P2 arrive. P1 has higher priority than P2. The
execution begins with process P1, which has burst time 4.
Step 1) At time=1, no new process arrive. Execution continues with P1.
Step 2) At time 2, no new process arrives, so you can continue with P1. P2 is in the
waiting queue.
Step 3) At time 3, no new process arrives so you can continue with P1. P2 process
still in the waiting queue.
Step 16) At time= 16, P5 is finished with its execution. P4 is the only process left.
It starts execution.
Step 17) At time =20, P5 has completed execution and no process is left.
Step 18) Let’s calculate the average waiting time for the above example.
Waiting Time = start time – arrival time + wait time for next burst
Advantages of priority scheduling
Here, are benefits/pros of using priority scheduling method:
If the system eventually crashes, all low priority processes get lost.
If high priority processes take lots of CPU time, then the lower priority
processes may starve and will be postponed for an indefinite time.
This scheduling algorithm may leave some low priority processes waiting
indefinitely.
A process will be blocked when it is ready to run but has to wait for the CPU
because some other process is running currently.
If a new higher priority process keeps on coming in the ready queue, then
the process which is in the waiting state may need to wait for a long duration
of time.
Summary: