0% found this document useful (0 votes)
10 views

Unit-2

The document discusses memory and I/O interfacing for the 8051 microcontroller, detailing the interfacing of external ROM and RAM. It explains the use of multiplexed data and address lines, address latching, and the generation of read and write signals. Additionally, it covers absolute and linear decoding methods for memory addressing, providing examples of memory mapping for different configurations.

Uploaded by

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

Unit-2

The document discusses memory and I/O interfacing for the 8051 microcontroller, detailing the interfacing of external ROM and RAM. It explains the use of multiplexed data and address lines, address latching, and the generation of read and write signals. Additionally, it covers absolute and linear decoding methods for memory addressing, providing examples of memory mapping for different configurations.

Uploaded by

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

TOPIC 6

MEMORY AND I/O INTERFACING


MEMORY INTERFACING
i. External ROM (program memory) Interfacing

P1 P0 D0-D7

EA A0
| ROM/
8051 LATCH A7 EPROM
ALE
clock
A8 Address
P3 | lines
A15
PSEN OE

FIGURE 1 INTERFACING OF ROM/EPROM TO µC 8051.

above figure shows how to access or interface ROM to 8051.


port 0 is used as multiplexed data & address lines.
it gives lower order (A7-A0) 8 bit address in initial T cycle & higher
order (A8-A15) used as data bus.
8 bit address is latched using external latch & ALE signal from 8051.
port 2 provides higher order (A15-A8) 8 bit address.
PSEN is used to activate the output enable signal of external
ROM/EPROM.

ii. External RAM (data memory) Interfacing

P1 D0 data
P0 | lines
D7
RAM
8051 LATCH A0
ALE clock |
A7 address
lines

RD P3 P2

Chapter: 6 MEMORY AND I/O INTERFACING


WR WR OE

FIGURE 2 INTERFACING OF RAM(DATA MEMORY) TO µC 8051.

above figure shows how to connect or interface external RAM(data


memory) to 8051.
port 0 is used as multiplexed data & address lines.
address lines are decoded using external latch & ALE signal from 8051
to provide lower order (A7-A0) address lines.
port 2 gives higher order address lines.
RD & WR signals from 8051 selects the memory read & memory write
operations respectively.
RD & WR signals: generally P3.6 & P3.7 pins of port 3 are used
to generate meamory read and memory write
signals.
remaining pins of port 3 i.e. P3.0-P3.5 can be used for other
functions.

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

FIGURE 3 MEMORY (RAM) INTERFACING USING ABSOLUTE DECODING.

ii. Linear Decoding (Partial Decoding)


for small systems : individual higher order address lines used
to select memory chip.

replacing the hardware by


decoding logic.

reducing the cost of decoding, drawback is- multiple addresses.


as shown in figure below, A14 line is directly connected to chip
select line, A15 line not connected anywhere, kept open.
so, status of A15- not considered for generation of chip select
signal.

Chapter: 6 MEMORY AND I/O INTERFACING


Vss
P0.7 D7-D0
EA |
P0.0
74LS373 A7-A0

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

FIGURE 4 MEMORY (RAM) INTERFACING USING LINEAR DECODING.

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.

Chapter: 6 MEMORY AND I/O INTERFACING


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

FIGURE 5 16K X 8 MEMORY (RAM) INTERFACING TO µC 8051.


3
Example 2: Design a µController system using 8051.Interface the external ROM of
size 4k x 8.
Solution: Given, Memory size: 4k
that means we require 2n=4k :: n address lines
here n=12 :: A0 to A11 address lines are required.
remaining lines A0, A0, A0, A0 & PSEN are connected though OR gate to CS &
RD of external ROM.
when A0 to A0 are low (logic ‘0’), only then external ROM is selected.
Address Decoding(Memory Map)for 4k x 8 RAM.
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 0 1 1 1 1 1 1 1 1 1 1 1 1 0FFFH
Vss
P0.7 D7-D0
EA |
P0.0
74LS373 A7-A0

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

FIGURE 6 4K X 8 MEMORY (ROM) INTERFACING TO µC 8051.

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.

Chapter: 6 MEMORY AND I/O INTERFACING


A14,A15,PSEN ORed CS

when low – ROM is selected.

Memory size- RAM :32k


that means we require 2n=32k :: n address lines
here n=15 :: A0 to A15 address lines are required.

A15 inverted(NOT Gate) CS

when high- RAM is selected.

PSEN is used as chip select pin ROM.


RD is used as read control signal pin. for RAM
WR is used as write control signal pin. selection.

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

ALE G OC 16k x 8 32k x 8


8051 ROM RAM
P2.0
| A8-A13 A8-A13
P2.5
P2.6 To
P2.7 CS CS(A15)
P2.7
To
PSEN P2.6 A14
P3.6 RD
RD WR
P3.7

FIGURE 7 16K X 8 ROM AND 32K X 8 RAM INTERFACING TO µC 8051.

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.

Chapter: 6 MEMORY AND I/O INTERFACING


A13,A14,A15,PSEN ORed CS

when low – program ROM is selected.

Memory size- RAM :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

when high- data RAM is selected.

PSEN is used as chip select pin ROM.


RD is used as read control signal pin. for RAM
WR is used as write control signal pin. selection.

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

FIGURE 8 8K X 8 ROM AND 8K X 8 RAM INTERFACING TO µC 8051.

Chapter: 6 MEMORY AND I/O INTERFACING

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.

port B programmed as input or output : with or without handshaking


signals.
port C divided in two parts : port C upper port C lower

(PC4-PC7) (PC0-PC3)

can be programmed as an input or output port.

can be individually set/reset to generate control signals.


40 pin DIP chip.
8255 Block Diagram: PA
Group A
Group A
Port A
Control
(8)
PA7-PA0

PC
Bidirectional Group A
data bus
Data Port C PC7-PC4
Bus upper(4)
D7-D0 buffer

Chapter: 6 MEMORY AND I/O INTERFACING


I/O
ports
PC
Group B
Port C PC3-PC0
RD lower(4)

WR
Read/
A0 Write
control
A1 logic PB
Group B
Reset Group B
Control Port B PB7-PB0
(8)

CS

FIGURE 9 BLOCK DIAGRAM OF 8255A.

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

Chapter: 6 MEMORY AND I/O INTERFACING


CS 6 35 RESET

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

Chapter: 6 MEMORY AND I/O INTERFACING


A1 | A0 | RD | WR | CS | OPERATION
-----------------------------------------------------------------
Input (read) operation
0 | 0 | 0 | 1 | 0 | port A to data bus.
0 | 1 | 0 | 1 | 0 | port B to data Bus.
1 | 0 | 0 | 1 | 0 | port C to data bus.
-----------------------------------------------------------------
Output (write) operation
0 | 0 | 1 | 0 | 0 | data bus to port A.
0 | 1 | 1 | 0 | 0 | data bus to port B.
1 | 0 | 1 | 0 | 0 | data bus to port C.
1 | 1 | 1 | 0 | 0 | data bus to control register.
-----------------------------------------------------------------
Disable Function
X | X | X | X | 1 | data bus tri-stated.
1 | 1 | 0 | 1 | 0 | illegal condition.
X | X | 1 | 1 | 0 | data bus tri-stated.
-----------------------------------------------------------------

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.

to transfer data between devices whose


data transfer speeds are not same.

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.

make use of handshaking signals


(PC3-PC7) for Port A only.

both inputs and outputs are latched.


when peripheral request processor, data is sent from CPU through Port A
appears on bus.
Port C lines are used for simple I/O functions.
Port B- programmed in Mode 0 or Mode 1.

PC0-PC2 used for handshaking.

CONTROL WORDS FORMATS Chapter: 6 MEMORY AND I/O INTERFACING


8255 PPI got inbuilt control registers.

also called as control or


command word register.

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

0 for X X X 0 0 0 PC0 in BSR Mode


BSR mode. 0 0 1 PC1 1 - set
0 1 0 PC2 0 - reset
0 1 1 PC3
1 0 0 PC4
1 0 1 PC5
1 1 0 PC6
1 1 1 PC7
FIGURE 10 BSR CONTROL WORD FORMAT.

2. for I/O mode:

D7 D6 D5 D4 D3 D2 D1 D0

1 for Port A mode seln Group B


i/o mode mode selection 1- i/p 0- mode 0 PCL
0 0 mode 0 0- o/p 1- mode 1 1- i/p
0 1 mode 1 Group A Port B 0- o/p
1 x mode 2 PCU 1- i/p
1- i/p 0- o/p
0- o/
FIGURE 11 BSR CONTROL WORD FORMAT FOR I/O MODE.

I/O PORT EXPANSION USING 8255

P2.7 CHIP
SELECT CS
|
P2.0 LOGIC PA
PB
PC
ALE
8255
8051 G

Chapter: 6 MEMORY AND I/O INTERFACING


AD7
P0.7 A1 A1
| 74LS373
A0
A0
P0.0 AD0 OC
RD WR D7
D7 RES

D0 WR RD
D0

FIGURE 12 8051 CONNECTION TO THE 8255.

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

FIGURE 13-A 8051 PORT 1 CONNECTION TO SWITCHES(KEYS).

AS shown in above figure 13-A 8 push buttons are connected to port 1.


Vcc

P0.0

P0.1

Chapter: 6 MEMORY AND I/O INTERFACING


PORT 0 P0.2

P0.3

P0.4

8051 P0.5

P0.6

P0.7

FIGURE 13-B 8051 PORT 0 CONNECTION TO LEDS.

as shown in above figure 13-B 8 LEDs (in common anode configuration)


are connected to port 0.
PORT 1- input port
PORT 0- output port
12
when push button pressed, bounce(make & break) take place ... before
firm contact.
soln to this is wait for 10- 20 sec till key is settled & then key is
checked again.

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

Chapter: 6 MEMORY AND I/O INTERFACING

PORT 2
P2.4 1-2
DECODER
1k

1k . .
FIGURE 14 8051 PORT 0 CONNECTION TO 7 SEGMENT DISPLAY.

3. Interfacing Of Stepper Motor


stepper motor: stepping or step motor

rotates in fixed steps. 13


if rotor rotates 90º in each step(from one pole segment to another)-
full step motor.

Coil 1
ROTOR

ROTOR
Coil 4 Coil 2

Coil 3
STATOR STATOR
(14-b 1)
(14-a)

FIGURE 14-a INSIGHT OF STEPPER MOTOR.

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)

FIGURE 14-b FULL STEP STEPPER MOTOR DRIVE SEQUENCE.

stepper motor may also be operated with half step sequence.

rotor rotates through 45º in


each step.

common stepping sequence- 1.8º, 7.5º and 15º etc.


---------------------------------------------

Chapter: 6 MEMORY AND I/O INTERFACING


step sequence | No. of steps required
| for 1 rotation
---------------------------------------------
1.8º | (360º/1.8º=) 200 steps
7.5º | (360º/7.5º=) 48 steps
15º | (360º/15º=) 24 steps
---------------------------------------------
figure below shows the drive sequence for half step stepper motor.
Coil 1
Coil 1
Coil 1

Coil 4 Coil 2 Coil 4 Coil 2 Coil 4 Coil 2


Coil 3
Coil 3
Coil 3

(15.1) (15.2) (15.3) 14


Coil 1
Coil 1
Coil 1
Coil 4 Coil 2 Coil 4 Coil 2 Coil 4 Coil 2

Coil 3
Coil 3
Coil 3
(15.4) (15.5) (15.6)

Coil 1
Coil 1
Coil 1

Coil 4 Coil 2 Coil 4 Coil 2 Coil 4 Coil 2

Coil 3
Coil 3
Coil 3

(15.7) (15.8) (15.9)


FIGURE 15.1-15.9 HALF STEP STEPPER MOTOR DRIVE SEQUENCE.

stepper motors can be driven directly by transistor to supply high


currents.
µC provide drive pattern at the output which causes the motor to
rotate.
diodes – flyback diodes which protects transistors from reverse bias.
+Vcc
Stepper motor

T1
D1
Vcc
+Vcc

Chapter: 6 MEMORY AND I/O INTERFACING


Vcc
T2
D2

+Vcc
PORT 2
T3
D3

+Vcc

T4
D4

FIGURE 16 STEPPER MOTOR DRIVE CIRCUIT INTERFACING WITH PORT2.

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.

a. normal 4 step sequence-


-----------------------------------------------------------------------
Step A B C D Hex Equivalent
-----------------------------------------------------------------------
Clockwise

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

Chapter: 6 MEMORY AND I/O INTERFACING


2 0 0 0 1 01H
Anticlockwise
Clockwise

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

+5V +5V +5V


ULN2803 RELAY COIL

µC 8051

P1.0

FIGURE 17 RELAY DRIVER & RELAY COIL INTERFACING WITH PORT 1.

solid state relay:


no coil, spring or mechanical contact switch.
no mechanical parts made of semiconductor.
extreamely low input current requirement& small packaging makes
it ideal for µC & logic control switching.
widely used in controlling pumps, solenoids, alarms & other power
applications.
AC Mains
Vcc
SSR

T3
Zero Fan
8051 Voltage
ckt

P1.0

FIGURE 18 FAN CONTROL USING A SOLID STATE RELAY (SSR).

above figure shows control of a fan using a solid state


relay(SSR).

Chapter: 6 MEMORY AND I/O INTERFACING

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

LED connected with Port0 of the microcontroller.


➢In embedded system programming C code is preferred over other language. Due

to the following reasons:

● Easy to understand

● High Reliability

● Portability

● Scalability

Embedded System Programming:

Basic Declaration

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

Block diagram of Embedded C Programming development

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 of basic 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>

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

 The microcontroller programming is different for each type of operating


system.
 Even though many operating systems exist such as Windows, Linux, RTOS,
etc but
 RTOS has several advantages for embedded system development.
EMBEDDED SYSTEMS PROGRAMMING IN C:
The embedded firmware is responsible for controlling the various peripherals of the
embedded hard-ware and generating response in accordance with the functional requirements
mentioned in the requirements for the particular embedded product.
Firmware is considered as the master brain of the embedded system.
Imparting intelligence to an embedded system is a onetime process and it can happen at any
stage, it can be immediately after the fabrication of the embedded hardware or at a later stage.

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.

'C' v/s. 'Embedded C':


'C' is a well structured, well defined and standardized general purpose programming language
with extensive bit manipulation support.
'C' offers a combination of the features of high level language and assembly and helps in
hardware access programming (system level programming) as well as business package
developments (Application developments like pay roll systems, banking applications, etc).
The conventional 'C' language follows ANSI(American National Standards Institute) standard
and it incorporates various library files for different operating systems.
A platform (operating system) specific application, known as, compiler is used for the
conversion of programs written in 'C' to the target processor (on which the OS is running)
specific binary files. Hence it is a platform specific development.
Embedded 'C' can be considered as a subset of conventional 'C' language. Embedded 'C'
supports all 'C' instructions and incorporates a few target processor specific
functions/instructions.
It should be noted that the standard ANSI 'C' library implementation is always tailored to the
target processor/controller library files in Embedded 'C'.
A software program called 'Cross-compiler' is used for the conversion of programs written in
Embedded 'C' to target processor/controller specific instructions (machine language).
Compiler vs. Cross-Compiler:
Compiler is a software tool that converts a source code written in a high level language on
top of a particular operating system running on a specific target processor architecture (e.g.
Intel x86/Pentium).
Here the operating system, the compiler program and the application making use of the
source code run on the same target processor. The source code is converted to the target
processor specific machine instructions.
The development is platform specific (OS as well as target processor on which the OS is
running). Compilers are generally termed as 'Native Compilers'. A native compiler generates
machine code for the same machine (processor) on which it is running.
Cross-compilers are the software tools used in cross-platform development applications. In
cross-platform development, the compiler running on a particular target processor/OS
converts the source code to machine code for a target.
Embedded system development is a typical example for cross-platform development where
embedded firmware is developed on a machine with Intel/AMD or any other target
processors and the same is converted into machine code for any other target processor
architecture (e.g. 8051, PIC, ARM, etc).
Keil C51 is an example for cross-compiler. The term 'Compiler' is used interchangeably with
'Cross-compiler' in embedded firmware applications. Whenever you see the term 'Compiler'
related to any embedded firmware application, please understand that it is referring to the
cross-compiler.

Using ‘C’ in ‘Embedded C’:


Let us brush up whatever we learned in conventional 'C' programming. Remember we will
only go through the peripheral aspects and will not go in deep.

Keywords and Identifiers:


Keywords are the reserved names used by the 'C' language. All keywords have a fixed
meaning in the 'C' language context and they are not allowed for programmers for naming
their own variables or functions. ANSI 'C' supports 32 keywords and they are listed below.
All 'C' supported keywords should be written in 'lowercase' letters.
C Keywords are predefined, reserved words used in programming that have special
meanings to the compiler.

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:

The list of arithmetic operations supported by ‘C’ are listed below.

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
}

Arrays and Pointers:


Array is a collection of related elements (data types).
Arrays are usually declared with data type of array, name of the array and the number of
related elements to be placed in the array.
For example the following array declaration declares a character array with name ‘arr’ and
reserves space for 5 character elements in the memory as below figure.

char arr [5]


0x10 0x10 0x23 0x03 0x45 (contents)
arr[0] arr[1] arr[2] arr[3] arr[4]

0x8000 0x8001 0x8002 0x8003 0x8004 (Addresses)

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.

BINDING AND RUNNING EMBEDDED C PROGRAM IN KEIL IDE:

Embedded system means some combination of computer hardware and programmable


software which is specially designed for a particular task like displaying message on LCD. If
you are still wondering about an embedded system, just take a look at these circuit
applications using 8051 microcontroller. You can call these applications embedded systems
as it involves hardware (8051 microcontroller) and software (the code written in assembly
language).

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.

You can see program file added under source group.

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]

Now you are done with your program.


BASIC TECHNIQUES FOR READING FROM PORT PINS:

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:

sfr P1 = 0x90; // Usually in header file


P1 = 0x0F; // Write 00001111 to Port 1

In exactly the same way, we can read from Port 1 as follows:


unsigned char Port_data;
P1 = 0xFF; // Set the port to 'read mode'
Port_data = P1; // Read from the port

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:

unsigned char Port_data;


// Assume nothing written to port since reset
// – DANGEROUS!!!
Port_data = P1;

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:

unsigned char Port_data;


P1 = 0x00;
...
// Assumes nothing written to port since reset
// – WON’T WORK
Port_data = P1;

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

Reading and writing bits:


 Demonstrated how to read from or write to an entire port. However, suppose we have
a switch connected to Pin 1.1 and an LED connected to Pin 2.1.

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

_ Rather than reading ‘A’ from a keypad, we may read ‘AAAAA’.


_ Counting the number of times that a switch is pressed becomes extremely difficult.
_ If a switch is depressed once, and then released some time later, the ‘bounce’ may
make it appear as if the switch has been pressed again (at the time of release).

APPLICATIONS:

LED INTERFACING WITH 8051 TO A SINGLE PIN:

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

LED’s interfacing with Port, P1 of 8051:

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.

Interfacing keypad with 8051 microcontroller (P89V51RD2)


As shown in above circuit diagram, to interface Keypad, we need to connect 8 terminals of
the keypad to any port (8 pins) of the microcontroller. Like we have connected keypad
terminals to Port 1 of 8051. Whenever any button is pressed we need to get the location of the
button, means the corresponding ROW an COLUMN no. Once we get the location of the
button, we can print the character accordingly.

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

sbit C4 = P1^0; // Connecting keypad to Port 1


sbit C3 = P1^1;
sbit C2 = P1^2;
sbit C1 = P1^3;
sbit R4 = P1^4;
sbit R3 = P1^5;
sbit R2 = P1^6;
sbit R1 = P1^7;

void msdelay(unsigned int time) // Function for creating delay in milliseconds.


{
unsigned i,j ;
for(i=0;i<time;i++)
for(j=0;j<1275;j++);
}
void lcd_cmd(unsigned char command) //Function to send command instruction to LCD
{
display_port = command;
rs= 0;
rw=0;
e=1;
msdelay(1);
e=0;
}
void lcd_data(unsigned char disp_data) //Function to send display data to LCD
{
display_port = disp_data;
rs= 1;
rw=0;
e=1;
msdelay(1);
e=0;
}
void lcd_init() //Function to prepare the LCD and get it ready
{
lcd_cmd(0x38); // for using 2 lines and 5X7 matrix of LCD
msdelay(10);
lcd_cmd(0x0F); // turn display ON, cursor blinking
msdelay(10);
lcd_cmd(0x01); //clear screen
msdelay(10);
lcd_cmd(0x81); // bring cursor to position 1 of line 1
msdelay(10);
}

void row_finder1() //Function for finding the row for column 1


{
R1=R2=R3=R4=1;
C1=C2=C3=C4=0;

if(R1==0)
lcd_data('7');
if(R2==0)
lcd_data('4');
if(R3==0)
lcd_data('1');
if(R4==0)
lcd_data('N');
}

void row_finder2() //Function for finding the row for column 2


{
R1=R2=R3=R4=1;
C1=C2=C3=C4=0;

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('=');
}

void row_finder4() //Function for finding the row for column 4


{
R1=R2=R3=R4=1;
C1=C2=C3=C4=0;

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

7 SEGMENT DISPLAY INTERFACING WITH 8051 MICROCONTROLLER:

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:

/*Program to interface seven segment display unit.*/


#include <REG51.H>
#define LEDPORT P0
#define ZERO 0x3f
#define ONE 0x06
#define TWO 0x5b
#define THREE 0x4f
#define FOUR 0x66
#define FIVE 0x6d
#define SIX 0x7d
#define SEVEN 0x07
#define EIGHT 0x7f
#define NINE 0x6f
#define TEN 0x77
#define ELEVEN 0x7c
#define TWELVE 0x39
#define THIRTEEN 0x5e
#define FOURTEEN 0x79
#define FIFTEEN 0x71
void Delay(void);
void main (void)
{
while(1)
{
LEDPORT = ZERO;
Delay();
LEDPORT = ONE;
Delay();
LEDPORT = TWO;
Delay();
LEDPORT = THREE;
Delay();
LEDPORT = FOUR;
Delay();
LEDPORT = FIVE;
Delay();
LEDPORT = SIX;
Delay();
LEDPORT = SEVEN;
Delay();
LEDPORT = FOURTEEN;
Delay();
LEDPORT = FIFTEEN;
Delay();
}
}
void Delay(void)
{
int j; int i;
for(i=0;i<30;i++)
{
for(j=0;j<10000;j++)
{
}
}
}
LCD DISPLAY INTERFACING WITH 8051 MICROCONTROLLER:

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)

6 E Enable pin is for starting or enabling the module. A high to low


pulse of about 450ns pulse is given to this pin.

7 DB0 DB0-DB7 Data pins for giving data(normal data like numbers
characters or command data) which is meant to be displayed

8 DB1 DB0-DB7 Data pins for giving data

9 DB2 DB0-DB7 Data pins for giving data


10 DB3 DB0-DB7 Data pins for giving data

11 DB4 DB0-DB7 Data pins for giving data

12 DB5 DB0-DB7 Data pins for giving data

13 DB6 DB0-DB7 Data pins for giving data

14 DB7 DB0-DB7 Data pins for giving data

15 LED+ Back light of the LCD which should be connected to Vcc

16 LED- Back light of LCD which should be connected to ground.

Follow these simple steps for displaying a character or data


E=1; enable pin should be high
RS=1; Register select should be high
R/W=0; Read/Write pin should be low.

To send a command to the LCD just follows these steps:


E=1; enable pin should be high
RS=0; Register select should be low
R/W=0; Read/Write pin should be low.

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

ADC (ADC0808) INTERFACING WITH 8051 MICROCONTROLLER:

ADC0808/ADC0809 is an 8 channel 8-bit analog to digital converter. Unlike ADC0804


which has one Analog channel, this ADC has 8 multiplexed analog input channels. This
tutorial will provide you basic information regarding this ADC, testing in free run mode and
interfacing example with 8051 with sample program in C and assembly.

 IN0-IN7: Analog Input channels


 D0-D7: Data Lines
 A, B, C: Analog Channel select lines; A is LSB and C is MSB
 OE: Output enable signal
 ALE: Address Latch Enable
 EOC: End of Conversion signal
 Vref+/Vref-: Differential Reference voltage input
 Clock: External ADC clock input
 Normally analogue-to-digital converter (ADC) needs interfacing through a microprocessor
to convert analogue data into digital format. This requires hardware and necessary
software, resulting in increased complexity and hence the total cost. The circuit of A-to-D
converter shown here is configured around ADC 0808, avoiding the use of a
microprocessor. The ADC 0808 is an 8-bit A-to-D converter, having data lines D0-D7. It
works on the principle of successive approximation. It has a total of eight analogue input
channels, out of which any one can be selected using address lines A, B and C. Here, in
this case, input channel IN0 is selected by grounding A, B and C address lines.
 Usually the control signals EOC (end of conversion), SC (start conversion), ALE (address
latch enable) and OE (output enable) are interfaced by means of a microprocessor.
However, the circuit shown here is built to operate in its continuous mode without using
any microprocessor. Therefore the input control signals ALE and OE, being active-high,
are tied to Vcc (+5 volts). The input control signal SC, being active-low, initiates start of
conversion at falling edge of the pulse, whereas the output signal EOC becomes high after
completion of digitization. This EOC output is coupled to SC input, where falling edge of
EOC output acts as SC input to direct the ADC to start the conversion.
 As the conversion starts, EOC signal goes high. At next clock pulse EOC output again
goes low, and hence SC is enabled to start the next conversion. Thus, it provides
continuous 8-bit digital output corresponding to instantaneous value of analogue input.
The maximum level of analogue input voltage should be appropriately scaled down below
positive reference (+5V) level.
 The ADC 0808 IC requires clock signal of typically 550 kHz, which can be easily derived
from an Astable multivibrator, constructed using 7404 inverter gates. In order to visualize
the digital output, the row of eight LEDs (LED1 through LED8) have been used, where in
each LED is connected to respective data lines D0 through D7. Since ADC works in the
continuous mode, it displays digital output as soon as analogue input is applied. The
decimal equivalent digital output value D for a given analogue input voltage Vin can be
calculated from the relationship.
Program:
#include <reg51.h>
#define ALE P3_4
#define OE P3_7
#define START P3_5
#define EOC P3_6
#define SEL_A P3_1
#define SEL_B P3_2
#define SEL_C P3_3
#define ADC_DATA P1
void main()
{
unsigned char adc_data;
/* Data port to input */
ADC_DATA = 0xFF;

EOC = 1; /* EOC as input */


ALE = OE = START = 0;
while (1)
{
/* Select channel 1 */
SEL_A = 1; /* LSB */
SEL_B = 0;
SEL_C = 0; /* MSB */

/* Latch channel select/address */


ALE = 1;
/* Start conversion */
START = 1;
ALE = 0;
START = 0;
/* Wait for end of conversion */
while (EOC == 1);
while (EOC == 0);
/* Assert Read signal */
OE = 1;
/* Read Data */
adc_data = ADC_DATA;
OE = 0;
/* Now adc data is stored */
/* start over for next conversion */
}
}

DAC INTERFACING WITH 8051 MICROCONTROLLER:

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.

Digital-to-analog (DAC) converter


The digital-to-analog converter (DAC) is a device widely used to convert digital pulses to
analog signals. In this section we discuss the basics of interfacing a DAC to the 8051.
Recall from your digital electronics book the two methods of creating a DAC:
1. Binary weighted.
2. R/2R ladder.
The vast majority of integrated circuit DACs, including the MC1408 (DAC0808) used in this
section use the R/2R method since it can achieve a much higher degree of precision. The first
criterion for judging a DAC is its resolution, which is a function of the number of binary
inputs. The common ones are 8, 10, and 12 bits. The number of data bit inputs decides the
resolution of the DAC since the number of analog output levels is equal to 2″, where n is the
number of data bit inputs.

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.

MC1408 DAC (or DAC0808)


In the MC1408 (or DAC0808), the digital inputs are converted to current (Iout), and by
connecting a resistor to the Iout pin, we convert the result to voltage.
The total current provided by the Iout pin is a function of the binary numbers at the DO – D7
inputs of the DAC0808 and the reference current (Iref), and is as follows:

𝐷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

Figure: 8051 Connection to DAC808

Converting lout to voltage in DAC0808

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.

Generating a sine wave:


To generate a sine wave, we first need a table whose values represent the magnitude of the
sine of angles between 0 and 360 degrees. The values for the sine function vary from -1.0 to
+1.0 for 0- to 360-degree angles. Therefore, the table values are integer numbers representing
the voltage magnitude for the sine of theta. This method ensures that only integer numbers
are output to the DAC by the 8051 microcontroller. Table shows the angles, the sine values,
the voltage magnitudes, and the integer values representing the voltage magnitude for each
angle (with 30-degree increments). To generate Table 13-7, we assumed the full-scale voltage
of 10 V for DAC output. Full-scale output of the DAC is achieved when all the data inputs of
the DAC are high. Therefore, to achieve the full-scale 10 V output, we use the following
equation.

Vout of DAC for various angles is calculated and shown in Table 13-7. See Example 13-5 for
verification of the calculations.

Angle θ Vout (Voltage Magnitude) Values Sent to DAC (decimal)


Sin θ
(degrees) 5 V + (5 V x sin θ) (Voltage Mag. X 25.6)

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

MULTIPLE INTERRUPTS IN 8051 MICROCONTROLLER:


Interrupts vs. polling:
A single microcontroller can serve several devices. There are two ways to do that: interrupts
or polling. In the interrupt method, whenever any device needs its service the device notifies
the microcontroller by sending it an interrupt signal. Upon receiving an interrupt signal, the
microcontroller interrupts whatever it is doing and serves the device.
The program associated with the interrupt is called the interrupt service routine (ISR) or
interrupt handler.
In polling, the microcontroller continuously monitors the status of a given device; when the
status condition is met, it performs the service. After that, it moves on to monitor the next
device until each one is serviced. Although polling can monitor the status of several devices
and serve each of them as certain conditions are met, it is not an efficient use of the
microcontroller.

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.

SIX INTERRUPTS IN THE 8051 MICROCONTROLLER:


In reality, only five interrupts are available to the user in the 8051, but many manufacturers
data sheets state that there are six interrupts since they include reset. The six interrupts in the
8051 are allocated as follows.
1. Reset. When the reset pin is activated, the 8051 jumps to address location 0000. This is the
power-up reset.
2. Two interrupts are set aside for the timers: one for Timer 0 and one for Timer1. Memory
locations 000BH and 001BH in the interrupt vector table belong to Timer 0 and Timer 1,
respectively.
3. Two interrupts are set aside for hardware external hardware interrupts, Pin numbers 12
(P3.2) and 13 (P3.3) in port 3 are for the external hardware interrupts INT 0 and INT 1,
respectively. These external interrupts are also referred to as EX 1 and EX 2. Memory
locations 0003H and 0013H In the interrupt vector table are assigned to INT0 and INT1,
respectively.
4. Serial communication has a single interrupt that belongs to both receive and transmit. The
interrupt vector table location 0023H belongs to this interrupt.

Table: Interrupt Vector Table for the 8051

Enabling and Disabling an interrupt:


Upon reset, all interrupts are disabled (masked), meaning that none will be responded to by
the microcontroller if they are activated. The interrupts must be enabled by software in order
for the microcontroller to respond to them. There is a register called IE (interrupt enable) that
is responsible for enabling (unmasking) and disabling (masking) the interrupts.
Figure shows the IE register. Note that IE is a bit-addressable register.
From figure notice that bit D7 in the IE register is called EA (enable all). This must be set to
1 in order for the rest of the register to take effect. D6 is unused. D5 is used by the 8052. The
D4 bit is for the serial interrupt, and so on.

Steps in enabling an interrupt:


To enable an interrupts, we take the following steps:
1. Bit D7 of the IE register (EA) must be set to high to allow the rest of register to take the
effect.
2. If EA =1, interrupts are enabled and will be responded to if their corresponding bits in IE
are high. If EA=0, no interrupt will be responded to, even if the associated bit in the IE
register is high.

IE (Interrupt Enable) Register:


• This register is responsible for enabling and disabling the interrupt.

• EA register is set to 1 for enabling interrupts and

• EA register is set to 0 for disabling the interrupts.

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

- IE.6 Reserved for future use.

- IE.5 Reserved for future use.

ES IE.4 Enables/disables serial port interrupt.

ET1 IE.3 Enables/disables timer1 overflow interrupt.

EX1 IE.2 Enables/disables external interrupt1.

ET0 IE.1 Enables/disables timer0 overflow interrupt.

EX0 IE.0 Enables/disables external interrupt0.

SERIAL COMMUNICATION PROGRAMMING:

Serial Communication can be


 Asynchronous
 Synchronous
Synchronous Communication:
Synchronous methods transfer a block of data (characters) at a time
The events are referenced to a clock
Example: SPI bus, I2C bus
Asynchronous Communication:
Asynchronous methods transfer a single byte at a time
There is no clock. The bytes are separated by start and stop bits.
Example: UART

1. Serial port programming in assembly

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.

Baud rate in the 8051

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.

Baud rate supported by Pentium / IBM 486 PC are

Calculation of baud rate:

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.

Clock frequency of timer clock: f = (11.0592 MHz / 12)/32 = 28,800Hz


Time period of each clock tick: T0 = 1/f = 1/28800
Duration of timer : n*T0 (n is the number of clock ticks)
9600 baud ->duration of 1 symbol: 1/9600
1/9600 = n*T0 = n*1/28800
n = f/9600 = 28800/9600 = 3 ->TH1 =-3
Similarly, for baud 2400
n = f/2400 = 12 ->TH1 = -12

Example: set baud rate at 9600


MOV TMOD, #20H ; timer 1,mode 2(auto reload) MOV
TH1, #-3 ; To set 9600 baud rate
SETB TR1; start timer 1

Baud rate selection

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

Registers for serial communication


SBUF (serial buffer) register:
It is an 8 bit register used solely for serial communication in the 8051.A byte of data to be
transferred via the TxD line must be placed in the SBUF register. SBUF holds the byte of
data when it is received by the RxD line. It can be accessed like any other register
MOV SBUF, #'D' ; load SBUF=44H, ASCII for 'D„
MOV SBUF, A ; copy accumulator into
SBUF MOV A, SBUF ; copy SBUF into accumulator
when a byte is written, it is framed with the start and stop bits and transferred serially via
the TxD pin. when the bits are received serially via RxD, it is deframed by eliminating the
stop and start bits, making a byte out of the data received, and then placing it in the SBUF.
SCON (serial control) register:
It is an 8 bit register used to program start bit, stop bit, and data bits of data framing, among
other things.
Figure 2. SCON register
The first two bits are SM0, SM1 which is the serial port mode bits. It is used to specify
framing format, how to calculate baud. For example if (SM0, SM1) = (0,1), mode 1: 8-bit
data, 1 start bit, 1 stop bit, variable baud rate can be set by timer. The other three modes are
rarely used and they are (SM0,SM1) = (0,0), mode 0: fixed baud = XTAL/12,(SM0, SM1) =
(1,0), mode 2: 9-bit data, fixed baud,(SM0, SM1) = (1, 1), mode 3: 9-bit data, variable baud.
The third bit is used to select the type of processor used for communication. If SM2 is 0
means it is single processor communication. If SM2 is 1, then it is multiprocessor
communication. The fourth bit REN is Receive Enable which is used to enable/disable
reception. If REN=1,then 8051 will accept incoming data from serial port. If REN=0, then
the receiver is disabled. E.g. SETB REN,CLR REN, SETB SCON.4, CLR SCON.4.

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

Steps to send data serially:


1.Set baud rate by loading TMOD register with the value 20H, this indicating timer 1 in
mode
2 (8-bit auto-reload) to set baud rate
2. The TH1 is loaded with proper values to set baud rate for serial data transfer
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is
framed with start and stop bits
4. TR1 is set to 1 to start timer 1
5. TI is cleared by CLR TI instruction
6. The character byte to be transferred serially is written into SBUF register
7. The TI flag bit is monitored with the use of instruction JNB TI,xx to see if the character
has been transferred completely
8. To transfer the next byte, go to step 5.
Program to transfer letter “D” serially at 9800baud, continuously:
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
AGAIN: MOV SBUF, #”D” ; letter “D” to transfer
HERE: JNB TI, HERE ; wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ; keep sending A

Importance of the TI flag:


Check the TI flag bit, we know whether or not 8051 is ready to transfer another byte. TI flag
bit is raised by the 8051 after transfer of data. TI flag is cleared by the programmer by
instruction like “CLR TI”. When writing a byte into SBUF, before the TI flag bit is raised, it
may lead to loss of a portion of the byte being transferred.
Steps to receive data serially:
1. Set baud rate by loading TMOD register with the value 20H, this indicating timer 1 in
mode 2 (8-bit auto-reload) to set baud rate
2. The TH1 is loaded with proper values to set baud rate
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is framed with start and stop bits
4. TR1 is set to 1 to start timer 1
5. RI is cleared by CLR RI instruction
6. The RI flag bit is monitored with the use of instruction JNB RI,xx to see if an
entire character has been received yet
7. When RI is raised, SBUF has the byte; its contents are moved into a safe place
8. To receive next character, go to step 5

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:

Baud rate can be increase by two ways-

1. Increasing frequency of crystal

2. Change bit in PCON register

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.

Table 2. Comparison of Baud rate


WHAT IS AN RTOS?

Simply put, an RTOS is a piece of software designed to efficiently manage the


time of a central processing unit (CPU). This is especially relevant for embedded
systems when time is critical.

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.

Because an RTOS is designed to respond to events quickly and perform under


heavy loads, it can be slower at big tasks when compared to another OS.

NEED FOR RTOS

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)

Real-time operating systems (RTOS) are used in environments where a large


number of events, mostly external to the computer system, must be accepted and
processed in a short time or within certain deadlines. such applications are
industrial control, telephone switching equipment, flight control, and real-time
simulations. With an RTOS, the processing time is measured in tenths of seconds.
This system is time-bound and has a fixed deadline. The processing in this type of
system must occur within the specified constraints. Otherwise, This will lead to
system failure.
Examples of the real-time operating systems: Airline traffic control systems,
Command Control Systems, Airlines reservation system, Heart Pacemaker,
Network Multimedia Systems, Robot etc.

The real-time operating systems can be of 3 types –

1. Hard Real-Time operating system:

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

Emphasize on the principle ‗A late answer is a wrong answer‘

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)‘

Automatic Teller Machine (ATM) is a typical example of Soft Real Time


System. If the ATM takes a few seconds more than the ideal operation time,
nothing fatal happens.

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.

This operating system provides some relaxation in the time limit.


For example – Multimedia systems, digital audio systems etc. Explicit,
programmer-defined and controlled processes are encountered in real-time
systems. A separate process is changed with handling a single external event. The
process is activated upon occurrence of the related event signalled by an interrupt.

Multitasking operation is accomplished by scheduling processes for execution


independently of each other. Each process is assigned a certain level of priority
that corresponds to the relative importance of the event that it services. The
processor is allocated to the highest priority processes. This type of schedule,
called, priority-based preemptive scheduling is used by real-time systems.

3. Firm Real-time Operating System:


RTOS of this type have to follow deadlines as well. In spite of its small impact,
missing a deadline can have unintended consequences, including a reduction in
the quality of the product. Example: Multimedia applications.

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.

4. Real-Time Operating System In Embedded System –


Since the size of programs is small, RTOS can also be embedded systems like
in transport and others.

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.

2. Use Heavy System Resources –


Sometimes the system resources are not so good and they are expensive as
well.

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

4. Device Driver And Interrupt signals –


It needs specific device drivers and interrupts signals to respond earliest to
interrupts.

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

6. Minimum Switching – RTOS performs minimal task switching.


COMPARISON OF REGULAR AND REAL-TIME OPERATING
SYSTEMS:
Tasks, Processes & Threads:
In the Operating System context, a task is defined as the program in execution
and the related information maintained by the Operating system for the program

Task is also known as ‗Job‘ in the operating system context

A program or part of it in execution is also called a ‗Process‘

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

The structure of a Processes


The concept of ‗Process‘ leads to concurrent execution (pseudo parallelism) of
tasks and thereby the efficient utilization of the CPU and other system resources

Concurrent execution is achieved through the sharing of CPU among the


processes.

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:

Figure 6.Process states and State transition


 Created State: The state at which a process is being created is referred as
‗Created State‘. The Operating System recognizes a process in the ‗Created State‘
but no resources are allocated to the process
Ready State: The state, where a process is incepted into the memory and awaiting
the processor time for execution, is known as ‗Ready State‘. At this stage, the
process is placed in the ‗Ready list‘ queue maintained by the OS

 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

 . Blocked State/Wait State: Refers to a state where a running process is


temporarily suspended from execution and does not have immediate access to
resources. The blocked state might have invoked by various conditions like- the
process enters a wait state for an event to occur (E.g. Waiting for user inputs such
as keyboard input) or waiting for getting access to a shared resource like
semaphore, mutex etc

Completed State: A state where the process completes its execution


The transition of a process from one state to another is known as ‗State
transition‘

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

Figure 7 Memory organization of process and its associated Threads


 Athread is the primitive that can execute code

 Athread is a single sequential flow of control within a process

 ‗Thread‘ is also known as lightweight process

 A process can have many threads of execution

 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

MULTIPROCESSING & MULTITASKING THEORY


Most embedded systems require functionality and timing that is too complex to
body in a single program. We break the system in to multiple tasks in order to
manage when things happen. In this section we will develop the basic abstractions
that will be manipulated by the RTOS to build multirate systems. To understand
why these parathion of an application in to tasks may be reflected in the program
structure, consider how we would build a stand-alone compression unit based on
the compression algorithm we implemented in Section3.7. As shown in Figure6.1,
this device is connected to serial ports on both ends. The input to the box is an
uncompressed stream of bytes. The box emits a compressed string of bits on the
output serial line, based on a predefined compression table. Such a box may be
used, for example, 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 obviously find itself
reflected in the structure of the code. It is easy to create irregular, ungainly code to
solve this problem; a more elegant solution is to create a queue of out put bits, with
those bits being removed from the queue and sent to the serial port in 8-bit sets.
But beyond the need to create a clean data structure that simplifies the control
structure of the code, we must also ensure that we process the inputs and outputs at
the proper rates. For example, if we spend too much time in packaging and
emitting output characters, we may drop an input character. Solving timing
problems is a more challenging problem.

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.

One solution is to introduce a counter in to the main compression loop, so that a


subroutine to check the input button is called once every times the compression
loop is executed. But this solution does not work when either the compression loop
or the button-handling routine has highly variable execution times—if the
execution time of either varies significantly, it will cause the other to execute later
than expected, possibly causing data to be lost. We need to be able to keep track of
these two different tasks separately, applying different timing requirements to
each.

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.

TASK AND RTOS SHORT NOTES

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

MULTIPROCESSING & MULTITASKING SHORT NOTES


The ability to execute multiple processes simultaneously is referred as
multiprocessing
 Systems which are capable of performing multiprocessing are known as
multiprocessor systems
 Multiprocessor systems possess multiple CPUs and can execute multiple
processes simultaneously

 The ability of the Operating System to have multiple programs in memory,


which are ready for execution, is referred as multiprogramming .

Multitasking refers to the ability of an operating system to hold multiple


processes in memory and switch the processor (CPU) from executing one process
to another process

 Multitasking involves ‗Context switching‘, ‗Context saving‘ and ‗Context


retrieval‘

Context switching refers to the switching of execution context from task to other

 When a task/process switching happens, the current context of execution should


be saved to (Context saving) retrieve it at a later point of time when the CPU
executes the process, which is interrupted currently due to execution switching
 During context switching, the context of the task to be executed is retrieved
from the saved context list. This is known as Context retrieval.

• In a multiprogramming environment, usually more programs to be executed than


could possibly be rim at one time. In CPU scheduling, it switches from one process
to another process. CPU resource management is commonly known as scheduling.
• Objective of the multiprogramming is to increases the CPU utilization. CPU
scheduling is one kind of fundamental operating system functions.
• Each process has an execution state which indicates what process is currently
doing. The process descriptor is the basic data structure used to represent the
specific state for each process. A state diagram is composed of a set of states and
transitions between states.

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

Figure 9 Context Switching


Context Switch
In computing, a context switch is the process of storing the state of a process or
thread, so that it can be restored and resume execution at a later point. This allows
multiple processes to share a single CPU, and is an essential feature of a
multitasking operating system.
The precise meaning of the phrase ―context switch‖ varies. In a multitasking
context, it refers to the process of storing the system state for one task, so that task
can be paused and another task resumed. A context switch can also occur as the
result of an interrupt, such as when a task needs to access disk storage, freeing up
CPU time for other tasks. Some operating systems also require a context switch to
move between user mode and kernel mode tasks. The process of context switching
can have a negative impact on system performance.
Multiprogramming: The ability of the Operating System to have multiple
Programs in memory, which are ready for execution, is referred as
multiprogramming.
Types of Multitasking
Depending on how the task/process execution switching act is implemented,
multitasking can is classified into
• Co-operative Multitasking: Co-operative multitasking is the most primitive
form of multitasking in which a task/process gets a chance to execute only when
the currently executing task/process voluntarily relinquishes the CPU. In this
method, any task/process can avail the CPU as much time as it wants. Since this
type of implementation involves the mercy of the tasks each other for getting the
CPU time for execution, it is known as co-operative multitasking. If the currently
executing task is non-cooperative, the other tasks may have to wait for a long time
to get the CPU

• Preemptive Multitasking: Preemptive multitasking ensures that every


task/process gets a chance to execute. When and how much time a process gets is
dependent on the implementation of the preemptive scheduling. As the name
indicates, in preemptive multitasking, the currently running task/process is
preempted to give a chance to other tasks/process to execute. The preemption of
task may be based on time slots or task/process priority
• Non-preemptive Multitasking: The process/task, which is currently given the
CPU time, is allowed to execute until it terminates (enters the ‗Completed‘ state)
or enters the ‗Blocked/Wait‘ state, waiting for an I/O. The co- operative and non-
preemptive multitasking differs in their behavior when they are in the
‗Blocked/Wait‘ state. In co-operative multitasking, the currently executing
process/task need not relinquish the CPU when it enters the ‗Blocked/Wait‘ sate,
waiting for an I/O, or a shared resource access or an event to occur whereas in non-
preemptive multitasking the currently executing task relinquishes the CPU when it
waits for an I/O.

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

 Determining which task/process is to be executed at a given point of time is


known as task/process scheduling

 Task scheduling forms the basis of multitasking

 Scheduling policies forms the guidelines for determining which task is to be


executed when


The scheduling policies are implemented in an algorithm and it is run by the
kernel as a service

 The kernel service/application, which implements the scheduling algorithm, is


known as ‗Scheduler‘

 The task scheduling policy can be pre-emptive, non-preemptive or co- operative

 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

Task Scheduling - Scheduler Selection:


The selection of a scheduling criteria/algorithm should consider the following
factors:
• CPU Utilization: The scheduling algorithm should always make the CPU
utilization high. CPU utilization is a direct measure of how much percentage of the
CPU is being utilized.

• Throughput: This gives an indication of the number of processes executed per


unit of time. The throughput for a good scheduler should always be higher.

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

TASK SCHEDULING – TASK TRANSITION THROUGH VARIOUS


QUEUES
Non-preemptive scheduling – First Come First Served (FCFS)/First In First
Out (FIFO) Scheduling:
 Allocates CPU time to the processes based on the order in which they enters the
‗Ready‘ queue

 The first entered process is serviced first

 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

Non-preemptive scheduling – Last Come First Served (LCFS)/Last In First


Out (LIFO) Scheduling:
 Allocates CPU time to the processes based on the order in which they are
entered in the ‗Ready‘ queue

 The last entered process is serviced first

 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

Non-preemptive scheduling – Shortest Job First (SJF) Scheduling.


 Allocates CPU time to the processes based on the execution completion time for
tasks

 The average waiting time for a given set of processes is minimal in SJF
scheduling

 Optimal compared to other non-preemptive scheduling like FCFS

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.

Non-preemptive scheduling – Priority based Scheduling


 A priority, which is unique or same is associated with each task

 The priority of a task is expressed in different ways, like a priority number, the
time required to complete the execution etc.

 In number based priority assignment the priority is a number ranging from 0 to


the maximum priority supported by the OS. The maximum level of priority is OS
dependent.
 Windows CE supports 256 levels of priority (0 to 255 priority numbers, with 0
being the highest priority)

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

‗Starvation‘ can be effectively tackled in priority based non-preemptive


scheduling by dynamically raising the priority of the low priority task/process
which is under starvation (waiting in the ready queue for a longer time for getting
the CPU time)

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

 The scheduler can preempt (stop temporarily) the currently executing


task/process and select another task from the ‗Ready‘ queue for execution

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

 Time-based preemption and priority-based preemption are the two important


approaches adopted in preemptive scheduling

Preemptive scheduling – Preemptive SJF Scheduling/ Shortest Remaining


Time (SRT):
 Thenon preemptive SJF scheduling algorithm sorts the ‗Ready‘ queue only after
the current process completes execution or enters wait state, whereas the
preemptive SJF scheduling algorithm sorts the ‗Ready‘ queue when a new process
enters the ‗Ready‘ queue and checks whether the execution time of the new
process is shorter than the remaining of the total estimated execution time of the
currently executing process

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

Preemptive scheduling – Round Robin (RR) Scheduling:


The term Round Robin is very popular among the sports and games activities. You
might have heard about 'Round Robin' league or 'Knock out' league associated with
any football or cricket tournament. In the 'Round Robin' league each team in a
group gets an equal chance to play against the rest of the teams in the same group
whereas in the 'Knock out' league the losing team in a match moves out of the
tournament .
In Round Robin scheduling, each process in the 'Ready' queue is executed for a
pre-defined time slot.
The execution starts with picking up the first process in the 'Ready' queue. It is
executed for a pre-defined time and when the pre-defined time elapses or the
process completes (before the pre-defined time slice), the next process in the
'Ready' queue is selected for execution.
This is repeated for all the processes in the 'Ready' queue. 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.
The sequence is repeated. This reveals that the 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.
Figure: Round Robin Scheduling

This is repeated for all the processes in the ‗Ready‘ queue

 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

 The priority of a task/process in preemptive priority based scheduling is


indicated in the same way as that of the mechanisms adopted for non- preemptive
multitasking.

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

Priority Scheduling is a method of scheduling processes that is based on priority.In


this algorithm, the scheduler selects the tasks to work as per the priority.

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.

Types of Priority Scheduling

Priority scheduling divided into two main types:

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.

Characteristics of Priority Scheduling

 A CPU algorithm that schedules processes based on priority.


 It used in Operating systems for performing batch processes.
 If two jobs having the same priority are READY, it works on a FIRST
COME,FIRST SERVED basis.
 In priority scheduling, a number is assigned to each process that indicatesits
priority level.
 Lower the number, higher is the priority.
 In this type of scheduling algorithm, if a newer process arrives, that ishaving
a higher priority than the currently running process, then thecurrently
running process is preempted.

Example of Priority 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 4) At time 4, P1 has finished its execution. P2 starts execution.


Step 5) At time= 5, no new process arrives, so we continue with P2.

Step 6) At time=6, P3 arrives. P3 is at higher priority (1) compared to P2 having


priority (2). P2 is preempted, and P3 begins its execution.
Step 7) At time 7, no-new process arrives, so we continue with P3. P2 is in the
waiting queue.

Step 8) At time= 8, no new process arrives, so we can continue with P3.

Step 9) At time= 9, no new process comes so we can continue with P3.


Step 10) At time interval 10, no new process comes, so we continue with P3

Step 11) At time=11, P4 arrives with priority 4. P3 has higher priority, so it


continues its execution.
Step 12) At time=12, P5 arrives. P3 has higher priority, so it continues execution.

Step 13) At time=13, P3 completes execution. We have P2,P4,P5 in ready queue.


P2 and P5 have equal priority. Arrival time of P2 is before P5. So P2 starts
execution.
Step 14) At time =14, the P2 process has finished its execution. P4 and P5 are in
the waiting state. P5 has the highest priority and starts execution.

Step 15) At time =15, P5 continues execution.

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:

 Easy to use scheduling method


 Processes are executed on the basis of priority so high priority does not need
to wait for long which saves time
 This method provides a good mechanism where the relative important of
each process may be precisely defined.
 Suitable for applications with fluctuating time and resource requirements.

Disadvantages of priority scheduling

Here, are cons/drawbacks of priority scheduling

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

 Priority scheduling is a method of scheduling processes that is based on


priority. In this algorithm, the scheduler selects the tasks to work as per the
priority.
 In Priority Preemptive Scheduling, the tasks are mostly assigned with their
priorities.
 In Priority Non-preemptive scheduling method, the CPU has been allocated
to a specific process.
 Processes are executed on the basis of priority so high priority does not need
to wait for long which saves time
 If high priority processes take lots of CPU time, then the lower priority
processes may starve and will be postponed for an indefinite time.

You might also like