0% found this document useful (0 votes)
35 views446 pages

Embedded System and IOT Design Technical Book 1

The document is a syllabus for a course on Embedded Systems and IoT Design, covering topics such as microcontrollers, embedded system design processes, operating systems, IoT architecture, and IoT system design. It includes detailed chapters on the 8051 microcontroller, ARM processors, real-time systems, and various IoT protocols. The syllabus outlines the structure and content of the course, including practical programming examples and case studies.

Uploaded by

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

Embedded System and IOT Design Technical Book 1

The document is a syllabus for a course on Embedded Systems and IoT Design, covering topics such as microcontrollers, embedded system design processes, operating systems, IoT architecture, and IoT system design. It includes detailed chapters on the 8051 microcontroller, ARM processors, real-time systems, and various IoT protocols. The syllabus outlines the structure and content of the course, including practical programming examples and case studies.

Uploaded by

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

<br>

Page I
of 446

SYLLABUS
-
Embedded Systems and IoT Design (ET3491)

g
in
UNIT I 8051 MICROCONTROLLER
Microcontrollers for an Embedded System - S0$1 - Architecture - Addressing Modes - Instruetion Set

er
- Program and Data Memory - Stacks - Interrupts - Timers Counters Serial Ports Programming.

e
(Chapters - 1, 2, 3)

in
ng
UNIT II EMBEDDED SYSTEMS
Embedded System Design Process - Model Train Controller - ARM Processor - Instruction Set
fE
Preliminaries - CPU - Programnming Input and Output - Supervisor Mode - xceptions and Trap
-

Models for programs - Assembly. Linking and Loading - Compilation Techniques - Program Level
O
Performance Analysis. (Chapters - 4, 5, 6. 7)
g e

UNIT III PROCESSES AND OPERATING SYSTEMS


le

Structure of a real - time system - Task Assignment and Scheduling - Multiple Tasks and MMultiple
ol

Processes - Multirate Systems - Pre emptive real - time Operating systems - Priority based scheduling
C

- Interprocess Communication Mechanisms - Distributed Embedded Systems - MPSoCs and Shared


- -
Memory Multiprocessors Design Example Audio Player. Engine Control Unit and Video
u

Accelerator. (Chapter - 8)
ad
iln

UNIT IV IOT ARCHITECTURE AND PROTOCOLS


Internet - of - Things - Physical Design, Logical Design - loT Enabling Technologies - Domain
m

Specific loTs - loT and M2M - loT System Management with NETCONF - YANG - loT Platform
Ta

Design - Methodology - loT Reference Model - Domain Model Communication Model loT
Reference Architecture loT Protocols - MQTT, XMPP. Modbus, CANBUS and BACNet.
(Chapter -9)

UNIT V IOT SYSTEM DESIGN


Basic building blocks of an loT device - Raspberry Pi - Board - Linux on Raspberry -
Pi Intertaces
Programming with Python Case Studies : Home Automation, Smart Cities, Environment and
Agriculture. (Chapter - 10)
<br>

Page 2 of 446

TABLE OF CONTENTS
UNIT I:
-
Chapter -1 Microcontrollers for an Embedded System 8051

g
(1- 1) to (1 -30)

in
er
1.1 Introduction... 1-2
..
Comparison between Microprocessor and Microcontroller 1-4

e
1.1.1
.... 1

in
1.1.2 Different Types of Microcontrollers.... -4

ng
1.1.2.1 Embedded Microcontrollers..... 1-4

1.1.2.2 External Memory Microcontrollers fE 1-5

1.1.2.3 CISC vs RISC Microcontrollers. 1-6


O
Criteria for Selecting Microcontroller. 1-6
1.1.3
1-7
e

1.1.4 Applications of Microcontroller.


g

Features of 8051 Microcontroller 1-7


1.2
le

Architecture of 8051 Microcontroller 1-8


1.3
ol

Register Organization... ***** 1-10


C

1.3.1
1.3.1.1 and
A B Registers 1-10
u

1.3.1.2 Data Pointer (DPTR)....... 1-11


ad

1.3.1.3 Program Counter


1-11
iln

.
1
- 11
1.3.1.4 8051 Flag Bits/PSW Registers
1-12
m

1.3.1.5 Special Function Registers

1.3.1.6 Stack and Stack Pointer......... 1-15


Ta

Pin Diagram
1-16
1.3.2
18
1.4 Program and Data Memory..... .l-
Internal RAM Organization......... 1-19
1.4.1
1-20
1.4.1.1 8051 Register Banks (Working Registers).....
1-21
1.4.1.2 Bit/ Byte Addressable
... 1-21
1.4.1.3 General Purpose RAM...

ROM Space in the 8051 1-21


1.4.2
(v)
<br>

Page 3 of 446

1.5 External Program and Data Memory Interfacing. 1-22


1.5.1 External Program Memory 1-22
1.5.2 External Data Memory... 1-24
1.5.3 Important Points to Remember in Accessing External Memory. 1-27
1-29

g
1.6 Stack and Stack Pointer....

in
Chapter -2 Addressing Modes and Instruction Set of 8051

er
(2- 1) to (236)

e
2.1 8051 Addressing Modes. 2-2

in
2.1.1 Register Addressing.. ..2-2

ng
2.1.2 Direct Byte Addressing...
.2-2
2.1.3 Register lndirect Addressing fE .2-3
2.1.4 Immediate Addressing.
.2-3
O
2.1.5 Register Specific.
.2- 4
e

2.1.6 Index ....2 - 4


g

2.1.7 Stack Addressing Mode.. ....


2- 4
le

2.2 Classification of Instruction Set of 8051..


2 -5
ol

2.3 Data Transfer Instructions...


2-5
C

2.3.1 Instructions to Access External Data Memory.


.....2-7
Instructions to Access External ROM/Program Memory ....
u

2.3.2
...2-7
ad

2.3.3 Data Transfer with Stack (PUSH and POP)


Instructions. ... -82

2.3.4 Data Exchange Instructions...


iln

.2-9
2.4 Byte Level Logical Instructions
m

2-10
2.5 Arithmetic Instructions...
..2-13
Ta

2.5.1 Incrementing and Decrementing.


Addition..
.2-13
2.5.2
.2-14
2.5.3 Subtraction
Multiplication and Division .
.2-15
2.5.4
Decimal Arithmetic...
2-15
2.5.5
.2-16
2.6 Bit Level Logical Instructions
2-16
2.7 Rotate and Swap lnstructions
2- 19
(vi)
<br>

Page 4 of 446

2.8 Jump and CALL Instructions 2-20


2.8.1 Jump and Call Program Range. 2-21
2.8.2 Jump. 2-21
2.8.3 CALL and Subroutines.... 2- 23

g
2.9 Time Delay for 8051 2- 24

in
2.10 Program Examples.. 2- 25

er
Program 2.10.1 : Program to load accumulator A, DPH and DPL with
30H..... 2- 25
... 2- 26

e
Program 2.10.2 : Copy byte in SCON to register R3.

in
Program 2.10.3: Put the number 90H in R2 and R3. 2-26

ng
Program 2.10.4 : Add two 8-bit numbers. 2-26
...
Program 2.10.5 : Add two 16-bit numbers. fE 2-26
Program 2.10.6 : Find the 2's complement of a number in RO. 2-26
O
Program 2.10.7 : Unpack the packed BCD number stored in the accumulator and
-
e

save the result in R0 and R1 such that (R0) <- LSB and (R1) MSB. .......e*. 2- 27
g

Program 2.10.8: Subtract two 8-bit numbers and exchange digits. 2-27
le

Program 2.10.9 : Subtract the contents of R1 of Bank0 from the contents of RO


ol

2- 27
C

of Bank2.
Program 2.10.10 Division of two 8-bit numbers. 2-27
:
u

Program 2.10.11 Multiply two 8-bit numbers.


:
2-27
ad

Program 2.10.12 : Program to convert 8-bit binary number


iln

.. 2-27
to its equivalent BCD.
m

Program 2.10.13 :To add two 16-bit BCD numbers. 2-28


DIV.....
Ta

Program 2.10.14
:
Implementing a BCD multiply using MUL and 2- 29

Program 2.10.15 :Subtract two 16-bit numbers. 2-29


port ....2 -29
Program 2.10.16 :Generate BCD up counter and send each count to
A.

Program 2.10.17 Find the maximum number from given 8-bit ten numbers. 2-29
: a

Program 2.10.18 Arrange the given ten 8-bit numbers in the ascending order. -31
: 2

Program 2.10.19:Count number of one's ina number. 2-32

Program 2.10.20:To find the sum of 10 numbers stored in the array...........2-32

(vi)
<br>

Page 5 of 446

Program 2.10.21: Data transfer from memory block B1


to memory block B2....2-34
Program 2.10.22 :Write a program to load accumulator with values 55H

and complement 70 times. 2-35


Program 2.10.23 :Write an 8051 assembly language program to
copy the value 55H

into RAM memory locations 40H to 45H using register indirect addressing

g
in
with a loop. 2-35

er
Program 2.10.24 : Write an 8051 assembly language program to clear the

e
accumulator and add 3 to the accumulator 10 times... 2-36

in
Chapter -3 8051 I/O Ports, Timers, Serial Ports and Interrupts

ng
(3 - 1) to (3- 82)
3.1 8051 |/O Ports Structure fE 3 -2
3.2 I/O Bit Manipulation Programming.
3-4
O
3.3 8051 Timers...
3-25
e

3.3.1 Structure of TMOD Register


3-25
g

3.3.2 Structure of TCON Register.


le

3 -26
3.4 8051 Timer Modes and Programming
ol

3-27
3.5 8051 Counter Programming.
C

3-33
3.5.1 Programming Timers in 8051 C... ...
3-42
u

3.6 8051 Serial Port


ad

3-50
3.6.1 Operating Modes for Serial Port.
3-52
iln

3.6.2 Generating Baud Rates..


3-53
3.6.3 Programming 8051 for Serial Data Transfer
m

3-55
3.6.4 Programming 8051 for Receiving Data Serially.
Ta

3-57
3.6.5 Doubling the Baud Rate in the 8051.
3-58
3.6.6 8051 Connection to RS 232C.
3-59
3.6.7 Serial Communication Programming in C
3 -59
3.7 8051 Interrupt Structure
3-64
3.7.1 Interrupt Control (Enabling and Disabling Interrupts using
IE)....... 3-65
3.7.2 Interrupt Priority and Interrupt Destinations (Vector Locations) ........
3 -66

(viii)
<br>

Page 6 of 446

3.8 Programming Interrupts..... 3 -68


3.8.1 Programming Timer Interrupts. 3-68
3.8.2 Programming External Hardware Interrupts.... 3-70
3.8.3 Programming the Serial Communication Interrupts 3-71
Unit |-Two Marks Questions with Answers

g
.3-74

in
UNIT II

er
Chapter - 4 Embedded System Design (4- 1) to (4- 28)

e
4.1 Embedded System Design Process.

in
4 -2
4.1.1 Requirements...

ng
4-5
4.1.2 Specifications 4-8
4.1.3 Architecture Design.....
fE 4-9
4.1.4 Designing Hardware and Software Components 4- 10
O
4.1.5 System Integration....
.. 4-11
e

4.2 Model Train Controller. 4- 12


g

4.2.1 Requirements... 4- 13
le

4.2.2 Digital Command Control (DCCc).... 4-14


ol

4.2.3 DCCComponents 4- 15
C

4.2.4 Conceptual Specification.... 4- 16


u

4.2.5 Detailed Specification 4 - 20


ad

4.2.5.1 Analog Physical Objects *.. 4-20


iln

4.2.5.2 Panel and Motor Interface.......... 4-21


4.2.5.3 Transmitter and Receiver.. 4-21
m

4.2.5.4 Formatter. 4-22


Ta

4.2.5.5 Controller 4-25

-
Chapter -5 ARM Processor (5-1) to (5 60)
5.1 Introduction.. 5-2
5.2 Preliminaries. 5-2

5.2.1 Computer Architecture Taxonomy .5-2


5.2.1.1 Von Neumann Architecture. ...5 -2

(ix)
<br>

Page 7 of 446

..5-3
5.2.1.2 Harvard Architecture.
Harvard and Von-Neumann
Architectures.......5 -3
5.2.1.3 Comparison between 4
(CISC). ...5-
5.2.1.4 Complex Instruction Set Computers
-4
.5
Set Computers (RISC).
5.2.1.5 Reduced Instruction
CiSC.
.5-5

g
RISC and
5.2.1.6 Comparison between
....5 -7

in
5.2.2 Assembly Language.
...5-7

er
Language...
5.2.2.1 Features of Assembly
*......5-7

e
Assembly Module....
5.2.2.2 Structure of ARM

in
.5-9
5.2.2.3 Rules for Labels in Assembly Language...

ng
..5-10
5.2.2.4 ARM Data Formats...
- 10
5.2.2.5 ARM Assembler Directives
... ....5
ARM Processor
fE 5-14
5.3 ....
5 - 14
O
5.3.1 Features of ARM Processor.
ARM Architecture....
.5-14
e

5.3.2
...5- 14
g

5.3.2.1 ARM Core Dataflow Model.


le

ARM Programmer's Model.... .5-17


5.3.3
ol

5.3.3.1 Processor Modes ..5-17


C

5.3.3.2 Programming Model.... ...5- 18


..5- 18
u

5.3.3.3 General Purpose Registers....


.5 - 19
ad

5.3.3.4 Special Purpose Registers.


...
ARM CPSR... 5 - 20
5.3.4
iln

Memory Organization
.. .5-22
5.3.5
m

Basic ARM Addressing .5- 24


5.3.6 Modes........
Ta

5- 25
5.4 Instruction Set..
5.4.1 Load and Store Instructions
.. 5 - 25
...
5.4.1.1 Basic Forms of LDR/STR Instructions .5-25
5.4.1.2 Offset Form : Immediate Value as the Offset ..5- 29
5.4.1.3 Offset Form: Register as the Offset.... .5-33
5.4.1.4 Offset Form: Scaled Register as the Offset ..5-33
5.4.2 Arithmetic Instructions 5-34

.(x)
<br>

Page &
of 446

5.4.2.1 Addition of Unsigned Numbers. ...5-35

5.4.2.2 Subtraction of Unsigned Numbers. .5- 37


5.4.2.3 Multiplication Unsigned Numbers. .5-39

5.4.2.4 Multiply and Accumulate Instructions ....5 - 40


-
5.4.2.5 Division of Unsigned Numbers ...5 41

g
.......
5-42

in
5.4.3 Logic Instructions
.5- 44

er
5.4.4 Rotate and Shift Instructions
5.4.5 Looping, Branch Instructions and Conditional Execution .5-47

e
in
5.4.5.1 Use of Comparison Instruction ....5-50
...

ng
5.4.5.2 Use of TST (Test) Instruction .5-51

5.4.5.3 Use of TEQ (Test Equal) Instruction .5 -52


fE
5.4.5.4 Short Branches and Calculating Short Branch Address.. .5-52
5-53
O
5.4.5.5 Branching Beyond 32 M Byte Limit.

5.4.5.6 Subroutine Instructions .5-53


e

Implementation of C
Language Statements using ARM Assembly........5 56
5.5
g
le

-
Chapter -6 Central Processing Unit (6-1) to (6 18)
ol

6.1 Introduction.. 6-2


C

6.2 Programming Input and Output.. 6-2


u

6.2.1 Input and Output Primitives. 6-3


ad

6.2.2 Busy-wait I/0 (Programed i/0) 6-5


...
iln

6.2.3 Interrupts 6-6

6.2.4 Priorities and Vectors... 6-10


m

6.2.4.1 Interrupt Priorities. 6-10


Ta

6.2.4.2 Interrupt Vectórs 6-13

Interrupts in ARM... 6-14


6.2.5
6.3 Supervisor Mode, Exceptions and Traps 6-16

6.3.1 Supervisor Mode. 6-16


Exceptions. 6-17
6.3.2
Traps.... 6-17
6.3.3

(xi)
<br>

Page 9 of 446

Chapter -7 Program Design and Analysis (7-1) to (7 -32)


7.1 Models for Programs. 7-2
Data Flow Graph.......
.... 7-2
7.1.1
7.1.2 Control/Data Flow Graphs .... ..7 -3

g
7.2 Assembly, Linking and Loading.. 7-5

in
....-7

er
7.2.1 Assembler...
7.2.2 Linking. ...7-10

e
... 7
-10

in
7.2.3 Loading.
7-11

ng
7.3 Compilation Techniques.
7.3.1 Statement Translation.... ...7-14
7.3.2 Procedures
fE ....7-18
.... .....
7-19
O
7.3.3 Data Structures

7.4 Program Level Performance Analysis... 7-21


e

Elements of Program Performance. .7-22


g

7.4.1 .....
le

7.4.2 Measurement- Driven Performance Analysis. .7-25


ol

Unit Il-Two Marks Questions with Answers .7-28


C

UNIT III
u

Chapter -8 Processes and Operating Systems (8- 1) to (8- 46)


ad

...
8.1
-
Structure of a Real time System 8-2
iln

8.1.1 Characteristic of RTOS. 8-3


m

8.1.2 Classification of Real-time Systems..... 8-4


Ta

8.1.3 Hard Real Time Systems.... 8-6


8.1.4 Soft Real Time System.... 8-7
..... 7
8.1.5 Difference between Hard and Soft Real Time System 8-
8.2 Multiple Tasks and Multiple Processes 8-8
8.2.1 Multirate Systems 8-10
8.2.2 Process State and Scheduling.... 8-11
8.2.3 Scheduling Policies... 8-12
8.3 Preemptive Real-time Operating Systems 8-12

(xii)
<br>

Page 10 of 446

8.3.1 Preemption 8-12


8.3.2 Priorities.... ..8- 13

8.3.3 Processes and Contèxt.. 8-16


8.3.4 Processes and Object-oriented Design 8-17
8.4 Priority based Scheduling. 8-18

g
in
8.4.1 Earliest-Deadline-First Scheduling. 8-18

er
8.4.2 Rate Monotonic Scheduling. 8-20
8.4.2.1 Comparison between RMS and EDF ..8- 22

e
in
8.4.3 Priority Inversion. 8-22

ng
8.5 Interprocess Communication Mechanisms.... 8-25
8.5.1 Features of Message Passing .... fE 8-27
8.5.2 IPC Message Format. 8-28
IPCSynchronization. 8-29
O
8.5.3
8.5.4 Shared Memory. 8-30
e

8.6 Distributed Embedded Systems. 8-31


g

Why Distributed. 8-31


le

8.6.1
Network Abstractions 8-32
ol

8.6.2
8.6.3 Hardware and Software Architectures... 8-34
C

8.6.4 Message Passing Programming.... 8-36


u

8.7 MPSoCs and Shared Memory Multiprocessors 8-37


ad

8.8 Design Example Audio Player....


:
8- 40
iln

8.9 Engine Control Unit 8- 41


..... 8-41
8.10 Video Accelerator
m

Unit Ill -Two Marks Questions with Answers 8-44


Ta

UNIT IV

loT Architecture and Protocols (9- 1) to (9- 66)


Chapter -9
- -
9.1 Introduction of Internet of Things 9-2
Definition of loT
... .9-3
9.1.1
loT Characteristics... 9-5
9.1.2
9.1.3 Component of loT .9-5
(xii)
<br>

Page 11 of 446

.9-6
9.1.4 Working of loT...
...9-7
9.1.5 Advantages and Disadvantages...
.9 -8
9.1.6 Applications of loT.....
9-8
9.2 Physical Design
.9-8
Things in loT.

g
9.2.1
...9 - 10

in
9.2.2 loT Protocol...
9-16

er
Logical Design.
9.3 ....9 - 16

e
9.3.1 loT Functional Blocks....
...9-18

in
loT Communication Model.
9.3.2
.9-20

ng
loT Communication API's.
9.3.3
loT Enabling Technologies. 9-22
9.4 fE
9.4.1 Cloud Computing. .9-22
Data Analytic .......... .9- 23
O
9.4.2 Big
..... .9- 23
9.4.3 Wireless Sensor Networks
e

...
Communication Protocols. 9- 24
g

9.4.4
le

9.4.5 Embedded System... .9-24


ol

9.4.6 Unmanned Aerial Vehicle. .9-25


...
C

9.5 Domain Specific loTs 9-26


26
Inventory Management in Retail ***.9-
u

9.5.1
ad

9.5.2 Smart Payments in Retail. .9-27


9.5.3 Smart Vending Machine. .9-28
iln

9.5.4 Route Generation and Scheduling in Logistics.... ..9-28


m

9.5.5 Fleet Tracking in Logistics... *.**...9 - 29


Ta

9.6 loT and M2M 9-30


Architecture and Components of M2M.... .....
9.6.1 9-31
9.6.2 Difference between M2M and loT... b......9- 33

9.7 loT System Management with NETCONF - YANG 9-33


9.7.1 simple Network Management Protocol (SNMP)
..9-33
9.7.2 Network Operator Requirements.
....9-34
9.7.3 NETCONF
.9 -35

(xiv)
<br>

Page 12 of 446

... 9
9.7.4 YANG -36
9.8 loT Platform Design Methodology 9-36
9.8.1 Purpose and Requirement Specification.... .9-37
9.8.2 Process Specification.... .9-38
Domain Model Specification ....

g
9.8.3 ...9-38
... 40

in
9.8.4 informatíion Model Specificaion 9-
.... 9 - 42

er
9.8.5 Service Specification
..9- 42

e
9.8.6 loT Level Specification.....
...

in
9.8.7 Functional View Specification 9-43

ng
9.8.8 Operational View Specification.. .......9-45
..
9.8.9 Device and Component Integration 9-46
9.8.10 Application Development
fE .9-47
9-49
O
9.9 loT Reference Model.
OneM2M Architecture
.... 9- 49
9.9.1
..
e

9.9.2 loT World Forum Standardized Architecture .9-50


g
le

9.9.3 Simplified loT Architecture. .9-52


9-53
ol

9.10 loT Protocols


..
9- 53
C

9.10.1 MQTT..

9.10.2 XMPP. .9-56


u

9 - 58
...
9.10.3 Modbus
ad

9.10.4 CANBUS ...9- 59


iln

...
BACNet..... 9 - 62
9.10.5
IV - Two Marks Questions with Answers .9-64
m

Unit
UNI V:
Ta

Chapter -
10 loT System Design (10- 1) to (10- 38)

10.1 Basic Building Blocks of an loT Device. 10-2


10.1.1 loT Device.
10-3
10 -5
10.2 Raspberry Pi...
10 -6
10.2.1 About the Board...

(xv)
<br>

Page 13 of 446

10.2.2 Linux on Raspberry Pi. 10-9

10.2.3 Difference between Raspberry Pi is and Desktop Computers. 10-11

10.3 Raspberry Pi Interfaces.. 10- 12


-
10 15
10.4 Raspberry Pi Programming with Python.
Controlling LED with Raspberry Pi. 10-15

g
10.4.1
10- 18

in
Pi.
10.4.2 Interfacing an LED and Switch with Raspberry
10- 19

er
10.4.3 Interfacing Light Sensor
10-21

e
10.5 Home Automation...

in
10.5.1 Smart Lighting.****** 10-21

ng
10.5.2 Smart Appliances... 10-23

Intrusion Detection.
10- 24
10.5.3

Smoke for Gas Detection


fE 10- 25
10.5,4
O
10.6 Smart Cities... 10-26
10- 27
e

10.6.1 Smart Parking.


g

10- 30
10.6.2 Smart Lighting
le

10.6.3 Smart Roads


10-30
ol

10- 31
10.7 Environment.
C

10.7.1 10 31
Weather Monitoring.
u

10.7.2 Air Pollution Mtonitoring 10-31


ad

10.7.3 Noise Pollution Monitoring 10-32


10.7.4 Forest Fire Detection. 10- 33
iln

10.7.5 River Floods Detection.. 10- 34


m

10.8 Agriculture. 10- 35


Ta

10.8.1 Machine Diagnosis and Prognosis. 10-35


10.8.2 Indoor Air Quality Monitoring.. 10-35
Unit V - Two Marks Questions with Answers. 10-36
- -
Solved Model Question Paper (M 1) to (M 2)

(xvi)
<br>

Page 14 of 446

UNIT I

Microcontrollers for
1 an Embedded System - 8051

g
in
e er
Syllabus

in
Microcontrollers for an Embedded System - 8051 - Architecture - Program and Data Memoy

ng
Stacks.

fE
Contents
O
1.1 Introduction
1.2 Features of 8051 Microcontroller
g e

1.3 Architecture of 8051 Microcontroller. May-10,11,12,13,16, 18,


le

Dec.-10,11,14,16,18, 19,
Marks 16
ol

1.4 Program and Data Memory Dec.- 10,11,12,16, 17,19,


C

May-11, Marks 16
u

1.5 External Program and Data Memory Interfacing


ad

Dec.-10,17,18, May-12, Marks 13


1.6 Stack and Stack Pointer
iln
m
Ta

(1 -1)
<br>

Page 15 of 446

-
1-2 Microcontrollers for an Embedded System 8051
Embedded Systems and loT Design

1 Introduction
a mnicroprocessor. As shown in
Fig. 1.1.1 shows the simplified block diagram of
(ALO), general purpOse
Fig. 1.1.1, it consists of an Arithmetic and Logic Unit
(PC), clock timing circuit and
registers, Stack Pointer (SP), Program Counter
interrupt circuit.

g
in
Registers

er
Accumulator
ALU

e
in
General
purpose

ng
registers
Clock
and
Timing
circuit Stack
fE
pointer
O
Interrupt
circuits
Program
e

Counter
g
le

a microprocessor
ol

Fig. 1.1.1 Simplified block diagram of


not sufficient. It
C

• To make a complete microcomputer system only microprocessor is


as read only memory (ROM),
is necessary to add other peripherals such
u

devices to
read/write memory (RAM), decoders, drivers, number of input/output
ad

purpose devices, such


make a complete microcomputer system. In addition, special
as interrupt controller, programmable timers, programmable I/O
devices, DMA
iln

flexibility
controllers may be added to improve the capacity and performance and
of a microcomputer system.
m

is possible to
• The key feature of microprocessor based computer system is that it
Ta

a system as
design a system with a great flexibility. It is possible to configure
large system or small system by adding suitable peripherals.
• On the other hand, the microcontroller incorporates all the features that found n
microprocessor. However, it has also added features to make a complete
mcrocomputer system on its own. The microcontroller has built-in ROM, RAM,
parallel I/0, serial I/O, counters and a clock circuit. Fig. 1.1.2 shows the
simplified block diagram of a microcontroller.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 16 of 446

Embedded Systems and loT Design 1-3 Microcontrollers for an Embedded System - 8051

Registers

Temp Temp Parallel


register register |Accumulator

g
I/O
ports

in
General
purpose

er
registers
Stack

e
ALU pointer Serial
I/O -

in
Program ports

ng
COunter

Status Instruction
register register fE Interrupt
circuits
O
RAM Program
address address
e

register register
g

Timing Timer/
le

and Counter
control circuit
ol

EPROMI
RAM
C

ROM
u

Internal memory
ad

Fig. 1.1.2 Block diagram of microcontroller


iln

. As shown in Fig. 1.1.2, the microcontroller has on-chip (built-in) peripheral


m

devices. These on-chip peripherals make it possible to have single-chip


:
microcomputer system. There are few more advantages of built-in peripherals
Ta

Built-in peripherals have smaller access times hence speed is more.


Hardware reduces due to single chip microcomputer system.
. Less hardware, reduces PCB size and increases reliability of the system.

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


<br>

Page 17 of 446

-
Embedded Systems and loT Design 1-4 Microcontrollers for an Embeddod System 8051

1.1:1 Comparison between Microprocessor and Microcontroller


microcontroller.
Table 1.1.1 shows the comparison between microprocessor and
Microcontroller
No. Microprocessor
Microcontroller contains the circuitry of
Microprocessor contains ALU, general
1.
microprocessor and in addition it has
prpose registers, stack pointer,

g
programn counter, clock timing circuit built-in ROM, RAM, I/O devices, timers

in
and counters.
and interrupt circuit.
It has one or instructions to move
twwo

er
move data
2
It has many instructions to memory and CPU.
betweern memory and CPU. data between

e
It has many bit handling instructions,
3 It has one or two bit handling

in
instructions.

ng
Access times for memory and I/0 Less access times for built-in memory
4
and I/ devices.
devices are more.
5. Microprocessor based system requires
more hardware.
fE Microcontroller based system requires
less hardware reducing PCBsize and
increasing the reliability.
O
6. Microprocessor based system is more Less flexible in design point of view.
flexible in design point of view.
e

It has single memory map for data and It has separate memory map for data
e
g

7.
code. and code.
le

8. Less number of pins are More number pins are multifunctioned.


ol

multifunctioned.
C

Table 1.1.1

112 Different Types of Microcontrollers


u
ad

Like microprocessors, the microcontrollers have family of microcontrollers.


Different microcontrollers require different support chips and resources to
iln

develope particular microcontroller system. To choose and appropriate device to


meet system requirements we must understand differences, different options and
m

features of various microcontrollers.


Ta

1121 Embedded Microcontrollers


• When a complete hardware required to run a particular application is provided on
the microcontroller chip, it is referred to as an embedded microcontroller.
Embedded microcontrollers only require power, reset circuit and clock. Embedded
microcontrollers communicate with external devices with its digital I/0 pins.
Fig. 1.1.3 shows the typical microcontroller system with embedded microcontroller.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 18 of 446

Embedded Systems and loT Design 1-5 Microcontrollers for an Embedded System- 8051

XTAL, XTAL2

g
Parallel /O
R. Embedded

in
Microcontroller

er
Reset Serial l/O

e
0.1 uF

in
Interrupt control

ng
Vcco Vcc
Gnd Timer / counter control
0.01uFE
fE
O
Fig. 1.1.3 Typical microcontroller system with embedded
microcontroller
g e

1.1.2.2 External Memory Microcontrollers


program memory and data memory are
le

Sometimes, for large systems, the built-in


the connection
insufficient. To overcome this problem some microcontrollers allow
ol

memory some parallel port


of external memory. For the connection of external
C

connecting external memory to the


pins are used as address and data lines. Thus
Fig. 1.1.4 shows the
microcontroller reduces its parallel input/output capabilities.
u

the Fig. 1.1.4,


microcontroller with external memory connections. As shown in
ad

many times address and data lines are multiplexed and separated by external latch
microcontroller.
and ALE signal from the
iln
m

Address bus,
Ta

/O
port
JALE Data bus External
Microcontroller memory

Control bus
/O
port

memory connections
Fig. 1.1.4 Microcontroller with external

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 19 of 446

Embedded Systems and loT Design 1-6 Microcontrollers for an Embedded System - 8051

In the next two chapters we are going to study the microcontroller, 8051. The 8051
can work very effectively as an embedded device or with external memory. Its
architecture is also very thoughtful and practical combination of different
see different
philosophies. Before going to study architecture of 8051 we will
processor's architectures.

g
M23 vs RISC Microcontrollers
CISC

in
CISC is an acronym for Complex Instruction Set computers or computing It is
as well as

er
based on the concept of using very large instruction set having simple
complex instrctions and making instruction set more flexible to keep program

e
length as small as possible.

in
RISC refers to Reduced instruction Set Computers or Computing. RISC

ng
microcontrollers are very different from CISC microcontrollers. RISC use concept of
keeping the instruction set as simple as possible to allow the microcontroller's
program to be written using only simple instructions. fE
Sr. No. RISC
O
CISC
Instruction takes one or. two cycles Instruction takes multiple cycles
e

2. Only load/store instruction are used to In addition to load and store instructions,
g

access memory memory access in possible with other


le

instructions also
ol

3. Instruction executed by hardware Instruction executed by the micro


program
C

4
Fixed forimat instructions Variable format instructions
u

5. Few addressing modes Many addressing modes


ad

6. Few instructions Complex instruction set


iln

Most of them have multiple register Single register bank


banks
wwwww.
m

1.1.3 Criteria for Selecting Microcontroller


Ta

Criteria that designer should consider in choosing microcontrollers are :


• It should satisfy the computing needs of the task efficiently and cost effectively. It
should also satisfy the speed requirements, packaging format, RAM and ROM
capacity, number I/O pins, on-chip timers and power consumption needs of the
application.
Availability of software development tools' such as
compilers, assemblers and
debuggers.
Availability in needed quantities both now and in the future.
Its ability to upgrade to higher-performance or lower power consumption versions.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 20 of 446

Embedded Systems and loT Design 1-7 Microcontrollers for an Embedded System - 8051

1.1.4 Applications of Microcontroller


Microcontrollers are preferred in embedded products. Some applications of
microcontroller are
:

Home appliances : Washing machine, refrigerators, microwave ovens etc.


Calculators, keyboards, printers, modems, mobile phones etc.

g
in
Industrial controllers, data acquisition systems communication systems etc.
Automobile engines, flight control systems, traffic light control systems etc.

er
Millitary applications.

e
in
Review Questions

ng
a microcontroller and justify that a
1. Give the basic block diagrams, of a microprocessor and
microcontroller is an onchip computer. fE
2. Give the comparison bettween microprocessor and microcontroller.

3. List out the typical applications of microprocessors and microcontrollers.


O
memory microcontrollers.
4. Write a short notes on a) Embedded microcontrollers b) External
e

? Mention the typical applications


5. What criteria do designers consider in choosing microcontrollers
g

of microcontrollers.
le

6. Mention any two applications of 8051 microcontroller.


ol

1.2 Features of 8051 Microcontroller


C

was optimized for 8-bit


The 8051 is an 8-bit microcontroller designed by Intel. It
8031, 8051, 8052 and
math and single bit Boolean operations. Its family includes
u

8051 microcontroller.
8751 microcontrollers. Let us see the features of
ad

• The features of the 8051 family are as follows


:
iln

1. 4096 bytes on
-
chip program memory.
128 bytes on chip data memory.
-
2.
m

3. Four register banks.


Ta

4. 128 user-defined software flags.


5. 64 kilobytes each program and external RAM
addressability.
6. One microsecond instruction cycle with 12 MHz crystal.
as four 8-bit ports (16 lines on 8031).
7. 32 bidirectional I/0 lines organized
8. Multiple mode, high-speed programmable serial port.
9. Two multiple mode, 16-bit timers/counters.
10. Two-level prioritized interrupt structure.
11. Full depth stack for subroutine return linkage and data
storage.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 21 of 446

-
1-8 Microcontrollers for an Embedded System 8051
Embedded Systems and loT Design

12. Direct byte and bit addressability.


13. Binary or decimal arithmetic.
14. Signed-overflow detection and parity computation.
15. Hardware multiple and divide in 4 usec.

g
16. Integrated boolean processor for control applications.

in
17. Upwardly compatible with existing 8084 software.

er
Table 1.2.1 gives the comparison of MCS-51 family microcontrollers.

e
Feature 8031 8051 8052 8751

in
Sr. No.

None 4 K ROM 8KROM 4K EPROM


Program memory (in bytes)

ng
2.
Data memory (in Bytes) 128 RAM 128 RAM 256 RAM 128 RAM
3. Timers/ Counters (16-bit) fE 2 2 3 2
4
I/O pins 32 32 32 32
O
5. Serial Port 1 1 1

Interrupt Sources (Reset not included)


6
5 5 6 5
g e

Table 1.2.1 Comparison of MCS-51 family microcontrollers


As shown in Table 1.2.1, the 8052 has an extra 128 bytes of RAM, 4 K extra ROM,
le

extra timer and one more interrupt source than the 8051 microcontroller. The 8052
ol

maintains the source compatibility with 8051. This means that all programns written
for the 8051 will run on 8052; however, reverse is not true.
C

The 8751 microcontroller has 4 K of EPROM instead of ROM. This allows to erase
u

and reprogram the contents of program memnory within 8751. It takes around 20
minutes to erase the 8751 before it can be programmed again. This feature is very
ad

useful in the program development stage.


iln

ReviewQestion
m

1. List the salient features of 8051 microcontroller.


Ta

.....
e*****

1.3 Architecture of 8051 Microcontroller


AU": May-10,11,12,13,16,18, Dec:-10,11,14,16,18,19

Fig. 1.3.1 shows


the internal block diagram of 8051. It consists of a CPU, two
kinds of memory sections (data memory - RAM and program memory - ROM),
input/output ports and control logic needed for a timer/counter, serial port and
interrupt functions. These elements communicate through an eight bit data bus
which runs throughout the chip referred as internal data bus. This bus is buffered
to the outside world through an
I/0 port when memory or I/0 expansion is
desired.

TECHNICAL PUBLICATIONS - an up-thrust for knowiedge


<br>

Page 22 of 446

Embedded Systems and loT Design 1-9 Microcontrollers for an Embedded Systerm - 8051

External
interrupts
ON-CHIP Counter inputs
INTO INT1 ROM
for
Interrupt program ON-CHIP
T| Tol
control code RAM Timer 0
(4 Kbytes)

g
(128 Bytes) Timer 1

in
er
CPU Internal bus

e
in
Bus Four (8-bit) Serial
OSC I/O ports port

ng
Control

30 pF 30 pF
Multiplexed
fE
PO P1 P2 P3 TxD RxD
dataladdress
O
4 to 30 MHz -Multi-functional
Higher order
normally 11.0592 MHz address
e

Fig. 1.3.1 Block diagram of 8051 microcontroller


g

are
Central Processor Unit (CPU) It monitors and controls all operations that
:
le

performed by microcontroller. The CPU of 8051 consists of eight-bit arithmetic and


ol

program
logic unit with associated registers like A, B, PSW, SP, the sixteen bit a
counter and "Data pointer" (DPTR) registers. Along with these registers it has set
C

of special function registers and control unit.


u

as on-chip ROM in 8051. The 8051


ROM : A code of 4K memory is incorporated
ad

contents cannot be altered.


ROM is a non-volatile memory mneaning that its
is
• RAM: The 8051 microcontroller is composed of 128 bytes of internal RAM. This
iln

power is switched off. These


a volatile memory since its contents will be lost if
128 bvtes of internal RAM are divided into 32 working registers
which in turn
m

consisting of 8 registers
constitute 4 register banks (Bank 0-Bank 3) with each bank
the internal RAM.
Ta

(RO - R7). There are 128 addressable bits in


• IO Ports : The 8051 microcontroller has four 8-bit input/output ports: P0,
P1, P2
as general purpose ports. In the presence of external
and P3. All Ports can used and Port2
memory, Port 0 functions as a multiplexed address and data bus
port pins of port 3 are
functions as a higher order byte address bus. All
can be programmed to use as I/O or
multifunctional. Therefore, each pin of port 3
as one of the alternate function.
an internal (software) and external (hardware)
Interrupt Control It supports both
:
are provided.
interrupts. In 8051, 5 sources of interrupts

TECHNICAL PUBLICATIONs an up-thrust for knowledge


<br>

Page 23 of 446

-
1-10 Microcontrollers for an Embedded System 8051
mbedded Systems and loT Design

timers/counters. In timer mode,


Timers : 8051 supports twO multiple mode, 16-bit can
a particular and in counter mode they
they carn be used to generate delay of
be used to count external pulses.
:
Provides a method of establishing serial communication by
Serial Port to transmit and
and receiving data bits. It uses TxD and RxD pins
transmitting

g
receive bits, respectively.

in
clock to 8051 and decide baud
rate for
Oscillator : It is used for providing the

er
serial communication.

e
in
Review Questions
block diagram of 8051.

ng
1. With the help of neat diagram explain the internal
8051 microcontroller.
2. Explain with a neat block diagram the architecture of
fE AU: May-13, 16, 18, Marks 16

3. Explain the functional block diagram of 8051 microcontroller.


FAU:Dëc.-14; 19, Marks 6
O
1.3.1 Register Organization
e

Fig. 1.3.2 shows the register organization of 8051. It shows all CPU registers along
g

with the registers used for timers, interrupts and serial communication.
le

TMODTcON
ol

A B

Math registers Timer control registers


C

DPH i DPL THO TLO TH1 TL1


u

Data pointer Timerlcounter regiesters


ad

PC |scON SBUF PCON


iln

Program counter Serial data registers


m

PSW SP IP IE
Ta

Flags Stack Interrupt registers


pointer
Fig. 1.3.2 Register organization of 8051
1.3.1.1 A and B Registers

Register A (Accumulator)
• It is an 8-bit register called accumulator. It holds a source operand and receives
the result of the arithmetic instructions (addition, subtraction, multiplication and
division).

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 24 of 446

Embedded Systems and loT Design 1-11 Microcontrollers for an Embedded System - 8051

Several functions apply exclusively to the accumulator :


Rotate, parity
computation, testing for zero and so on.
Register B
• In addition to accumulator, an 8-bit B-register is available as a general purpose
register. It is used for the hardware multiply/divide operation.

g
in
1.3.1.2 Data Pointer (DPTR)
The data pointer (DPTR) consists of a

er
16-bit DPTR
high byte (DPH) and a low byte

e
(DPL). Its function is to hold a 16-bit
Memory
address. It may be marnipulated as a

in
DPH DPL
(82H)
Address
(83H)
16-bit data register or as two 16

ng
independent 8-bit registers. It serves as 8-bit 8-bit
a base register in indirect jumps, Fig. 1.3.3
lookup table instructions and external
fE
data transfer. The DPTR does not have a single internal address; DPH (83I) and
O
DPL (82H) have separate internal addresses.

1.3.1.3. Program Counter


e

The 8051 has a 16-bit program counter. It is used to hold the address of memory
g

location from which the next instruction is to be fetched.


le
ol

1.3.1.4 8051 Flag Bits/PSW Registers


.Fig. 1.3.4 shows the bit pattern of Program Status Word (PSW) of 8051. PSW is
C

also known as flag register.


u

B B6 B B4 B B B, Bo
ad

CY AC FO RS1 RSO OV P
iln

Fig. 1.3.4

The 8051 consists of following flags.


m

carry flag
CY-Carry Flag : This flag is set if there is an overflow out of bit. 7. The
Ta

also serves as a borrow flag for subtraction. In both the examples shown below,
the carry flag is set.
an overflow out of bit 3 i.e.,
AC-Auxiliary Carry Flag : This flag is set if there is
carry from lower nibble to higher nibble (D, bit to D, bit).

ADDITION SUBTRACTION

9B H 1001 1011 89 H 1000 1001


75 H + 0111 0101 AB H 1010 1011
0000 Borrow T
DE H
11101 1110
Carry 110 H 10001

TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
<br>

Page 25 of 446

1-12 Microcontrollers for an Embedded System -8051


Embedded Systems and loT Design

FO - Available for user for general purpose. as


working register bank
RS1 - RS0 (Register Bank Select): They select the
follows :
RS1 RS0 Bank Selection

g
-07H Bark 0

in
00H
Bank 1
08H- 0FH

er
1 10H - 17H Bank 2

e
- 1FH Bank 3
1 18H

in
a number
OV-Over Flow Flag This flag is set whenever the result of signed

ng
:
sign bit.
operation is too large, causing the high-order bit to overflow into the
ones present in the accumulator.
fE
P-Parity Flag Parity is defined by the number of
:

= ones are odd.


P=0, if number of ones are even and P 1, if number of
is as
Example : The status of CY, AC and P flags after the addition of 9BH and 65H
O
:
follows
e

Carry
1 1111 1
g

9BH 1
00 110 1 1
le

65H 0 1 1
00 10 1

10 00 00 00 0
ol

Accumulator
C

CY = 1, AC = and P = 0
1
u

There are instructions in 8051, that tests the condition of flags in the PSW register
ad

and make decision based on the status of flags. Thus, programmer use these flags
to perform some arithmetic operations which involves carry or borrow, or to
iln

change the program control (using conditional branching).


As mention earlier, programmer can select register bank by setting corresponding
m

bits in PSW.
Ta

1.3.1.5 Special Function Registers


The group of registers, implemented to perform special functions and are located
immediately above the 128 bytes of RAM are called special function registers. Al
access to the four I/O ports, the CPU registers, interrupt control registers, the
timer/counter, UART and power control are performed through registers between
80H and FFH:
Special Function Registers (SFRs) are a sort of control table used for running and
monitoring the operation of the microcontroller. Each of these registers as well as
each bit they include, has its name, address in the scope of RAM and precisely

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 26 of 446

Embedded Systems and loT Design 1-13 Microcontrollers for an Embedded System - 8051

defined purpose such as timer control, interrupt control, serial communication


control etc.
Even though there are 128 memory locations intended to be occupied by them, the
basic core, shared by all types of 8051 microcontrollers, has only 21 such registers.
Rest of locations are intentionally left unoccupied in order to enable the
manufacturers to further develop microcontrollers keeping them compatible with

g
the previous versions.

in
Fig. 1.3.5 shows special function bit addresses.

er
Direct Bit address Hardware
byte register

e
address (MSB) (LSB)
symbol

in
OFFH

ng
F7
OFOH F6 F5 F4F3 F2 F1 FO B

OEOH E7 E6 E5 E4 E3
fE
E2 E1 E0 ACC
O
ODOH D7 D6 D5 D4 D3 D2 D1 DO PSW
g e
le

0B8H BC| BB BA B9 B8 IP
ol

OBOH B7 B6 B5 B4 B3 B2 B1 BO P3
C
u

--
OA8H AF
---AC AB| AA A9 A8 IE
ad

A7
A6A5 A4 A3 A2 A1 A0 P2
iln

OAOH
m

98H 9F 9E 9D 9c 98 9A 99 98 SCON
Ta

90H 97 96 95 94 93 92 91 90 P1

8F 8E 8D 8C 8B 8A 89 88 TCON
88H

86 85 84 83 82 81 80 PO
80H 87

Fig. 1.3.5 SFR bit address

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


<br>

Page 27 of 446

Microcontrollers for an Embedded System- 8051


dded Systems and loT Dosign 1-14

the SFRS and their addresses and their value


a list of all in
Table 1.3.1 contains
binary at reset.
Address Value in Bìnary
Symbol Name
Accumulator
OEOH 0000 0000
*ACC
OFOH 000 0 0000

g
*B B Register

in
Program Status Word. ODOH 00000000
*PSW
0000 0111

er
Stack Pointer 81H
SP

e
DPTR Data Pointer 2 Bytes
0000 0000

in
Low Byte 82H
DPL 0
0
DPH High Byte 83H 000000

ng
*PO Port 0 80H 1.1111.111.

"P1 Port 1 fE
9OH 1111 111 1

*P2 Port 2 OAOH 1111 1111


O
"P3 Port 3 OBOH 11111111
e

OB8H 8051
X
XX 00000
"IP Interrupt Priority Control
g

8052 XX0 0 0000


le

OA8H 8051
O
XX0 0000
"IE Interrupt Enable Control
ol

8052 0X000.000
C

TMOD Timer/Counter Mode 89H 0000 0000


Control
u

TCON Timer/Counter Control 88H 0000 000 0


ad

*+ T2CON Timer/Counter 2 Control 0C8H 0000 000 0


iln

THO Timer/Counter 0 High Byte 8CH 00000000


Timer/Counter 0 Low Byte 8AH 000 00000
m

TLO

THI Timer/Counter 1 High Byte 8DH


Ta

0000:0000
TL1 Timer/Counter 1 Low Byte 8BH 0000 0
000
+ TH2 Timer/Counter 2 High Byte 0CDH 0000 0000
+ TL2 Timer/Counter 2 Low Byte 0CCH 0000 0.0.0 0

+ RCAP2H T/C 2 Capture Reg. High 0CBH 0 000 0000


Byte
+ RCAP2L T/C 2 Capture Reg. Low 0CAH
0000 0000
Byte

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 28 of 446

Embedded Systems and loT Design 1-15 Microcontrollers for an Embedded System - 8051

SCON Serial Control 98H 0000 O000


SBUF Serial Data Buffer 99H Indeterminate

87H HMOS 0XXX XXXX


PCON Power Control
CHMOS 0XXX 0000
- 8052 only

g
Table 1.3.1 List of all SFRs (*- Bit addressable, + )

in
* before register name indicates that it is a bit addressable.

er
+ before register name indicates that it is supported by only 8052.

e
|1.3.1.6 Stack and Stack Pointer

in
The stack refers to an area of internal RAM that is used to store and retrieve data
an internal RAM
quickly. The stack pointer register is used by the 8051 to hold

ng
address that is called top of stack. The stack pointer register is 8-bit wide. It is
fE
increased before data is stored during PUSH and CALL instructions and
decremented after data is restored during POP and RET instructions.
The stack array can reside anywhere in on-chip RAM. The stack pointer is
O

initialized to 07H after a reset. This causes the stack to begin at location 08H. We
can modify default location of stack by loading new location in stack pointer. For
g e

example,
le

MOV SP, # 13H


The operation of stack and stack pointer is illustrated in Fig. 1.3.6.
ol

On-chip RAM On-chip RAM


C

On-chip RAM
u

08 09
ad

09
07 08 Data
SP 07
08
06 SP SP SP+1 07
Stack pointer
iln
m

(b) Store operation


(a) Status of stack and
stack pointer of reset
Ta

Data 2 09
Data 1
09
08
SP Data 2 08 Read 07
Data 3 07 SPSP-1
Stack pointer

(c) Read operation


Fig. 1.3.6

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 29 of 446

-
1-16 Microcontrollers for an Embedded System 8051
Embedded Systems and loT Design

bit-addressable RAM and


The stack may overwrite data in the register banks,
bit-addressable RAM
scratch-pad RAM. Thus to avoid conflict with the register,
initialized at a higher location in the
and scratch-pad RAM data, the stack is
internal RAM.
FAUMay'l1, Dc.:11, 16; 18
1.3.2 Pin Diagram

g
1.3.7 shows the pin diagram of 8051.
The 8051 is packaged in a 40-pin DIP. The Fig.

in
It is important to note that
many pins of 8051 are used for more than one function. The

er
alternative functions of pins are shown in bold letters.

e
Vcc + 5V

in
P1.0 40
39 PO.0 (AD,)

ng
P1.1 2
Pi.2 3 38 PO.1 (AD)
PO.2 (AD2)
Port 1
P1.3
P14
4
5
fE 37
36 PO.3 (AD,)
PO.4
Port 0
P1.5 35 (ADA
O
6
P1.6 34 PO.5 (ADs)
P1.7 PO.6
e

8 33 (AD)
g

RST 32 PO.7 (AD,)


le

P3.0.(RXD) 10 8051 31 EA (Vpp)


P3.1 (TXD) (40-pin)
11 30 ALE (PROG)
ol

DIP
P3.2 (INTO)
12 29 PSEN
C

P3.3 (INT1) 13 28 P2.7 (A15)


Port 3 P3,4 (Toj P2.6 (A14
14 27
u

P3.5 (T) 26 P2.5 (A13)


ad

15
16 25 P2.4 (A12)
P3.6 (WR)
Port 2
P2.3 (A11)
iln

17. 24
P3.7 (RD)
XTAL 2
18 23 P2.2 (A1o)
Oscillator
m

signals XTAL 12 19 22 P2.1 (Ag


P2.0 (As)
Ta

GND 20 21

Fig. 1.3.7 Pin-out of 8051

The 8051 has 32 I/O pins configured as four eight-bit parallel ports (PO, P1, P2
and P3). All four ports are bidirectional i.e. each pin will be configured as input or
output (or both). All port-pins are multiplexed except the pins of port 1. Each port
cosists of a latch, an output driver and an input buffer.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 30 of 446

Embedded Systems and loT Design 1-17 Microcontrollers for an Embedded System - 8051

Port 0 (Pins 32 - 39) : Port 0 pins can be used as I/O pins. The output drives and
input buffers of port 0 are used to access external memory. Port 0 outputs the low order
byte of the external memory address, time multiplexed with the data being written or
read. Thus, port 0 can be used as a multiplexed address/data bus.
- 8)
Port 1
(Pins 1 :
Port 1 pins can be used only as I/O pins.

g
Port (Pins 21 28) : The output
2

in
drives of port 2 are used to access Symbol Position Alternate use
external memory. Port 2 outputs the

er
RD P3.7 External memory read signal.
high order byte of the external
External memory write signal.

e
memory address when the address WR P3.6

in
is 16 bits wide. Otherwise, port 2 is T1 P3.5 External timer 1 input.
used as an I/0 port.

ng
TO P3.4 External.timer 0 input.
Port 3 (Pins 10 17): All-
port INT1 P3.3 External interrupt 1 input.
pins of port 3 are multifunctional.
INTO P3.2
fE External interrupt 0 input.
Therefore, each pin of port 3 can be
O
programmed to use as I/O or as TXD P3.1 Serial data output.
one of the alternate function. They
RXD P3.0 Serial data input.
have special functions as shown
g e

below including two external Table 1.3.2


le

interrupts, two counter inputs, two


special data lines and two timing control strobes.
ol

Power-supply Pins Vcc (Pin 40) and Vss (Pin 20) 8051 operates on d.c. power
:
C

supply of +5 V with respect to ground. The +5 is to be connected to pin Voc and


V

ground to pin Vss with rated power supply current of 125 mA.
u
ad

Oscillator Pins XTAL2 (Pin 18) and XTAL1 (Pin 19) : For generating an internal clock
Signal, the external oscillator is connected at these two pins.
iln

ALE (Address Latch Enable, Pin 30): AD to AD, lines are multiplexed. To
an external latch and
m

demultiplex these lines and for obtaining lower half of an address,


ALE signal of 8051 is used.
Ta

RST (Reset, Pin 9): This pin is used to reset 8051. For proper reset operation, reset
Signal must be held high at least for two machine cycles, while oscillator is running.

(Program Store Enable, Pin 29) It is the active low output control signal used
:
PSEN
to activate the enable signal of the external ROM/EPROM. It is activated every six
as the read
OScillator periods while reading the external memory. Thus, this signal acts
strobe to external program memory.

TECHNICAL PUBLICATIONS - an up-thrust for knowedge


<br>

Page 31 of 446

Embedded Systems and loT Design 1-18 Microcontrollers for an Embedded System - 8051

EA(External Access, Pin 31) When the EA pin is high (connected to Vcc. program
:

fetches to addresses 0000H through OFFFH are directed to the internal ROM
and
are directed to extermal
program fetches to addresses 1000H through FFFFH
ROM/EPROM. When EA is low (grounded), all addresses (0000H to FFFFH) fetched by
progranm are directed to the external ROM/EPROM.

g
in
ReviewN Questions

er
1. Explain the function of register A.

e
2. Explain the function of register B.

in
3. Explain the function of program counter.
4. List out the different bit addressable SFR's available in 8051.

ng
5. Explain the significance of Processor Status Word. Briefly discuSs PSW register of 8051.
6. What is the necessity of a flag register in a microprocessor/microcontroller ?
fE
7. Explain the utility of bit FO in the status register of 8051 microcontroller.
8. For what condition the OV flag of 8051 is set after the addition instruction.
O
9. What a ?
is' stack
e

10. Discuss the need for stack memory in microcontrollers. How stack is operated in 8051? What is the
default location of stack ? How programmer can modify it
g

?
le

11. Give the details of PSW of 8051. FAU May-i0, Dec:19, Marks 2
and say how the CPU knous which bank is
ol

12. Quantify the number of register banks in 8051


currently in use. AU :
Dec.-10
C

13. Mention the size of DPTR and stack pointer in 8051 microcontroller. AU Máy-11, Marks 2
u

14. What is program status word of 8051 ? AU May-12, Marks 2


ad

15. Draw the pin dingram of 8051 microcontroller and explain its port structure.

TAU' Dec.-11,.Marks 8
iln

16. List the alternative functions assigned to port 3 pins of 8051 microcontroller.
m

AU May-11, Marks 2

17. ·Explain the pinouts of 8051 microcontroller. AU Dec.-18, Marks 13


Ta

14 Program and Data Memory AU: Dec-10,11,12,16,17,19, May-11


Fig. 1.4.1 shows the basic memory structure for 8051. It can access up to 64 K
program memory and 64 K data memory. The 8051 has 4 kbytes of
internal program
memory and 256 bytes of internal data memory.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 32 of 446

-
Embedded Systems and loT Design 1-19 Microcontrollers for an Embedded System 8051

Program memory

FFFFH FFFFH
EA
=0
Access

g
60 kbytes

in
External External
memory 64 kbytes

er
External
OR

e
1000H
OFFFH

in
=
4 kbytes EÃ 1
Internal Access

ng
0000 Internal 0000
memory
fE
O
Data memory

External data memory


e

Internal data memory


g

(SFRS)
FFFFH
le

FFH
Accessible by
ol

Accessible by
indirect direct
Upper addressing addressing
C

128 only AND 64 kbytes


80H external
u

7FH rnemory
ad

Accessible by
Lower direct & indirect
128 addressing
iln

0000H
m

Fig. 14.1
Ta

1.4.1 Internal RAM Organization


The 8051 has 128-byte internal RAM. It is accessed using RAM address register. The
Fig. 1.4.2 shows the organization of internal RAM. As shown in the Fig. 1.4.2 internal
RAM of 8051 is organized into three distinct areas :
Register bank
Bit addressable
General prpose.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 33 of 446

-
Embedded Systems and loT Design Microcontrollers for an Embedded System 8051
1-20

Byte Byte
address address
R7 7F
1F

1E R6
1D R$
1C R4

g
Bank 3 R3
1B

in
1A R2

er
19 R1

18 Ro

e
R

in
17
16 Re

ng
15 R5
14 RA
Bank 2
13
12
R3
Rz
fE
O
11

10 Ro B, B B
B4 B3 B
B, B
e

OF R7 7F 7E 7D7C 7B 7A 79 78 2F
g

OE Re 77 76 75 |74 73 72 71 70 2E
Rs
le

OD 6F 6E 6D6C 6B 6A 69 68 2D
00C R4 67 66 65 64 63 62 61 60 2C
ol

1
Bank
0B Rs 5F 5E 5D 5C 5B 5A 59 58 2B
C

R2 57 56 55 54 53 52 51 50 2A
09R4 4F 4E 4D 4C 4B4A 49 48 29
u

08 Ro 47 46 45 44 43 42 41 40 28
ad

07 R7 3F 3E 3D 3C 3B 3A 39 38 27
06 Rs 37 36 35 34 33 32 31 30 26
iln

05 Rs 2F 2E 2D 20 2B 2A 29 28 25
04 RA 27 26 25 24 23 22 21 20 24
m

Bank 0
03 Rs 1F 1E 1D 1C 1B 1A 19 18
23
02 R2 17
Ta

16 15 14 13. 12 11 10 22
01 R
OFOE OD OB
0A09 08 21
00 Ro 07 0605 04 03 0201 00 20
30
Register Bit addresses Byte General purpose
bank addresses
Fi. 1.4.2 Organization of internal RAM of 8051
1.4.1.1 8051 Register Banks (Working Registers)

The first 32-bytes from address 00H to 1FH of internal RAM constitute 32
working
registers. They are organized into four banks of eight registers each. The four register
banks are numbered 0 to 3 and are consists of eight registers named Ro to Rz.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 34 of 446

Embedded Systems and loT Design 1-21 Microcontrollers for an Embedded System- 8051

Each register can be addressed by name or by its RAM address.


Only one register bank is in use at a time. Bits RSO and RS1 in the PSW determine
which bank of registers is currently in use.

RS1 (PSW.4) RSO (PSW.3) Bank selection

g
0 Bank 0

in
Bank 1

er
1 Bank 2

e
in
Bank 3

ng
On reset, the bank 0 is selected and hence it is a default register bank. Register banks
when not selected can be used as general purpose RAM.
1.4.1.2 Bit / Byte Addressable
fE
The 8051 provides 16 bytes of a bit-addressable area. It occupies RAM byte addresses
O
from 20H to 2FH, forming a total of 128 (16 x 8) addressable bits.
e

An addressable bit may be specified by its bit address of 00H to 7FH, or 8 bits
may
g

form any byte address from 20H to 2FH.


le

For example, bit address 4EH refers bit 6 of the byte address 29H.
ol

1.4.1.3 General Purpose RAM


C

The RAM area above bit addressable area from 30H to 7FH is called general purpose
u

RAM. It is addressable as byte.


ad

1.4.2 ROM Space in the 8051


iln

The 8051 has 4 kbyte of internal ROM with address


space from 0000H to OFFFH. It is
programmed by manufacturer when the chip is built. This
part cannot be erased or
m

program. It is accessed
altered after fabrication. This is used to store final version of the
Ta

using program address register.

Review Questions
RAM in 8051 microcontroller
? AU: Dec.-10
1. What do you understand by bit addressable
8051 microcontroller.
2. Discuss the internal memory organization of the
Dec.-10, May-11, Marks 16
AU :

special function registers of 8051


3. DiscuSs about the organization of internal RAM and
AU : May-11, Marks 8
microcontroller in detail.

TECHNICAL PUBLICATIONS- en up-thrust for knowledge


<br>

Page 35 of 446

-
Embedded Systems and loT Design 1-22 Microcontrollers for an Embedded System 8051

4. Discuss in detail internal data memory organízation of microcontroller 8051.


AU :Dec.-19,-Marks 8
memory structure of 8051 nicrocontroller.
5. Explain the program memnory and data
AU : Dec-11, Marks 8

6. Draw the data memory structure of 8051 microcontroller and explain.

g
Marks 8
AU:Deci-12, 17,

in
7. Explain the RAM structure of 8051l microcontroller. AU: Dec.-16, Marks 8

er
1.5 External Program and Data Memory Interfacing

e
AU Dec 10,17,18, May-12

in
memory
We have seen that 8051 has internal data and code memory with limited

ng
some applications. In such
capacity. This memory capacity may not be sufficient for
situations, we have to connect external ROM/EPROM and RAM to 8051 microcontroller
fE
to increase the memory capacity. We also krnow that ROM is used as a program memory
and RAM is used as a data memory. Let us see how 8051 accesses these memories.
O
1.5.1 External Program Memory
e

Fig. 1.5.1 shows a map of the 8051 program memory.


g
le

Program memory
ol
C

FFFFH FFFFH
EA=0
u

60 kbytes Access
ad

External External
memory 64 kbytes
iln

OR External
m

1000H
OFFFH
4 kbytes EA = 1
Ta

Internal Access
0000 0000
Internal
memory

Fig. 1.5.1 The 8051 program memory

In 8051, when the EA pin is connected to Vcc program fetches to addresses 0000H
through OFFFH are directed to the internal ROM and program fetches to addresses
1000H through FFFFH are directed to external ROM/EPROM. On the other hand when
EA pin is grounded, all addresses (0000H to FFFFH) fetched by program are directed to

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 36 of 446

Embedded Systems and loT Design 1-23 Microcontrollers for an Embedded System - 8051

the external ROM/EPROM. The PSEN signal is used to activate output enable signal of
the external ROM/EPROM, as shown in the Fig. 1.5.2.

P
Do
P,
D,

g
EA ROM/EPROM

in
H
8051 A Ao

er
T
A7
ALE H Addr.
CLK

e
Ag

in
P2 A15
PSEN OE

ng
Fig. 1.5.2 Accessing external program memory

As shown in the Fig. the


1.5.2, fE
port 0-is used as a multiplexedaddress/bus. It gives
as a data bus. The
lower order 8-bit address in the initial T-cycle and later it is used
8-bit address is latched using external latch and ALE signal generated by 8051. The
O
port 2 provides the higher order &-bit address. Fig. 1.5.3 shows the timing waveforms
for
e

external program memory read cycle.


g
le

ALE
ol
C

PSEN
u
ad

INSTR Ag -A7
Ao -Ay IN
PORT O
iln

Ag -A15 Ay -A15
PORT 2
m

program memory read cycle


Fig. 1.5.3 Timing waveforms for external
Ta

memory stores the vector addresses for various interrupt


Ihe lower part of program map. Each interrupt is assigned
Service routines. Fig. 1.5.4 shows the vector address
with a fixed location in program
memory. For example, external interrupt 0 is assigned
are spaced at 8-byte intervals such as
,

to location 0003H. The interrupt service locations 1,


U003H for External Interrupt 0, 000BH for Timer
0, 0013H for External Interrupt

v0LBH for Timer 1, etc. If interrupt is going


to be used, its service routine must begin at
to be used, its service location is
cOTresponding location. If the interrupt is not going
available as general purpose program memory.

TECHNICAL PUBLICATIONS® - an up-thrust for knowledge


<br>

Page 37 of 446

-
Embedded Systems and loT Design 1-24 Microcontrollers for an Embedded System 8051

0033 H

002B H

g
in
Serial Port 0023 H

er
Timer 1 001B H
8 Bytes
Interrupt

e
External Interrupt 1 0013 H
Locations

in
Timer 0 000B H

ng
External Interrupt 0 0003 H

RESET 0000 H
fE
Fig. 1.5.4 InterruptWector locations in the lower part of program memory .
O

Instructions to Access External ROMI Program Memory


e

The Table 1.5.1 explains the instructions to access external ROM/program memory.
g
le

Mnemonic Operation
ol

MOVC A, @

A+ DPTR Copy the contents of the external ROM address


C

formed by adding A and the DPTR, to A.


u

MOVC A, @ A + PC Copy the,contents of the external ROM address


ad

formed by adding A and the PC, to A.


Table 1.5.1
iln

1.5.2 External Data Memory


m

Fig. 1.5.5 shows a map of the 8051 data memory.


Ta

The 8051 can address upto 64 kbytes of external data memory.


The "MOVX"
instruction is used to access the external data memory. The internal
data memory space
for 8051 is divided into three blocks : Lower 128 bytes,
Upper 128 bytes and SFRs. The
upper addresses and SFRs occupy the samne block of
address space, 80H through FFH,
although they are physically separate entities. As shown in the Fig. 1.5.5, the upper
address space is accessible by indirect addressing. only and SFRS are accessible
by direct
addressing only. On the other hand, lower address space can be accessed
either by
direct addressing or by indirect addressing.
<br>

Page 38 of 446

Embedded Systems and loT Design 1-25 Microcontrollers for an Embedded System - 805:

Data memory

Internal data memory External data memory

(SFRS)
FEH FEFFH
Accessible by
indirect Accessible by

g
Upper direct
128
addressing

in
addressing
only
AND 64 kbytes

er
80H:
external
7FH memory

e
Accessible by
Lowerdirect & indirect

in
128
addressing

ng
0000H
fE
Fig. 1.5.5 A map of the 8051 data memory
O
Fig. 1.5.6 shows the circuit diagram for connecting external data memory. The
multiplexed address/data bus provided by port 0 is demultiplexed by external latch and
e

ALE signal. Port 2 gives the higher order address bus. The RD and WR signals from
g
le

s051 selects the memory read and memory write operation, respectively.
ol
C

P Do
Pok
D7
u

+Vcc
EA RAM
ad

A Ao
T
A;
iln

8051 ALE H
CLK ADDR
m
Ta

PAGE
P2
RD P3 BITS

WR OE
WR

memory
Fig. 1.5.6 Accessing external data
memnory read and
Fig. 1.5.7 (a)and (b) shows the timing waveforms for external data
wite cycles, respectively.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 39 of 446

bedded Systems and loT Design 1-26 Microcontrollers for an Embedded System - 8051

ALE

PSEN

g
in
RD

e er
DATA KINSTR IN
PORT O Ao- Ay
IN Ag -Ay

in
FROM PCL
FROM RIOR DPL

ng
P2.0-P2.7 OR Ag-Ays FROM DPH Ag -A1s FROM PCH
PORT 2
fE
Fig. 1.5.7 (a) Timing waveforms for external data memory read cycle
O
ALE
g e

PSEN
le

WR
ol
C

PORT 0 Ag-Ay DATAOUT


u

INSTR IN
FROM PCL
ad

FROM RI OR DPL

PORT 2 P2.0-P2.7 OR Ag-A15 FROM DPH A8-A1s FROM PCH


iln

Fig. 1.5.7 (b) Timing waveforms for external data memory write cycle
Instructions to Access External Data Memory
m

The Table 1.5.2 explains the instruction to access external data memory.
Ta

Mnemonic Operation
MOVX A, @Rp Copy the contents of the external address in Rp to A.

MOVX A, ODPTR Copy the contents of the external address in DPTR to A.

MOVX @ Rp, A Copy data from A to the external address in Rp.

MOVX @DPTR, A
Copy data from A to the external address in DPTR.

Table 1.5.2

TECHNICAL PUBLICA TIONS - an up-thrust for knowledge


<br>

Page 40 of 446

Embedded Systems and loT Design 1-27 Microcontrollers for an Embedded System - 8051

1.5.3 Important Points to Remember in Accessing External Memory


All extermal data moves with external ROM or external RAM involve the
A register.
While accessing external memory, Rp can address 256 bytes and DPTR can address
64 kbytes.

g
• MOVX instruction is used to access external RAM or I/O addresses.

in
When PC is used to access external ROM, it is incremented by 1 (to point to the next

er
instruction) before it is added to A to form the physical address of external ROM.

e
Example,1.5.1 An 8051 based system requires external memory of four 4 kbytes of SRAM

in
each and two chips of EPROM of size 2 kbytes. The EPROM starts at address 2000H.

ng
SRAM address map follows EPROM map. Give the complete interface.

Solution: fE
A1s
Aj A13 A12 A A1o Ag Ag AyiAç AsA Ag Ag Aj Ap Address
O
1 0 0 0 0 2000H
EPROMO
e

1 0 1 1 1 1 1 1 1 1 1 27FFH
g
le

1 1 0 0 0 0 2800H
EPROM1
ol

00 1 1 1 1 1 1 1 1 1 1 1 1 1 2FFFH
C

0 0 0 0 0 3000F
1 0
RAMO
u

0 0 1 1 1 1 1 1 1 1 1 1 1 1 3FFFH
ad

0 1 0 0 0 0 0 0
0 4000H
RAM1
iln

1 1 1 1 1 1 1 1 4FFFH
0 1 0 1 1

5000H
m

1 1 0
0 0 0 0 0
0
RAM2
5FFFH
Ta

1 1 1
1 1 1 1 1 1 1
0 1

0 0 0 0 6000H
1 1 0 0
RAM3
0 1 1 1 1 1 1 1 1 1 6FFFH
1 1

-
TECHNICAL PUBLICATIONS an up-thrust for knowledge
<br>

Page 41 of 446

Embedded Systems and loT Design 1-28 Microcontrollers for an Embedded System- B08

AgA1s
Do-D,

0 1
EPROM EPROM

g
in
er
A-As4

e
(EPROM) 1
EPROM

in
DgD15

CS

ng
2K
OE

fE
O
Ayg-Ao

(EPROM)
0
EPROM
e

D,-Do
g

2K
le

OE
ol
C
u
ad

4
WR RAM

3|
RAM
A-A
iln

(RAM) 2
RAM

1
RAM 1
RAM 2
-RAM
3 4
D,Do K -RAM RAM
m

-
OE
Ta

8054

RST

Fig. 1.5.8

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 42 of 446

Embedded Systems and loT Design 1-29 Microcontrollers for an Embedded System - 8051

Review Questions

1. Explain program memory interfacing in 8051 microcontroller.


AU : May-12, Marks 8
2. Design an 8057 based system with 16 kbytes of program ROM and 16 kbytes of data ROM.
:
AU Dec.-10, Marks 16
3. Explain in detail the different methods of memory address decoding in 8051.

g
AU': Dec.-10, Marks 8

in
4. Explain twith block diagram, how to access external memory devices in an 8051 based system.

er
:
AU Dec.-17, Marks 6
5. Describe the timing diagram of external data memory read cycle of 8051.

e
AU : Dec.-18, Marks 13

in
ng
1.6 Stack and Stack Pointer
The stack refers to an area of internal RAM that is used to store and retrieve data
fE
quickly. The stack pointer register is used by the 8051 to hold an interrnal RAM address
that is called top of stack. The stack pointer register is &-bit wide. It is increased before
O
data iš stored during PUSH and CALL instructions and decremented after data is
restored during POP and RET instructions.
e

The stack array can reside anywhere in on-chip RAM. The stack pointer is initialized
g

to 07H after a reset. This causes the stack to begin at location 08H. The operation of
le

stack and stack pointer is illustrated in Fig. 1.6.1.


ol

On-chip RAM On-chip RAM On-chip RAM


C
u

08 09
09
ad

07 08
SP Data 08
06 SP 07
Stack pointer SP +SP+1 07
iln
m

(b) Store operation


(a) Status of stack and
stack pointer of reset
Ta

09 09
Data 1
Data 2
08
SP Data 2 08 Read
07 SP+ SP-1 07
Data 3
Stack pointer

(c) Read operation

Fig. 1.6.1

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 43 of 446

Microcontrollers for an Embedded System


-
Embedded Systems and loT Design 1-30 805

RAM
The stack may overwrite data in the register banks, bit-addressable
scratch-pad RAM. Thus to avoid conflict with the register, bit-addressable RAM
scratch-pad RAM data, the stack is initialized at a higher location in the internal RAM

Review Questions

g
1. Explain the operation of stack in 8051.

in
2. Define SP.

e er
in
ng
fE
O
g e
le
ol
C
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS
• an up-thrust for knowledge
<br>

Page 44 of 446

UNIT I

Addressing Modes
2 and Instruction Set of 8051

g
in
e er
in
Syllabus

ng
-
Addressing Modes Instruction Set

Contents fE June-08,11, Dec.-07,08,09,11,13, 14,


2.1 8051 Addressing Modes. .
O
May-13,14,16,17, Marks 16

Classification of Instruction Set of 8051 May-10


e

2.2
Dec.-07,08,11,16, 19,
g

2.3 Data Transfer Instructions


Marks 16
le

May-11
May-10, 11, Marks 10
Byte Level Logical Instructions.
ol

2.4 •
May-05, 08, June-11, Marks 2
2.5 Arithmetic Instructions
C

May-08, 10, 11, 17,


2.6 Bit Level Logical Instructions
u

Dec.-18, 19, Marks 13


ad

2.7 Rotate and Swap Instructions


June-09, Dec.-09
2.8 Jump and CALL Instructions
iln

2.9 Time Delay for 8051 .


May-10, Dec.-12, Marks 6
m

2.10 Program Examples


Ta

(2- 1)
<br>

Page 45 of 446

Embedded Systems and loT Design 2-2 Addressing Modes and Instruction Set of 8051

2.1 8051 Addressing Modes


14, 16,17
AU : June-08, 11, Dec.-07,08,09,1 1, 13,14, May-13,
or destination addresses are specified in the
The way, using which the data sources
section
instruction mnemonic for moving the data, is called 'addressing mode'. This
explains addressing modes used in 8051 with examples.

g
2.1.1. Register Addressing

in
the
The 8051 can access eight "working registers" (RO-R7). Three bit code within

er
instruction selects one of the eight registers fromn the selected register bank. The
programmer can select a register bank by modifying bits 4 and 3 in the PSW.

e
in
Destination register Source register

ng
Example: Add the contents of fE
register R3 and R4 from bank 2
Step 1 Select register bank.
O
;
MOV PSW, #00001000Bselect register Bank 2
Step 2 Add the contents of R3 and R4
e

MOV A, R3
-
g

ADD A, R4
le

2.1.2 Direct Byte Addressing


ol

Memory
C
u
ad

Destination register
iln

Address of memory
Data from within the instruction
selected memory
m

location
Ta

Direct addressing can access any on-chip vàriable or hardware


register i.e. on-chip
RAM and special function register. The most significant bit of the address decides
whether it is a location within on-chip RAM (MSB = 0) or in special function register
(MSB = 1).

Example : Add the contents of locations 50H and 51H


MOV A, 50H ; load byte from address 50H into A
ADD A, 51H ;Add the contents of and the contents at memory location 51H.
A

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 46 of 446

Embedded Systems and loT Design 2-3 Addressing Modes and Instruction Set of 8051

2.1.3 Register Indirect Addressing


In this addressing mode RO and R1 of each register bank can be used as an index or
pointer register. RO and R1 point to the contents in the RAM. The instruction with
indirect addressing uses the '® sign.
Indirect addressing accesses data in dynamic manner rather than static manner.
Looping is not possible in direct addressing mode. In indirect addressing we can

g
increment the index or pointer register to access successive locations.

in
er
Memory

e
in
Register

ng
Destination register
fE Contents of register are
used to point memory
Data from
O
selected memory
location
g e

and R1 are the only registers that


RO carn be used for pointers in register indirect
le

addressing mode.
ol

Example: ADD the contents of memory location addressed by register 1 to the


C

contents of RAM location pointed by register 0.


MOV A, @RO ;
load the contents pointed by RO in A
u

ADD A, @R1 :Add the contents of and the contents pointed by R1


A
ad

2.1.4 Immediate Addressing


iln

In this addressing mode source operand


a constant rather than a variable. So the Destination register
m

iS
constant can be incorporated in the Data specified
Ta

inthe instruction
nstruction. Sign " indicates it is a
immediate addressing mode.

Example : Add the constant 52 decimal in accumulator.


MOV A,
#52

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 47 of 446

Embedded Systems and loT Design 2-4 Addressing Modes and Instruction Set of 8051

2.1.5 Register Specific


Inherent in the instruction, these refer to a specific register such as accumulator Or
DPTR.

Example:
SWAP A :Swap nibbles within the Accumulator

g
in
2:1.6 Index

er
Only program memory can be accessed in the index addressing. Either the DPTR or
PC can be used as an index register.

e
in
DPTR Register

ng
Program memory

A Register
fE Contents of DPTR register
O
Data from Address of
selected memory memory
g e
le
ol
C

Contents of register A
u
ad

Example: Read data from the program memory.


MOVC A, @A+DPTR :This instruction adds the unsigned 8-bit
and accumulator contents into
iln

;sixteen uses
bit Data pointer, and the sum as an address from which
;byte to be moved into accumulator
m

2.1.7 Stack Addressing Mode


Ta

It is subtype of direct addressing mode in which


stack instructions (PUSH and POP)
are used. Instruction such as 'PUSH A' is
invalid. Here, we have to specify the address
of register A. Thus, PUSH OEOH is a valid instruction;
it pushes/stores the contents of
accumulator on the stack.
:
Examples
PUSH 04 Push R4 onto stack
PUSH 06 Push R6 onto stack

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 48 of 446

Embedded Systems and loT Design 2-5 Addressing Modes and Instruction Set of 8051

POP 02 Pop top of stack into R2


POP OFOH Pop top of stack into register B

Review Questions

1. Classify the addressing modes of 805l microcontroller. AU May-17, Marks 2


2. Explain the diferent addressing modes in 8051 in detail. AUFJune-08,,Dec.-07,08,11Marks 8

g
3. What are the

in
addresing modes of 8051 microcontroller ?
AU.Deci-11, May-13, Matks 2
4. What is register indirect addressing mode of microcontroller 8051 ? Give example.

er
AU June-11, Marks2

e
5. Explain the different addressing modes of 8051 microcontroller.

in
AUMay-13,14, TDec:13, Marks 16

ng
6. What are the addressing modes followed in 8051 microcontroller ? FAUDec-14, Marks 2

7. Explain the different addressing modes of 8051 microcontroller. AUEMay-16, Marks.8


fE
2.2 Classification of Instruction Set of 8051 AUE May-10
O
An instruction is a single operation of a processor defined by an instruction set
architecture. According to type of operations, the instruction set of 8051 is classified as,
e

Data Transfer Instructions.


g

Byte Level Logical Instructions.


le

Bit Level Logical nstructions.


ol

Arithmetic Instructions.
C

Jump and CALL Instructions.


u

Review Questions
ad

FAU May-10
1. List the different types of 8051 instructions.
set.
Give the classification of 8051 instruction
iln

2.

2:3 Data Transfer Instructions AUDec 07: 08,116 19, May:11


m

are used in different


An immediate, direct, register and indirect adaressing modes
Ta

MOVE instructions. Table 2.3.1 lists all types of data moving (data transfer) instructions.
: : 1/2
: Bytes 1/2/3 Cycies
MOV <dest>, <src> Move 8-bit/16-bit
Description : Copy the byte variable indicated by 'src-byte' into the 'dest-byte' location.
Flags are not affected.
to A.
MOVA, Rn Copy the contents of register Rn of selected register bank
RO of
MOV A, RO This instruction copies the contents of the register
:

Example :
selected register bank to the acciumulator.

- an up-thrust for knowledge


TECHNICAL PUBLICATIONs
<br>

Page 49 of 446

Embedded Systems and loT Design 2-6 Addressing Modes and Instruction Set of 8051

MOV A, direct Copy the contents of address specified with instruction to A.


Example : MOV 30H : This instruction copies the contents of memory location
A,

whose address is 30H to the accumlator.


MOV A, @Ri Copy the contents of-the address in Ri to A.
Example : MOV A, ©R1 : This instruction copies the contents of memory location
whose address is specified in the register R1 from selected register bank.

g
MOV A, #data Load data given in the instruction to A.
Example : MOV A, #30H : This instruction copies data given within instruction

in
(30H) into the accumulator.

er
MOVRn, A Copy the contents of A to register Rn of selected register bank.
:
Example MOV R2, A : This instruction copies the contents of accumulator in R2

e
register of selected register bank.

in
MOV Rn, direct Copy the contents of address to register Rn of selected register bank.

ng
Example : MOV R1, 40H :This instruction copies the contents at memory
address
40H into the R1 register of the selected register bank.
MOV Rn, #data
Example :
fE
Load data given in the instruction to register Rn of selected
MOV R2, #20H :This instruction loads 20H in the register R2
register bank.
of selected
register bank.
O
MOV direct, A Copy the contents A to the address specified
within instruction.
Example : MOV20H, A :This instruction
copies the contents of accumulator to the
e

direct memory address specified in the instruction


(20H).
g

MOVdirect, Rn Copy the contents of register Rn of selected barnk


register to the address
le

specified within instruction.


Example :
MOV 3OH, R2 : This instruction copies
the contents
ol

selected register bank to the direct memory address of register R2 of


instruction (30H). specified in the
C

MOVdirect, direct Copy the contents of the address specified


address specified within instruction. within instruction to the
u

Example : MOV 20H, 40H : This instruction


copies the contents of memory
ad

whose address is 40H to the memory location


location whose address is 20H.
MOVdirect, @Ri Copy the contents of the address
given by register Ri of selected
bank to the address specified within instruction. register
iln

:
Example MOV 20H, @R3 : This instruction
whose address is given by registercopies the contents of memory location
m

R3 of selected register
memory location whose address is 20H. bank into the
Ta

MOVdirect, #data Load data given within instruction


to the address specified within
instruction.
Example : MOV 3OH, #12H:This instruction
copies data given
(12H) into the memory location whose within instruction
address is 30H.
MOV @Ri, A Copy the contents of A to the
address given by register Ri of selected
register bank.
Exampe : MOV @R1, A : This instruction copies
memory location whose the contents of accumulator to the
address is given by register R1 of selected
bank. register

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 50 of 446

Embedded Systems and loT Design 2-7 Addressing Modes and Instruction Set of 8051

MOV GRi, direct Copy the contents of address specified within instruction to the address
specified by register Ri of selected register bank.
MOV eR2, 30H : This instruction copies the contents of memory location
:
Example
whose address is given within the instruction (30H) into the memory
location whose address is specified by register R2 of selected register
bank.
MOV @Ri, #data Load the data specified within instruction to the address specified by

g
register Ri of selected register bank.

in
Example :
MOV @R2, #30H:This instruction loads 3OH into the memory location
whose address is specified by register R2 of selected register bank.

er
MOVDPTR, #datal6 The data pointer is loaded with the 16-bit constant indicated. The second
byte (DPH) is the high-order byte, while the third byte (DPL) holds the

e
low-order byte.

in
Example : MOV DPTR, #1234H : This instruction loads the value 1234H into the

ng
Data Pointer : DPH will hold 12H and DPL will hold 34H.
Table 2.3.1

2.3.1 Instructions to Access External Data Memory


fE
O
The Table 2.3.2 explains the instruction to access external data memory.
Copy the contents of the external address in Ri to A.
e

MOVX A, ORi
MOVX A, RO: This instruction copies data from the 8-bit address in R0
@
g

Example :
to A.
le

MOVX A, @DPTR This instruction copies data from the 16-bit address in DPTR to A
ol

MOVX @Ri, A Copy data from A to the external address in Ri.


MOVX @R1, A This instruction copies data from A to the 8-bit address in
:
C

Example :
R1.
This instruction copies data from A to the 16-bit address in DPTR.
u

MOVX @DPTR, A
ad

Table 2.3.2
Important Points to Remember in Accessing External Data Memory
iln

• All external data moves with external RAM involve the A register.
can address
• While accessing external RAM, Rp can address 256 bytes and DPTR
m

64 kbytes.
Ta

or addresses.
• MOVX instruction is used to access external RAM I/0
ROMIProgram Memory
2.3.2 Instructions to Access External
access external ROM/program memory.
The Table 2.3.3 explains the instructions to
A
MOVC A, CA + DPTR Copy the contents of the external ROM address formed by adding
and the DPTR, to A.
formed by adding A
MOVC A, CA + PC Copy the contents of the external ROM address
and the PC, to A.
Table 2.3.3
- an up-thrust for knowledge
TECHNICAL PUBLICATIONs
<br>

Page 51 of 446

Embedded Systems and loT Design 2-8 Addressing Modes and Instruction Set of 8Os:

Important Points to Remember in Accessing External Read Only Memory


• When PCis used to access external ROM, it is incremented by 1 (to point to th
next instruction) before it is added to A to form the physical address of extema
ROM.
• data moves with external ROM involve the A register.
All external

g
• MOVC is used with internal or external ROM and can address

in
4 K of interna
code or 64 K of external code.

er
The DPTR and the PC are not charnged.

e
in
2.3.3 Data Transfer with Stack (PUSH and POP) Instructions

ng
PUSH direct : Push onto stack Bytes : 2 Cycles : 2
Description : fE
The Stack Pointer is incremented by one. The contents of the indicated variable is
then copied into the internal RAM location addressed by the Stack Pointer.
Otherwise no flags are affected.
O
Example : PUSH B: This instruction increments the stack pointer by one and stores the
contents of register. B to the internal RAM location addressed by the Stack
Pointer (SP).
g e

POP direct : Pop from stack Bytes :


2 Cycles : 2
le

:
Description The contents of the internal RAM location addressed by the Stack Pointer is
ol

read, and the Stack Pointer is decremented by one. The value read is then
transferred to the directly addressed byte indicated. No flags are affected.
C

Example : POP ACC: This instruction copies the contents of the internal RAM location
addressed by the stack pointer to the accumulator. Then the stack pointer is
decremented by one.
u
ad

Important Points to Remember during PUSH and POP


• When the SP contents become FFH, for the next PUSH,
the SP rolls over to 00H.
iln

The top of the internal RAM, ie. it's end address is 7FH. So next PUSHes after
m

TFH result in errors.


Ta

Generally the SP is set at address above the register banks.


The PUSH and POP operations may be applied to the Stack Pointer (SP).
When PUSH and POP operations are used for the registers from the register
banks
(bank 0 - bank 3), specify direct addresses within the instructions. Do not use
register name from register bank since the register name does not specify the bank
in use.

TECHNICAL PUBLICATIONS-an up-thrust for knowledge


<br>

Page 52 of 446

Embedded Systems and loT Design 2-9 Addressing Modes and Instruction Set of 8051

2.3.4 Data Exchange Instructions


When 8051 executes MOV, PUSH or POP instruction, the 'copy operation' takes place.
The data from the source address is copied to the destination address. The data at the
source address remains unchanged. The Exchange instructions move data from source
address to destination address and vice versa. Table 2.3.4 lists all types of exchange

g
instructions in 8051.

in
er
XCH A, Rn Exchange data bytes between register Rn and A.
:
Example XCH A, RO : This instruction exchanges contents of accumulator with the

e
contents of register RO of selected register bank.

in
XCH A, irect Exchange data bytes between address directly given within instruction and A.

ng
Example XCH A, 2011 : This instruction exchanges contents of accumulator with the
contents of memory whose address is given within the instruction (20H).

XCH A, @Ri
fE
Exchange data bytes between A and address in Ri.
Example: MOV A, @R2 : This instruction exchanges the contents of accumulator with
O
the contents of memory location whose address is given by the contents of
register R2 of selected register bank.
e

XCHD A, @Ri XCHD exchanges the low-order nibble of the Accumulator (bits 3-0), with
g

that of the internal RAM location indirectly addressed by the specified


le

register. The high-order nibbles (bits 7-4) of each register are not affected.
Example RO contains the address 20H. The Accumulator holds the value 36H
ol

(00110110B). Internal RAM location 20H holds the value 75H (01110101B). The
instruction, XCHD A, @R0 will leave RAM location 20H holding the value
C

76H (01110110B) and 35H (00110101B) in the Accumulator.


u
ad

Table 2.3.4
Important Points to Remember in Exchange Instructions
iln

Allexcharnges involve the A register.

• All exchanges take place internally within 8051.


m

When XCHD A, @ Ri instruction is executed, the upper nibble of A and the upper
Ta

nibble of the address in Ri do not change.


Immediate addressing mode cannot be used in the exchange instructions.

Review Questions

I. Write the I/O related instructions in microcontroller 8051.


AU: Dec.-08
What is the operation carried out when 8051 executes the instruction MOvC A, @ A + DPTR ?

-AU: Dec.-07
3. Mention the I/O instructions of 8051 microcontroller. FAU Dec-11, Marks'2

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 53 of 446

Embedded Systems and loT Design 2- 10 Addressing Modes and Instruction Set of 805i

4. Explain the data transfer instructions and program control instructions of 805l microcontroller.
AU: May-11, Marks 8

5. Explain the operations carried out when the folloving instructions are executed by 8051.
i) MOVX@ RO,A ii) MOVC A,@A + PC ii) RLC A iv) CJNE A, 50H, L2
v) XCH A, 30H where L2 and L3 are labels. AU Dec.-07, Marks: 16

g
in
2.4 Byte Level Logical Instructions AU : May-10, 11

er
The instructions ANL, ORL and XRL perform the logical functions AND, OR

e
and/or Exclusive-OR on the two byte variables indicated, leaving the results in the

in
first. No flags are affected.

ng
The byte-level logical operations use all four addressing modes for the source of a
data byte. Here, directly addressed bytes may be used as the destination with
fE
either the accumulator or a constant as the source. These instructions are useful for
clearing (ANL), setting (ORL) or complementing (XRL) one or more bits in a
O
RAM, output ports or control registers.
This is illustrated in following figures.
g e

X
XX X X XX X Unknown 8-bit binary number.
le

• 1 1
11 000 0 Masking pattern
ol

XXX X 0000 Result


C

Masked bits
u

Fig. 2.4.1 Masking using AND operation


ad

X X X X X X X X Unknown 8-bit binary number


iln

+ 1 1 1 1
0000 Setting pattern
1. 1
11
m

XXX X Result

Set bits
Ta

Fig. 2.4.2 Setting bit/s using OR operation

X X X X X X X X Unknown 8-bit binary number


000 0 1
11 1
Pattern for inverting lower 4-bits
X X X X
Result
Inverted bits
Fig. 2.4.3 Inversion of part of a number using XOR operation

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 54 of 446

8051
2- 11 Addressing Modes and Instruction Set of
Embedded Systems and loT Design

Table 2.4.1 gives the list of byte level logical operations.


:

Logical-AND
: for byte variables Bytes : 1/2/3 Cycles 1/2
ANL<dest-byte>, <src-byte>
operation between the variables
Description
:
ANL performs the bitwise logical-AND variable. No flags are
indicated and stores the result in the destination
affected.

g
to Accumulator Byte I Cycle 1
ANL A, Rn AND register

in
ANL A, R2: Logically ANDS
A
and R2 and store
Example:
result in A.

er
Accumulator Byte 2 Cycle 1
ANL A, direct AND direct byte to
Logically ANDs contents of A and

e
Example ANL A, 20H
memory location whose address is 20H and stores

in
result in A. Cycle 1
Byte 1

ng
@Ri AND indirect RAM to Accumulator
ANL A, and
contents of A

Example: ANL A, @R2 : Logically ANDs R2 and


memory location whose address is given by
stores result in A.
fE Byte 2 Cycle 1
ANL A, #data AND immediate data to Accumulator
Logically ANDs contents of A with
O
:
Example: ANL A, #50H
50H and stores result in A.
Byte 2 Cycle 1
e

ANL direct, A AND Accumulator to direct byte A


with the
contents of
ANL 20OH, A : Logically ANDs
g

Example : stores result at


contents of memory location 20H and
le

memory location 20H.


to direct byte Byte 3 Cycle 2
ol

ANL direct, #data AND immediate data contents


:
Logically, ANDs the of
ANL 20H, #20H
Example memory location 20H with data 20H and stores result
C

memory location 20H.


in Bytes : 1/2/3 Cycles: 1/2
u

ORL <dest-byte>, <src-byte>


: Logical-OR for byte variables
between the indicated
ad

ORL performs the bitwise logical-OR operation


Description :
variables, storing the restlts in the destination byte. No flags are affected.
Byte 1 Cycle 1
OR register to Accumulator
iln

ORL A, Rn
Example: ORL R2: Logically ORs the contents of A and R2
A,

and stores result in A.


m

to Accumulator Byte 2 Cycle 1


ORL A, direct OR direct byte
Ta

ORL A, 20H: Logically ORs the contents ofA


and
Example : A.
memory location 20H and stores result in
Byte 1 Cycle 1
ORL A, @Ri OR indirect RAM to Accumulator
conternts of A and
ORL A, @R2 Logically ORs the
:
Example
memory location whose address is given by register R2
and stores result in A.
Byte 2 Cycle 1
ORL A, #data OR immediate data to Accumulator
Example : ORL A, #32H : Logically ORs the contents of A
with
A

32H and stores result in


wwiwie

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 55 of 446

2-12 Addressing Modes and Instruction Set of 8051


Embedded Systems and loT Design
Byte 2 Cycle 1
oRL direct, A OR Accumulator to direct byte
ORS the contents of A with the
Example: ORL 30H, A:Logically result at
and stores
Contents of memory location 30H
memory location 30H.
Byte 3 Cycle 2
ORL direct, #data ORimmediate data to direct byte
contents of
ORL 20H, #30H : Logically
ORS the
Example: memory location 20H and data 30H and stores result at

g
memory location 20H.

in
:

<src-byte> :
Logical Exclusive-OR for byte variables Bytes 1/2/3 Cycles 1/2 :

XRL <dest-byte>,

er
XRL performs the bitwise logical Exclusive-OR operation
between the
Description No flags are
indicated variables, storing the results in the destination.

e
affected.

in
1 Cycle 1
Byte
XRL A, Rn Exclusive-OR register to Accumulator

ng
XRL A, R2 : Logically XOR the contents and R2A
of
Example:
and stores result in A.
Cycle 1
XRL A, direct
Example:
fE
Exclusive-OR direct byte to Accumulator
XRL A, 20H : Logically XORs the conternts of with A
Byte 2

memory location 20H and stores result in A.


O
1
XRL A, @Ri Exclusive-OR indirect RAM to A Byte 1 Cycle
Example: XRL A, @R2 : Logically XORs the.contents of and A
e

the memory location whose address is given by R2 and


g

stores result in A.
le

XRL A, #data Exclusive-OR immediate data to A Byte 2 Cycle 1

XRL A, #40H:Logically XORS the contents of with A


ol

Example
data 40H and stores result in A.
C

Cycle 1
XRL direct, A Exclusive-OR Accumulator to direct byte Byte 2
XRL 20H, A Logically XORs the contents at 20H and
Examplet
u

the A and stores the result at 30H.


ad

XRL direct, #data Exclusive-OR immediate data to direct Byte 3 Cycle 2


XRL 30H, #40H : Logically XORs the conternts at 30H
Example:
and data 40H and stores the result at 30H.
iln

:
CLR Bytes : 1 Cycles
A
Clear Accumulator :1
m

Description The Accumulator is cleared (all bits set on zero). No flags are affected.
Ta

CPL AComplement Accumulator Bytes : 1 Cycles:1


:
Description Each bit of the Accumulator is logically complemented (one's complement).
Bits which previously contained a one are changed to a zero and
No flags are affected.
vice-versa. wewwwwasvwwwwwwwwwwww
Table 2.4.1
Review, Questions

1. What is the operation of the given 8051 microcontroller


instructions : XRL A, direct ?

2. Explain the instruction set of 8051 microcontroller.


AU': May-11; Marks 2
AU,::May-10, Marks 10

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 56 of 446

Embedded Systemns and loT Desian 2-13 Addressing Modes and Instruction Set of 8051

2.5 Arithmetic Instructions AU': May-05, 08, June-11

The arithmetic operations of 8051 include increment, decrement, addition, subtraction,


multiplication, division and decimal operations.

2.5.1 Incrementing and Decrementing

g
in
1
Incrementing and decrementing instructions allow addition and subtraction of from
a given number. These instructions not affect C, AC and OV flags. Table 2.5.1 lists the

er
increment and decrement instructions.

e
Bytes : 1/2 Cycles: 1/2

in
:
INC <bytes Increment

ng
Description INC increments the indicated variable by 1. An original value of OFFH will
overflow to 00H. No flags are affected.
INC A Increment Accumulator by 1 fE Byte 1
Byte 1
Cycde

Cycle
1

1
INC Rn Increment register
O
Example INC R2 Increments contents of R2 by 1
Byte 2 Cycle 1
Increment direct byte
e

INC direct
Example : INC 20H : Increments. contents of memory location whose
g

instruction (20H) by 1.
address is given within the
le

Byte 1 Cycle 1
INC @Ri. Increment indirect RAM
ol

Example : INC ORZ : increment contents of memory location whose


1
address is given by register R2 by
C

1 Byte 1 Cycle 2
INCDPTR Increment Data Pointer by
u

: 1/2 : 1
DEC <byte>: Decrement Bytes Cycles
ad

: The variable indicated is decremented by 1. An original value of 00H wvill


Description
underflow to 0FFH. No flags are affected.
iln

1
Decremnent Accmulator Byte 1 Cycle
DEC A
m

1
Byte 1 Cycie
DEC Rn Decrement register
Ta

R3 by 1
Example: DEC R3 Decrements conterits of
1
Byte 2 Cycle
DEC direct Decrement direct byte
Example : DEC 2OH : Decrements the contents of memory location
whose address is 20H by 1.
1
Byte 1 Cycle
DEC ®Ri Decrement indirect RAM
Example: DEC R2 : Decrements the contents of menory location
whose address is given by regSter R2 by 1.
Table 2.5.1

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 57 of 446

Embedded Systems and loT Design


2-14 Addressing Modes and Instruction
Set of 8051

2.5.2 Addition
Table shows the list of addition instructions supported
by 8051.
ADD A, <src-bytes : Add Bytes :
12 Cycles :1
Description : Adds the byte variable indicated to the Accumulator,
Accumulator. The carry and auxiliary-carry leaving the result in the

g
flags are set, respectively, if there
is a carry-out from bit 7 or bit 3 and cleared, otherwise.

in
When adding signed integers, OV indicates a
sum of two positive operands, or a negative number produced as the

er
positive sum from two negative operands.
ADD A, Rn Add register to Accumiulator

e
Byte 1 Cycle 1
Example : ADD A, R2:Adds contents
ofA and R2 and storeresult

in
in A.

ng
ADD A, direct Add direct byte to Accumulator
Byte2Cycle 1
Example : ADD A, 20H Adds contents
of A memory whose
address is 20H and store result in A. and
fE
ADD A, @Ri Add indirect RAM to Accumulator
Example : ADD A, @R2 : Adds the contents Byte 1
Cycle 1
O
of A and memory
whose address is given by register R2 and stores result in A.
ADD A, #data Add immediate data to Accumulator
e

Example : Byte2Cycle 1
ADD A, #20H : Adds the contents of A
g

and 20H.
le

ADDC A, <src-byte> :
Add with Carry Bytes : 1/2
ol

Cycles :1
Description :
ADDC simultaneously adds the byte variable
indicated, the carry flag and the
C

Accumulator, respectively, if there is a carry-out


cleared otherwise. from bit 7 or bit 3 and
u

ADDC A, Rn Add register to AcCumulator with carry flag


ad

Example : Byte 1 Cycle 1


ADDC.A, R2: Adds the contents of A, R2
and carry flag,
and stores resuit in A.
iln

ADDC A, direct Add direct byte to A with carry flag


Example : Byte 2 Cycle 1
ADDC A,20H : Adds the contents A, memory
of
m

whose address is 20H and the carry location


flag and stores result
in A.
Ta

ADDC A, @Ri Add indirect RAM to A with carry


flag Byte 1 Cyele 1
Example: ADDC A, @R2: Adds the contents mnemory
whose address is given by register of A, location
R2 and the carry flag
and stores resut in the A.
ADDC A, #data Add immediate data to A
Example :
with carry flag Byte 2 Cycle 1
ADDC A, #20H : Adds the contents
and 20H and stores result of A and carry flag
in A.

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 58 of 446

Embedded Systems and loT Design 2-15 Addressing Modes and Instruction Set of 8051

2.5.3 Subtraction
Table shows the list of subtraction instructions supported by 8051.

SUBB A, <src-byte> : Subtract with Borrow Bytes 1/2 Cycles : 1

g
Description: SUBB Subtracts the indicated variable and the carry flag,
together from the

in
Accumulator, leaving the result in the Accumulator. SUBB sets the carry
(borrow) flag if a borrow is needed for bit 7 and clears otherwise. AC is set if a

er
borrow is needed for bit 3, and cleared otherwise. OV is set if a borrow is
needed into bit 6, but not into bit 7 or into bit 7, but not bit 6.

e
Precaution :
IH
the state carry is not known before starting a single or
of the

in
multiple-precision subtraction, it should be explicitly cleared by a LR C
instruction.

ng
SUBB A, Rn Subtract register from A with borrow Byte 1 Cycle 1
Example : fE
SUBB A, R3 : Subtracts contents of R3 and carry together
from A and stores resuts in A.
O
SUBB A,direct Subtract direct byte from À with borrow Byte 2 Cycle 1

Example: SUBB A, 20H Subtracts the contents of memory location


e

20H and carry together from A stores result in A.


g

SUBB A,@Ri Subtract indirect RAM from:A with borrow Byte 1 Cycle 1
le

Example :
SUBB A, @R2 : Subtracts the contents of memory location
whose address is given by R2 and carry together from A
ol

and stores result in A.


C

SUBB A,#data Subtract immediate data from A with borrow Byte 2 Cycle 1
Example :
SUBB A, #20H : Subtracts 20H from A and stores result in A.
u
ad

2:5.4 Multiplication and Division


iln

MUL AB: Multiply Bytes :1 Cycles : 4


m

Description MUL AB multiplies the unsigned eight-bit integers in the Accumulator and
register B. The low-order byte of the sixteen-bit product is left in the
Ta

Accumulator, and the high-order byte in B. If the product is greater than. 255
(FFH) the overflow flag is set; otherwise it is cleared. The carry flag is always
cleared.

Example :
Originally the Accumulator holds the value 80 (50H). Register B holds the value
160 (0A0H). The instruction, MUL AB will give the product 12,800 (3200H), so B
is changed to 321 (00110010B) and the Accumulator is cleared. The overflow flag
is set, carry is cleared.
<br>

Page 59 of 446

Embedded Systems and loT Design 2-16 Addressing Modes and Instruction Set of 8051

: 4
DIV AB: Divide Bytes :1 Cycles

by the
Description DIV AB divides the unsigned eight-bit integer in the Accumulator
B. The Accumulator receives the integer
unsigned eight-bit integer in register carry
part the quotient; register B receives the integer remainder. The
of and Ov
flags will be cleared.
the
If B had originally contained 00H, the values returned in set.
:

Exception
undefined and the overflow flag will be
Accumulator and B-register will be

g
The carry flag is cleared in any case.

in
The Accumulator contains 250 (0FBH or 11111010B) and
B contains 18 (12H or
Example :
in the Accumulator (0DH or

er
00010010OB). The instruction, DIV AB will leave 13
= x
value 16(10H or 00010000B) in B, since 250 (13 18) 16.
+
00001101B) and the

e
Carry and OV will both be cleared.

in
ng
2.5.5 Decimal Arithmetic
:
DA A: Decimal-adjust fE
Accumulator for addition Bytes 1 Cycles:1

Description Adjusts the eight-bit value in the Accumulator resulting from the earlier addition
O
of two variables (each in packed-BCD format), to produce packed-BCD result.
If the lower nibble of the accumulator is greater than 9 or AF is set, it corrects
the result by adding 06 in the lower nibble. If the upper nibble of the
e

accumulator is greater than 9 or CF is set, it corrects the result by adding 06 in


g

the upper nibble.


le

: =
Example A
55H, B= 68H and CF =1. Then i:struction sequence
ol

ADDC A, R3
DA
A
C

will first perform a standard binary addition, resulting in the value BEH
(10111110) in the Accumulator. The carry and auxiliary carry
cleared.
flags wìll be
u

Since lower ribble >9, Lower níbble EH + 6H = 4H with AF=1


ad

Since upper nibble > 9, Upper nibble BH + 6H + AF(1) = 2H with CF=1


Thus the final result - 124, which is valid BCD sum.
iln
m

Review Questions
Ta

1. What is the tme taken to execute


MIL instruction in 8031 ? AUMay-05
2. How can you perform multiplication using 8051 microcontroller ?
AU May-08
3. List the arithmetic instructions of microcontroller 8051. AU June-11; Marks 2

2.6 Bit Level Logical Instructions FAU:May-08, 10,117 Deç.-18, 19


Bit level manipulations are very
convenient when it is necessary to set or reset a
particular bit in the internal RAM or SFRs. The internal RAM 8051
of from address 20H

TECHNICAL PUBLICATIONS® an
up-thrust for knowledge
<br>

Page 60 of 446

Embedded Systems and loT Design 2-17 Addressing Modes and Instruction Set of 8051

through 2FH is both byte addressable and bit addressable. However, byte and bit
addresses are different. The Table 2.6.1 shows the correspondence between byte and bit
addresses.

Byte Address in Hex Bit Address in Hex Byte Address in Hex Bit Address in Hex
20 00-07 28 40-47

g
21 08-0F 29 48-4F

in
22 10-17 2A 50-57

er
23 18-1F 2B 58-5F

e
24

in
20-27 2C 60-67

25

ng
28-2F 2D 68-6F

26 30-37 2E 70-77

27 38-3F
fE 2F 78-7F

Table 2.6.1 Bit and byte addresses of internal RAM


O
As shown in the Table 2.6.1,
SFR Direct Address Bit Address in
e

addresses of bit 0 and bit 7 of


in Hex Hex
g

internal RAM byte address 20H


are 00H and 07H respectively.
le

A E0 E0-E7
From Table 2.6.1 we can easily
ol

B FO FO-F7
of 1 and
interpolate addresses bit
A8-AF
C

IE A8
bit 6 of internal RAM byte
address 26H as 31H and 36H, IP B8 B8-BF
u

respectively:
ad

PO 80 80-87
Like internal RAM, some SFRs
P1 90 90-97
iln

are bit addressable. The


P2 A0 A0-A7
Table 2.6.2 shows the bit
m

addressalble SFR and the P3 B0 BO-B7

corresponding bit addresses.


Ta

PSW DO D0-D7

TCON 88 88-3F

SCON 98 98-9F

Table 2.6.2 Bit and byte addresses of SFRs

TECHNICAL PUBLICATIONs an up-thrust for knowledge


<br>

Page 61 of 446

Embedded Systems and loT Design 2- 18 Addressing Modes and Instruction Set of 8051

Table 2.6.3 gives the list of bit level operations.

CLR C: Clear Carry flag Bytes : 1 Cycles :1


CLR bit: Clear direct bit Bytes : 1 Cycles :1
Description : The indicated bit is cleared (reset to zero). No other flags are affected.
Example: Port 1 has previously been written with FFH (11111111B). The instruction
CLR P1.2 will leave the port set to FBH (11111011B)

g
*********eets*i
SETB C: Set Carry flag Bytes : 1 Cycles :1

in
SETB bit : Set direct bit Bytes : 2 Cycles : 1

er
Description : SETB sets the indicated bit to one. SETB can operate on the carry flag or any
directly addressable bit. No other flags are affected.

e
Example: The carry is cleared. Output Port 1 has been written with the value 34H

in
(0011010ÓB). The instruction,

ng
SETB C
SETB P1.0
will leave thecarry flag set to 1,and change the data output on Port 1 to
CPL
35H (00110101B).
C: Complement Carry flag
fE Bytes : 1 Cycles :1
CPL
O
bit: Complement direct bit Bytes :
2 Cycles : 1
: The bit variable specified is complemented. No other flags are affected.
Description
e

Example : Port 1 has previously been written with FFH (11111111B). The
CPL P1.1 will leave the port set to FDH (11111101B) instruction
g

ANL C, <src-bitb: Logical-AND for bit variables


le

Bytes : 2 Cycles:2
Description : If the Boolean value of the source bit is a logical 0 then clear the carry flag;
ol

otherwise leave the carry flag in its current state. A slash


operand in the assembly language indicates that the logical ("/") preceding the
C

the addressed bit is used as the source value, but the source complement not of
affected. No flags are affected. bit itself is
u

Only direct addressing is allowed for the source operand.


ad

{ANL C, bit AND direct bit to Carry flag


Byte 2 Cycle 2
Example :
ANL C, ACC:7: And Carry with Accumulator bit 7
iln

ANL C, bit AND complement of direct bit to Carry Byte 2 Cycle 2


Example : ANL C, /ov And with inverse of Overflow flag
m

ORL C, <src-bit>:Logical-OR for bit variables


Bytes : 2 Cycles :2
Ta

Description Set the carry flag if the Boolean value is a logical 1;


:

current state otherwise slash ("/") preceding the leave the carry in its
operand in the assembly
language indicates that the logical complement of the addressed
as the source value, but the source bit is used
are affected.
bit itself is not affected. No other flags

ORL C, bit OR direct bit to Carry flag


Byte 2 Cycle 2
Example : ORL C, ACC.7: Or Carry with the ACC.bit7
ORL C, bit OR complement of direct bit to
: Carry Byte 2 Cycle 2
Example ORL C, /OV:Or Carry with
the
inverse of OV

TECHNICAL PUBLICATIONS -an


up-thrust for knowledge
<br>

Page 62 of 446

Embedded Systems and loT Design


2-19 Addressing Modes and Instruction Set of 8051

MOV <dest-bit>, <src-bit> :


Move bit data Bytes :2 Cycles :1/2
:
Description The Boolean variable indicated by the second operarnd is
location specified by the first cperand. One of the operands copied into the
carry flag: the other may be any directly must be the
addressable bit. No other register or
flag is affected.
MOV C, bit Move direct bit to Carry flag Byte 2 Cycde 1
Example : MOV C, P3.3: Copies the status
of P3.3 into carry.

g
MOV bit, C Move Carry flag to direct bit Byte 2

in
Cycle 2
Example:
Bvowwww.
MOV P1.3, C: Copies the status of carry into P1.3.

er
Table 2.6.3
Review Question

e
in
1. Name any four bit manipulation instructions in microcontroller 8051.
EAU Mäy-08:
2. What are the various operations performed by boolean variable

ng
instructions of 8051 ? AUMay-10,
3. What are the different operations performed by boolean variable
instructions of 8051 ?
fE AUMay 11, Marks2
4. What is meant by bit oriented instructions ? AUE May 17. Marks 2
5. Explain the various bit manipulation instructions in 8051 with examples.
O
AU: Dec18, Märks T3

2:7. Rotate and Swap Instructions


g e

The Table 2.7.1 gives the list of rotate and swap operations supported by 8051.
le

RL A
Rotate Accumulator Left
ol

:
Bytes 1 Cycles :1
The eight bits in the Accumulator are rotated one bit to the left. Bit 7 is
C

:
Description
rotated into the bit 0 position. No flags are affected.
u

7 6 5
43 2 1
ad

The Accumulator holds the value C5H (11000101B), The instruction RL A


iln

Example leaves the Accumulator holding the value 8BH (10001011B) with the carry
unaffected.
m

RLC A : Rotate A
Left through the Carry flag Bytes : 1
Cycles :1
Ta

Description The eight bits in the Accumulator and the carry flag are together rotated
one bit to the léft. Bit 7 moves into the carry flag:; the original state of the
carry flag moves into the bit 0 position. No other flags are affected.
C7 65 4 3 210

Carry flag
Example :
The Accumulator holds the value C5H (11000101B) and the carry is zero.
The instruction, RLC A leaves the Accumulator holding the value 8BH
(10001010B) with the carry set.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 63 of 446

Embedded Systems and loT Design 2-20 Addressing Modes and Instruction Set of 8051

RR A: Rotate Accumulator Right Bytes : 1 Cycles:1

Description :
The eight bits in the Accumulator are rotated one bit to the right. Bit 0 is
rotated into the bit 7 position. No flags are affected.

7 6 5 4 3 2 1

g
in
:

Example The Accumulator hclds the value C5H (11000101B). The instruction, RR A

er
leaves the Accumulator holding the value E2H (11100010B) with the carry
unaffected.

e
RRC A : Rotate A Right through Carry flag Bytes :
1 Cycles :1

in
The eight bits in the Accumulator and the carry flag are together rotated
:
Description

ng
one bit to the right. Bit 0 moves into the carry lag, the original value of
the carry flag moves into the bit 7 position. No other flags are affected.
fE
7 6 5 4 3 2 1
O

Carry
e

flag
g

Example : The Accumulator holds the value C5H (11000101B),


the carry is zero. The
le

instruction RRC A leaves the Accumulator


(01100010B) with the carry set. holding the value 62
ol

SWAP A:Swap nibbles within the Accumulator Bytes : 1


Cycles:1
C

Description : Swap A interchanges the low and high-order nibbles


Accumulator (bits 3-0 and bits 7-4). The operation can (four-bit fields) of the
u

a four-bit rotate also be thought of as


instruction. No flags are affected.
ad
iln

7 4 3
Higher nibble| Lower nibble
m
Ta

Example : The Accumulator holds the value CSH (11000101B).


A leaves the Accumulator holding The instruction SWAP
the value 5CH (01011100B)
w

Table 2.7.1

2.8 Jump and CALL Instructions AU:June-09; Dec-09


Jump and CALL instructions change the flow
of the program by changing the
contents of program counter. A jump permanently changes
the program flow whereas
call temporarily changes the program flow to allow another part of
the program to run.
TECHNICAL PUBLICATIONSs - an up-thrust
for knowiedge
<br>

Page 64 of 446

Embedded Systens and loT Deslgn 2-21 Addressing Modes and Instruction Set of 8051

There are jump instructions which change the program flow if certain condition exists.
For example, CjNE (compare and jump if not equal). This instruction compares the
magnitude of the first two operands and changes program Alow if their values are not
equal.
The following types of instructions change the program flow :

Jump on bit conditions.

g
Compare byte and jump if not equal.

in
Decrement byte and jump if zero.

er
Jump unconditionally.

e
Call a subroutine.

in
Return from a subroutine.

ng
2.8.1 Jump and Call Program Range
fE
We know that a jump and call instructions replace the contents of the program
counter with a new program address. The new address can be specified either by
O
specifying the difference between the new address and the current program counter
conternts or by specifying the entire new address. The difference, in bytes, of the new
e

address from the address in the program counter is called the range of the jump or call.
g

For example, if a jump instruction is located at program address 0200H and the jump
le

causes the program counter to become 0230H, then the range of the jump is 30H bytes.
ol

Jump and CALL instructions may have one of the three ranges.
C

-
Relative (short) range:+127 to 128 (+7FH to- 80H)
u

Absolute range 0000H to 07FFH


:
ad

Long range 0000H to FFFFH


:
iln

2.8.2 Jump
m

The Table 2.8.1 shows the list of jump instructions supported by 8051.
Ta

Bytes : 2
Cycles :2
AJMP addr11: Absolut Jump
AJMP transfers program execution to the indicated address. Since address
: is
Description same program
11-bit the destination must therefore be within the 2K block of
memory as the first byte of the instruction following AJMP. No flags are affected.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 65 of 446

Embedded Systems and loT Design 2- 22 Addressing Modes and Instruction Set of 8051

LJMP addr16 : Long Jump Bytes : 3 Cycles :2


the
Description
:
LJMP causes an unconditional branch to the indicated áddress by loading
high-order and low-order bytes of the PC(respectively) with the second and third
K
instruction bytes. The destination may therefore be anywhere in the full
64
program memory address space. No flags are affected.
:
SJMP rel :
Short Jump (relative addr) Bytes 2 Cycles :2

g
in
Description
:
Program control branches unconditionally to the address indicated. The branch
destination is computed by adding the signed displacenment in the second

er
instruction byte to the PC, after incrementing the PC twice. Therefore, the range
of destinations allowed is from 128 bytes preceding this instruction to 127 bytes

e
following it.

in
JMP @A+DPTR : Jump indirect relative to the DPTR
:
Bytes 1 Cycles :2

ng
Description : Add the eight-bit unsigned.conitents of the Accumulator with the sixteen-bit data
pointer, and load the resulting sum to the program counter. This will be the
fE
address for subsequent instruction fetches.
Neither the accumulator nor the data pointer is altered. No flags are affected.
O
:
Jump if Accumulatot is zero
:
JZ rel :
Bytes 2 Cycles 2
e

Description :
If all bits of the Accumulator are zero, branch to the address indicated; otherwise
g

proceed with the next instruction. The accumulator is not modified. No flags are
affected.
le

JNZ rel :Jump if Accumulator is not zero Bytes : 2 Cycles :2


ol
C

Description :
If any bit of the Accumulator is a one, branch to the indicated address; otherwise
proceed with the next instruction. The accumulator is not mnodified. No flags are
affected.
u
ad

JC rel : Jump if Carry flag is set Bytes : 2 Cycles :


2

Description : If the carry flag is set branch to the address indicated; otherwise proceed with the
iln

next instruction. No flags are affected.


m

JNC rel : Jump if no Carry flag Bytes : 2 Cycles : 2


Ta

Description: If the carry flag is a zero, branch to the address indicated; otherwise proceed with
the next instruction. The carry flag is not modified.
:
JB bit, rel Jump if direct Bit set Bytes : 3 Cycles : 2
Description: If the indicated bit is one, jump to the address indicated; otherwise proceed with
the next instruction. The bit tested is not modified. No flags are afected.

JNB bit, rel : Jump if direct Bit not set Bytes : 3 Cycles :2
Description :
If the indicated bit is a zero, banch to the indicated address; otherwise proceed
with the next instruction. The bit tested is not modified. No flags are affected.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 66 of 446

Embedded Systems and loT Design 2-23 Addressing Modes and Instruction Set of 8051

JBC bit, rel : Jump if direct Bit is set and Clear bit Bytes : 3 Cycles : 2
:
Description If the indicated bit is one, branch to the address indicated; otherwise proceed
with the next instruction. The bit will not be cleared if it is already a zero.

CJNE <dest-byte>,<scr-byte>, rel : Compare and Jump if Not Equal


Bytes : 3 Cycles : 2

g
in
:
Description CJNE COmpares the magnitudes of the first two operands, and branches if their
values are not equal. The carry flag is set if the unsigned integer value of

er
<dest-byte> is less than the unsigned integer value of <src-byte>; otherwise, the
carry is cleared. Neither operand is affected.

e
in
DJNZ <byte>, <rel-addr> : Decrement and Jump if Not Zero
Bytes : 2/3 Cycles : 2

ng
Description : DJNZ decrements the location indicated by 1, and branches to the address
fE
indicated by the second operand if the resulting value is not zero. An original
value of 00H will underflow to OFFH. No flags are affected.
O
: 1
NOP Function : No Operation Bytes 1 Cycles:

Description: Execution continues at the following instruction. Other than the PC, no registers
e

or flags are affected.


g
le

Table 2.8.1
ol

2.8.3 CALL and Subroutines


C

ACALL
There are two subroutine-call instructions. LCALL (Long Call) and
(Absolute Call). Each increments the PC to the first byte of the following instruction,
u

the stack
then pushes it onto the stack (low byte first). Saving both bytes increment
ad

same ways as LJMP


pointer by two. The subroutine's starting address is encoded in the
CALL, which 8051
and AJMP. The generic form of the call operation is the mnemonic
iln

will translate into LCALL or ACALL as appropriate.


m

of the program
The return instruction RET pops the high and low-order bytes
two. Program
counter successively from the stack, decrementing the stack pointer by
Ta

The first byte of the instruction


:

execution continues at the address previously pushed


immediately following the call.
:
Call
Bytes 2 Cycles :2
ACALL addr11:Absolute
a located at the indicated address. The
Description ACALL unconditionally calls subroutine
to obtain the address of the following
instruction inçrements the PC twice onto the stack (low-order byte first) and
instruction, then pushes the 16-bit result address is 11-bit the subroutine called
increments the Stack Pointer twice. Since
start within the same 2 K block of the program memory as the
must therefore ACALL. No flags are affected.
first byte of the instruction following
oewww

PUBLICATIONS® - an up-thrust for knowledge


TECHNICAL
<br>

Page 67 of 446

2-24 Addressing Modes and Instruction


Set of 8051
LCALL addr16 : Long
Call Bytes : 3 Cycles :2
Description : LCALL calls a subroutine located at the indicated address.
three to the program counter to generate the address The instruction adds
then pushes the 16-bit result onto the stack (low of the next instruction and
stack pointer by two. The high-order and byte first), incrementing the
low-order bytes of the PC are then
loaded, respectively, with the second and third bytes
of the LCALL instruction.
Program execution continues with the instruction at
may therefore begin anywhere this address. The subroutine
in the full 64 kbyte program memory address

g
space. No flags are affected.

in
RET : Return from subroutine

er
Bytes : 1
Cycles :2
Description RET pops the high and low-order bytes of

e
the PC successively from the stack,
decrementing the Stack Pointer by two program

in
resulting address. No flags are affected. execution continues at the

ng
RETI: Return from Interrupt
: 1
Bytes Cycles : 2
Description :
RETI pops the high and low-order fE bytes of the PC successively from the stack,
and restores the interrupt logic to accept
priority level as the one just processed. additional interrupts at the same
O
two. No other registers are affected; The Stack Pointer is left decremented by
the PSW is not automatically restored to
per-interrupt status. Program execution continues its
at the resulting address, which
e

is generally the instruction immediately


request was detected. If a lower-level or after the point at which the interrupt
g

same-level interrupt had been


interrupt is processed. pending
le
ol

Review Questions
C

1. What are the uses of LCALL and LJUMP instructions


of 8051 ?
u

AU Dec-09
2. Explain about the instruction DJNZ.
ad

AUSjJune-09
2.9 Time Delay for 8051
iln

Many times, it is necessary to generate time


delays. For example, to generate a square
m

wave we have to generate a delay


of T/2 period so that we can make output 1 for
T/2
Ta

period and make output 0 for T/2 period."Let us see how to


calculate exact delays for
8051.

For 8051 operating frequency is one-twelfth (1/12) of the


crystal frequency. Therefore,
one machine cycle lasts for 12 oscillator periods.

Machine cycle period = 12


Crystal frequency
For crystal frequerncy 11.0592 MHz,
Machine cycle period = 12 = 1.085 us
11.0592 x 106

TECHNICAL PUBLICATIONS - an.up-thrust


for knowledge
<br>

Page 68 of 446

Embedded Systems and loT Design 2-25 Addressing Modes and Instruction Set of 8051

For 8051, we know that how much machine cycle/s are required to execute the
particular instruction. Therefore, we can calculate the exact time for execution of that
instruction, as shown below.

Instruction Machine cycle Time to execute

g
MOV R2, #40 1
1x1.085 us = 1.085 us

in
DJNZ R1, SKIP 2 2 X1.085 us = 2.17 us

er
MUL AB 4x1.085 us = 4.34 us

e
in
Example 2.9-1 Calculate the time delay produced by the following subroutine.

ng
Delay: MOV R1, #30
HERE DJNZ R1, HERE
NOP
NOP
fE
O
RET
Solution : Let us assume the crystal frequency of 8051 is 11.0592 MHz. Therefore, the
e

period of the machine cycle will be


g

12 = 1.085 usec
le

T=
11.0592x106
ol

Instruction Machine cycle


C

1
Delay :
MOV R1, #30
u

HERE :
DJNZ R1, HERE 2
ad

1
NOP
1
NOP
iln

1
RET
m

+ + + 1]x 1.085 isec = 69.44 us


Time delay = [1 + 1 1
(2x 30)
Ta

30 times.
Here, (2x 30) indicates that the instruction DJNZ R1, HERE is executed

Program Examples AU May-10, Dec12


2.10
Program 2.10.1: Program to load accumulator
A,
DPH and DPL with 30H.
MOV A, #30H ; Loads 30H in A register
MOV DPH, A : (DPH), +
(A)
MOVDPL, A :(DPL) - (A)

- an
TECHNICAL PUBLICATIONS up-thrust for knowledge
<br>

Page 69 of 446

Embedded Systems and loT Design 2-26 Addressing Modes and Instruction Set of 80s+

Program 2.10.2 Copy byte in SCON to register R3.

Method 1: Using direct address for SCON (98H)


MOVR3, 98H ;Copy SCON to R3
Method 2: Using direct address for SCON (98H) and R3 (03H)

g
MOV 03H, 98H ; Copy SCON to R3

in
Method 3: Using indirect address for R3

er
MOV R1, # 03H ; Initialize pointer to R3

e
MOV @ R1, 98H ;Copy SCON to R3

in
Method 4: Using PUSH instruction

ng
MOV81H, #02H :Set the SP to address 02H in RAM
PUSH 98H ;Push SCON (98H) to address (03H)

Progranm 2.10.3: Put the number 90H in R2 and


fE R3,

1: Use immediate addressing


O
Method mode
MOV R2, #90H
e

MOVR3, #90H
g

Method 2: Use immediate and register addressing


le

MOV R2, #90H


ol

MOV R3, R2
Program 2.10.4: Add two 8-bit numbers.
C

MOV A, #30H ; (A)J- 30


u

ADD A, #50H : (A)- (A) + 50H


ad

Program 2.10.5 : Add two 16-bit numbers.


:
MOVDPTR, #2040H (DPTR) 2040H (16-bit number)
iln

MOV A, #2BH :(A) -2BH (l0wer byte of


second 16-bit number)
MOV B, #20H ;(B) 20H (Higher byte of second 16-bit
number)
m

ADD A, DPL :Add lower bytes


Ta

MOV DPL, A ;Save result of lower byte addition


MOV A, B ;Get higher byte of second number A
in
ADDC A, DPH ;Add higher bytes with any carry from lower byte addition
MOV DPH, A ;Save result of higher byté addition

Program 2.10.6 : Find the 2's comnplement of a number in RO.

MOV A, RO -
:(A) (RO)
; 1's complement A
CPL A
ADD A, #01 ;Add 1 to it to get 2's complement

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 70 of 446

Embedded Systemns and loT Design 2-27 Addressing Modes and Instruction Set of 8051

Program 2.10.7 Unpack the packed BCD number stored in the accumulator and save
the result in RO and R1 such that (RO) LSB and (R1) MSB.
MOV B, A ;Save the packed BCD
number
ANL A, #0FH ; Mask upper nibble of BCD number
MOV RO, A ; Save the lower digit

g
MOV A, B ; Get the packed BCD number

in
ANL A, #0FOH ;Mask lower nibble of BCD
number

er
SWAP A ;Exchange the lower and upper nibbles
MOV R1,A ;Save the upper digit.

e
Program 2.10.8: Subtract two 8-bit numbers and. exchange digits.

in
MOV A, #9F ;Get the first number in A

ng
MOV RO, #40 ; Get the second number in RO
CLR C ; Clear carry
SUBB A, RO ;AA-(RO)
fE
SWAP A ;Exchange digits
O
Program 2.10.9 : Subtract the corntents of R1 of Bank0 from the contents of RO of
Bank2.
g e

MOV PSw, #10 Select Bank2


-
le

MOV A, RO ; (A) from Bank2


(RO)
MOV PSW, #00 Select Bank0
ol

CLR C Clear carry


C

SUBB A,R1 ;AA-(R1) from Banko

Program 2.10.10: Division of two 8-bit numbers.


u

ese

:
Get the first number in A
ad

MOV A,#90
MOV B,#20 ;
Get the second number in B A

;A+B, Remainder in and Ouotient in


B
iln

DIV AB
Program 2.10.11: Muutiply two &-bit numbers.
m

MOVA, #8F ;Get the first number in A


Ta

MOV B, #79 :
Get the second number in B
of result in A
MUL AB :Ax B, Higher byte of result in B and lower byte
conyert 8-bit binarynumber to iteDO
ber to its equivalent BCD.
Ogram 2.10.12 Program to
:

Program Logic :
save hundred's digit.
Step 1 : Divide number with 100 decimal and save quotient ie.
Step 2 : Make remainder as a new number.
save tens digit.
Step 3 : Divide number with 10 decimal and save quotient i.e.
Step 4 : Save remainder as ones digit.

TECHNICAL PUBLICA TIONs - an up-thrust for knowledge


<br>

Page 71 of 446

Addressing Modes and Instruction Set of 805


Embedded Systems and loT Design 2-28

: Flowchart:
Sample Example Start
Quotient Remainder
76H +100 1 12H
Get the number
12H + 10 = 1

76H = (118) 10

g
Number +100

in
Program:
;Load the binary number in A

er
MOV A, #76H
MOV B, #100 ;Load B
with 100 decimal Number+Remainder

e
;Divide number with 100 Hund digit Quotient
DIV AB

in
MOV RO „A ;Save the hundreds of the number
;(Quotient of the previous division)

ng
Number+ 10
MOVA, B ;
Get the remainder
; Load B with 10 decimal
MOV B, #10
DIV AB ;Divide number with 10
fE Ten_digit+Quotient
;Save the tens of the number |One_digit +Remainder
MOV R1, A
O
MOV R3, B ;Save the ones of the number
Stop
g e

Program 2.10.13: To add two 16-bit BCD numbers.


le

:
Flowchart :

Program
ol

Start
MOV DPTR, #1234H ;Load first number
C

MOV RO, #20H ;Load lower byte


Load the first 16-bit BCD number
;of second number
u

MOV R1, #30H ; Load higher byte


ad

;of second number Load the second 16-bit BCD number

MOV A, RO ;Get thelower


iln

;byte of second number Add two lower-digits

ADD A, DPL ;Add two lower bytes


m

DA A ;Adjust result to valid BCD Adjust result to valid BCD number


:Store the sum of lower bytes
Ta

MOV DPL, A
;Get the higher byte of second
MOVA, R1 Store lower byte of result
;
number
ADDC A, DPH
;Add two higher bytes considering
Add two higher - digits considering
: carry of lower byte addition carry of lower byte addition

DA A ;Adjust result to valid BCD


:Store the sum of higher bytes
MOV DPH, A Adjust result to valid BCD number

Store higher byte of result

Stop

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 72 of 446

Embedded Systems and loT Design 2- 29 Addressing Modes and Instruction Set of 8051

Program 2.10.14: Implementing a BCD multiply using MUL and DIV.


MULBCD: UNPACK TWO BCD DIGITS RECEIVED IN ACC, FIND THEIR
PRODUCT, AND RETURN PRODUCT IN PACKED BCD FORMAT IN ACC
MULBCD: MOV B, #10H ; DIVIDE INPUT BY 16

DIV AB ;A ANDB HOLDSEPARATED DIGITS

g
:
(EACH RIGHT JUSTIFIED IN REGISTER)

in
MUL AB ;A HOLDS PRODUCT IN BINARY FORMAT

er
(0- 99(DECIMAL)= 0-63H)
MOV B, #10 ; DIVIDE PRODUCT BY 10

e
DIV AB ;A HOLDS # OF TENS, B HOLDS REMAINDER

in
SWAP A

ng
ORL A, B ; PACK DIGITS
RET
Program 2.10.15:Subtract two 16-bit númbers.
fE
MOV DPTR, #9080 (DPTR) t 9080H (16-bit number)
--
O
MOV B, #50H (B) 50H Higher byte of second number
MOV A, #40H (A) 40H Lower byte of second number
e

CLR C Clear carry


g

SUBB A, DPL Subtract lower bytes


le

MOV DPL, A Save result of lower byte subtraction


ol

MOV A,B Get the higher byte


Subtract higher byte with borrow
C

SUBB A, DPH
MOV DPH, A Save result of higher bytes subtraction
u

Program 2.10.16: Generate BCD up conter and send each count to port
A.
ad

MOV A, #00
;
Initialize counter
BACK: MOV P1, A :Send count to port A
iln

;Increment counter
ADD A, #01
:Decimnal adjust the counter
m

DA A
AJMP BACK ;Jump BACK
Ta

a ten numbers.
Program 2.10.17: Find the maximum númber from given 8-bit
Flowchart: (See on next page)
Program: are stored
MOV DPTR, #2000
;Initialize pointer to memory where numbers
: Initialize counter
MOV R0, #0A
MOVR3, #00
; Maximum = 0

AGAIN: MOVX A, @DPTR :Get the number from memory


CJNE A, R3, NE ;Compare number with maximum number
AJMP SKIP ;If equal go to SKIP
;If not equal check for carry, if cary
go to SKIP
NE: JC SKIP

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 73 of 446

Embedded Systems and loT Design 2-30 Addressing Modes and Instruction Set of ans

MOV R3, A ;Otherwise maximum= number


SKIP : INC DPTR ;Increment memory pointer
DJNZ RO, AGAIN ;Decrement count, if count = 0 stop otherwise go to AGAIN

Start

g
in
Initialize pointer
to memory

e er
in
Initialize counter

ng
Maximum number =0 fE
O
Get the number
g e
le

Is

Number > Yes


ol

Max. number
?
C

Max. number-Number
No
u
ad

Increment memory pointer


iln
m
Ta

Decrement counter

No Is
counter =0
?

Yes

Stop

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 74 of 446

Embedded Systems and loT Design 2-31 Addressing Modes and Instruction Set of 8051

Program ghiS numbers


2.10.18: Arange the given ten 8-bit in the ascending order.
:
Program Flowchart :
MOV RO, #09 ;Initialize
:
counter1
AGAIN MOV DPTR, #2000H ;
Initialize memory
ipointer

g
MOVR1, #09 ; Initialize counter2

in
;Save lower byte of Start
BACK: MOV R2, DPL

er
memory address Initialize counter 1

MOVX A, @DPTR ;
Get the number

e
MOV B, A ;Save
the number |Initialize memory pointer

in
INC DPTR ;Increment memory

ng
ipointer Initialize cOunter 2

MOVXA, @DPTR :Get the next


;number fE Get the number
CJNE A,B,NE ;If not equal check
Increent
;for greater or memory pointer
less
O
AJMP SKIP ;Otherwise to go
Get the number
iskip
e

NE: JNC SKIP ; If


g

MOV DPL, R2 :| Exchange 1s


le

(pointer) > Yes


MOVX @DPTR, A ;
the contents (pointer + 1)
ol

INC DPTR ; of two Interchange contents of


No compared memory locations
MOV A,B
C

memory
MOVX @DPTR, A ;
locations ] Decrement counter 2
u

SKIP: DJNZ R1, BACK ;If R1 not equal to


ad

;0 go to BACK
DJNZ RO, AGAIN ; If R0 not equal to No Is
cOunter 2
=0
;0 go to AGAIN
iln

Yes
m

Decrement counter 1
Ta

No Is
counter 1=0

Yes
Stop

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 75 of 446

80s
Embedded Systems and loT Design Addressing Modes and Instruction Set of
2-32

Program 2.10.19 : Count number of one's in a number.

Program : Flowchart
:

: Initialize one's
MOV R2, #0
;Counter = 0 Start
MOV R1, #08 ; Initialize iteration

g
:Count Initialíze count = 0

in
MOV RO,#56 ;
Load number Initlalize counter = 8

:Get the number in

er
MOV A, RO
; accumulator Get the contents of

e
ROregister inthe
BACK :
RRC A ;Rotate A and
C LSB
accumulator

in
JNC SKP ;If carry is not zero go to
;skip

ng
Rotate contents of
INC R2 ;Otherwise increment accumulator so that
;one's LSB will go in carry
counter fE
SKIP: DJNZ R1, BACK ;Decrement iteration
count and if not
O
NO Is
; zero repeat carry =1
e

Yes
g
le

Increment count
ol

Decrement counter
C
u

No Is
Kcounter =0
ad

rYes
iln

Stop
m

Program 2.10.20 :To find the sum of 10 numbers stored in the arrav.
Ta

Statement: Calculate the sum of series of numbers. The length of the series is in
memory location 2200H and the series itself begins from memory location 2201H.
a. Assume the sum to be 8-bit number sO you can
ignore carries. Store the sum at
memory location 2300H.
b. Assume the sum to be 16-bit number. Store the sum at memory locations 23001
and 2301H.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 76 of 446

Embedded Systems and loT Design 2-33 Addressing Modes and Instruction Set of 8051

a. Sample problem
2200H = 04H
2201H = 20H
2202H = 15H
2203H = 13H
2204H = 22H
Result = 20 + 15 + 13 + 22 = 6AH

g
2300H = 6AH

in
Program: Flowchart :

er
a) MOV DPTR, #2200H ;Initialize memory pointer
MOVX A, @DPTR ;Get
the count

e
Start
MOV RO, #10 :Initialize

in
the iteration
; counter
Sum=0

ng
INC DPTR ;Initialize pointer to array of Pointer = 2201H
;numbers Count = (2200H)

BACK:
MOV R1, #00
MOVX A, @DPTR
; Result = 0 fE Sun = Sum + (Pointer)
:Get the number
O
ADD A, R1 ;AResult + A
MOV R1, A Pointer = Pointer +1
;Result -A. Count = Count-1
e

INC DPTR ; Increment the array pointer


g

DJNZ RO, BACK ;Decrement iteration count


le

:if not zero repeat No Is


Count 0
MOV DPTR, #2300H ;
Initialize memory pointer
ol

MOV A, R1 ;Get the result


C

; Store the result Yes


MOVX @DPTR, A
(2300H) = Sum
b. Sample problem
u

= 04H 2201H= 9AH


ad

2200H
End
2202H = 52H 2203H =89H 2204H = 3EH
9AH + 52H + 89H + 3EH = 1B3H
iln

Result
2300H B3H Lower byte 2301H = 01H Higher byte
m

Flowchart : (See on next page)


Ta

Program:
b) MOV DPTR, #2200H :Initialize memnory pointer
Get the count
:
MOVX A, @DPTR
: Initialize the iteration counter
MOV RO, #10
Initialize pointer to array of numbers
:
INC DPTR
MOV R2, #00 : [Make
MOV R1, #00 ;
result = 00H]

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 77 of 446

Embedded Systems and loT Design 2-34 Addressing Modes and Instruction Set of 80s.

:
BACK: MOVX A, @DPTR ;Get the mumber Flowchart
ADD A, R1 ;A+Result + A Start

MOV R1, A ;Result -A


; If carry exists, add it Sum high=0
ADDC R2, #00
Sum low = 0
;to MSD
Pointer = 2201H
INCDPTR ;increment the array Count = (2200H)

g
i pointer

in
DJNZ Decrement iteration,
RO, BACK Sum low= Sum low + (Pointer)
;count if not zero repeat

er
MOV DPTR, #2300H; Initialize memory
Is

e
: pointer No
Carry 1

in
;Get the lower byte of
MOV A, R1 ?
;result

ng
; Store the lower byte of Yes
MOVX @DPTR, A
+
;
result Sum high = Sum high 1

INC DPTR
;
Increment memory
fE
ipointer
Pointer = Pointer + 1
O
MOV A, R2 ;Get the higher byte of Count Count -1
;result
e

MOVX @DPTR, A ;Store the higher byte of


g

result No
Is
=
Count 0
le
ol

Yes
C

(2300H) = Sum low


(2301H) = Sum high
u
ad

End
iln

2.10.21 : Data transfer from memory block B1 to memory block B2.


Program
m

Statement :
Assume two blocks are non-overlapped.
Ta

Flowchart :
(See on next page)
:
Program ;Initialize iteration counter
MOV R2, #1
MOV R1, #20H ;Initialize source memory pointer
MOV R0, #30H
;Initialize destination memory pointer
;Get data
BACK: MOV A, @R1
; Store data
MOV @RO, A
;Increment source memory pointer
INC R1
INC RO :Increment destination memory pointer
DJNZ R2, BACK
:
Decrement iteration count and if not zero repeat

TECHNICAL PUBLICA TIONS - an up-thrust for knowledge


<br>

Page 78 of 446

Embedded Systems and loT Design 2-35 Addressing Modes and Instruction Set of 8051

Start

Initiaize cOunter = 10

Initialíze source memory pointer

g
in
Initialize destination memory pointer

e er
Get the byte from source memory block

in
ng
Store byte in the destination memory block

fE
Increment source memory pointer, increment
destination memory pointer and decrement counter
O
e

Is
No
Count =0
g

?
le

Yes
ol

End
C

55H and
2.10.22 : Write a program to load accumulator with values
u

Program
ad

complement 70 times.
; Initialize iteration count
MOV RO, #70
iln

MOV A, # 55H
;
load 55H in accumulator
HERE : CPL A Complement accumulator
m

DJNZ RO, HERE Repeat till RO = 0


Ta

program to copy the value 55H


Program 2.40.23: Write an 8051 assembiy language
addressing with a loop.
nto RAM memory locations 40H to 45H using register indirect 8
Mak
AU Dec12;

MOV RO, #06H Initialize iteration count


MOV R1, #40H Initialize memory pointer
MOV A, #55H Load data byte in A
memory location
BACK: MOV @R1, A Copy data byte into RAM
INC R1 Increment memory pointer
zero repeat
DJNZ RO, BACK i Decrement iteration count and if not

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 79 of 446

Embedded Systems and loT Design 2-36 Addressing Modes and Instruction Set of 8051

P 2.10:24 : Write an
8051 assembly language program to clear the accumulator
and add 3 to the accumulator 10 times. AU : Dec.-12, Marks 2

Solution:
CLR A Clears the accumulator (A -0)
MOV R0, #0AH :
Set the iteration count
:
BACK ADD A, #03H ;
Add 3 to accumulator

g
DJNZ RO, BACK ; Decrement iteration count and if not zero repeat

in
er
Review.Question

e
1. Write an 8051 based assembly Janguage program for perforning four basic arithmetic operations on

in
two data. AU : May-10, Marks 6

ng
fE
O
g e
le
ol
C
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 80 of 446

UNIT I

8051 /O Ports, Timers,


3 Serial Ports and Interrupts

g
in
e er
Syllabus

in
Interrupts - Timers/Counters - Serial Ports - Programming.

ng
Contents
fE
O
3.1 8051 WO Ports Structure. Dec.-08,15,16, May-14,18, Marks 16
.
Marks 2
3.2 VO Bit Manipulation Programming May-13,
e

3.3 8051 Timers May-08, Dec.-09, 11, 13, 15, Marks 16


.....
g

.
3.4 8051 Timer Modes and Programming Dec.-07,11, 15,
le

.
May-10,11,12,14,17, Marks 16
ol

3.5 8051 Counter Programming. Dec.-12, Marks 8


C

3.6 8051 Serial Port May-05, 10, 12,


Dec.-08, 09, 11, 13, 14, 17,
u
ad

June-07, Marks 16
3.7 8051 Interrupt Structure June-07, Dec.-07,12,14,16,
iln

May-11,13,14,16, Marks 16
3.8 Programming Interrupts May-11
m
Ta

(3- 1)
<br>

Page 81 of 446

Embedded Systems and loT Design 3-2 8051VO Ports, Timers, Serial Ports and Interupts

3.1 8051 VO-Ports Structure AU: De-08,15;16, May-14,18

The s051 has 32 1/0 pins configured as four eight-bit parallel ports (P0, P1, P2
and P3). Al four ports are bidirectional i.e. each pin will be configured as input or
output (or both). All port-pins are multiplexed except the pins of port 1. Each port
consists of a latch, an output driver and an input buffer.

g
Port 0 (Pins 32 - 39) : Port 0 pins can be used as I/O pins. The output drives and

in
input buffers of port 0 are used to access external memory. Port O outputs the low order

er
byte of the external memory address, time multipiexed with the data being written or

e
read. Thus, port 0 can be used as a multiplexed address/data bus.

in
Addrldata bus
Vcc

ng
Control

Read iatch
fE
PO.X
O
Pin
Intenal bus
e

POX
Latch Y Mux
g

Write to latch CL
le

Control logic
ol
C

Read pin
u

Fig. 3.1.1 Port 0 bit


Port 1 (Pins 1 8) : Port 1 pins can
ad

be used only as
I/O pins.
iln

Read latch
m

Internal
pull-up
Ta

Internal bus D
P1.X
P1.X Pin
Latch
Write to latcn CL

Read pin
Fig. 3.1.2 Port 1 bit

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 82 of 446

Embedded Systems and loT Design 3-3 8051 WO Ports, Timers, Serial Ports and Interrupts

Port 2 (Pins 21 - 28) : The output drives of port 2 are used to access external memory.
Port 2 outputs the high order byte of the external memory address when the address is
16 bits wide. Otherwise, port 2 is used as an
I/0 port.
Addr bus
Vcc
Corntrol

Read latch

g
Internal

in
pull-up

er
Internal bus Do

e
P2.X P2.X
o

in
Latch Pin
Write to latch CL

ng
MUX

Read pin
fE
Contro! iogic
O
Fig. 3.1.3 Port 2 bit
e

-
Port 3 (Pins 10 17) All port pins of port 3 are multifunctional. Therefore, each pin
:
g

of port 3 can be programmed to use as I/0 or as one of the alternate function. They
le

have special functions as shown below including two external interrupts, two counter
inputs, two special data lines and two timing control strobes.
ol

Vçc
C

Alternate
u

output
function Internal
ad

Read latch pull-up


iln

P3.X
Pin
m

Internal bus D
P3.X
Ta

Latch
CL
Write to latch

Read pin
Alternate
input
function
Fig. 3.1.4 Port 3 bit

TECHNICAL PUBLICATIONS an up-thrust for knowledge


-
<br>

Page 83 of 446

3-4 8051 VO Ports, Timers, Serial Ports and Interuot


Embedded Systems and loT Design

Symbol Position Alternate use


RD P3.7 Extermal memory read signal.

WR P3.6 External memoryYwrite signal.


External timer 1 input.
T1 P3.5

g
TO P3.4 External timer 0 input.

in
INTI P3.3 External interrupt 1 input.

er
INTO. P3.2 External interrupt 0 input.
TXD P3.1 Serial data output.

e
in
RXD P3.0 Serial data input.

ng
Table 3.1.1
Review Questions

1. Explain the I/O ports of 8051.


fE
AUDec.-08, Marks 8
O
2. Explain the port operation in 8051 microcontroller.
AUE May-14, Marks 16
3. Explain the I/O ports and their functions of 8051 microcontroller.
AU Dec.-15, Marks 16
e

4. Explain the I/0 ports of 8051 microcontroller in detail. AU:Dec.-16, Marks.16


g

5. Briefly discuss the ports of 8051, internal


circuits
le

and its functions in detail.

A: May-18, Marks 13
ol

3.2 |/O Bit Manipulation Programming


C

AU:May-13
Let us see important points for
u

programming I/O ports


:

W
oVco
ad

Port 0 has open drain outputs


and hence to use this port as an
Poo
iln

input or an output it is necessary


to connect external pull-up resistors Po.t
m

(value 10 K) as shown in the Po2


Fig. 3.2.1. Po.3
Ta

8051
Po4 Port 0
Port 1, port 2 and port 3 do not Po.5
require any pull-up resistors since Po6
they have internal pull-up resistors. Po.7.
On reset, all ports are
configured as an input ports. Fig. 3.2.1 Port 0 with
pull-up resistors
If the ports are configured as an output ports, to
make them input ports again, we
have to write FFH (1 to all 8-bits) on these ports.
Now we will see simple programming examples to clearly understand
the I/0
concepts discussed above.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 84 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Interrupts
3-5
Example 3.2.1 MWrite a program to toggle aill bits ofPO continuously.
:
Solution
BACK :
MOV A, #0AAH :

Load AAH in the (A) accumulator


MOV P0, A Send contents of A to port 0
A CALL Delay Wait for some time
MOV A, #55H

g
Load 55H in the accumulator
MOV P0, A

in
Send contents of A to port 0
A CALL Delay Wait for some time

er
SJMP BACK Repeat
The same action can be imnplemented using following program code.

e
BACK: MOV P0, A Send contents of A on port 0

in
CPL A Complement contents of port 0

ng
A CALL Delay Wait for some time
SJMP Back Repeat

Note port
Like we can toggle all bits of Pl, P2
0,
fE or P3 by replacing the
corresponding port instead of PO in the above programs.
O

Example 3.2.2 Write a program to read the content of P1 and save it in R6 and also send it
e

to P2:
g
le

:
Solution
ol

MOVA, # OFFH A+FFH


MOV P1, A Make P1 as an input port by writing all 1l's to it
C

MOV A, P1 Read data from P1


MOV R6, A Save it in R6
u

MOV P2, A Send it to P2


ad

Example 3.2.3 Write an ALP to receive input from port P1.5 and if it is high then an output
iln

35H is sent to port 0. AU:-May-13, Marks 2

Solution:
m

SETB P1.5 Configure P1.5 as an input


Ta

JNB P1.5, LAST Skip next instruction if P1.5 is low


MOV P0, #35H Send 35H on PO
LAST:

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 85 of 446

3-6 8051 VO Ports, Timers, Serial Ports and Intermupte


Embedded Systems and loT Design

Programming /O Ports using 8051C


us brief some important
Before going to see programming I/O ports using 8051C let
points about 8051c.
all the
For 8051 microcontroller we need to include' the file reg51.h. This file contains
can
definitions of 8051 registers. With this information C compiler produces hex file that
be downloaded into the ROM of the microcontroller. It is important to note that the
size

g
file
of the hex file produced by the assembly language is much smaller than the hex

in
produced by the compiler. Apart from this fact, there are many reasons for writing
C

er
programs in C instead of assembly :

e
1. It is much easier and less time consuming to write programs
inCthan assembly.

in
2. C is more flexible; it is easier to modify and update.

ng
3. Programming in allows to use code available in function libraries.
C

4. Program written in C for one microcontroller is portable to other microcontrollers


with litle or no modifications.
fE
Data Types in 8051C
O
The Table 3.2.1 lists the data types that are available in typical Cx51
compiler. The
e

Table 3.2.1 gives the information about the size of the data variable
and its value range.
g

Data type
le

Bits Bytes Value range


bit
ol

1 0 to 1
signed char 1 - 128 to +
C

127
unsigned char 8 1 0
to 255
u

enum 8/16 1
or 2 - 128 to +127 or - 32768 to +32767
ad

signed short 16 2 32768 to +32767


iln

unsigned short 16 2 0 to 65535


signed int 16 2 32768 to +32767
m

unsigned int 16
20 to 65535
Ta

signed long 32 4 2147483648 to 2147483647


nsigned long 32 4 0 to 4294967295
float 32 4 ± 1.175494E-38 to ±
3.402823E+38
sbit 1
0 to 1

sfr 8 4 0 to 255
sfr16 16 0 to 65535

Table 3.2.1 Data types

TECHNICAL PUBLICA TIONS -


an up-thrust for knowledge
<br>

Page 86 of 446

Embedded Systems and loT Design 3-7 8051 VO Ports, Timers, Serial Ports and Interrupts

Using the Appropriate Data Type


It is necessary to keep in mind that the code space for the 8051 is limited to
64 kbytes and it has limited on-chip ROM. Thus, it is necessary to look at the size of the
created hex file. One way to keep the size of data file optimum is to use appropriate
data type. The following points must be considered while selecting the data type.
The unsigned char is an 8-bit data type. Thu5, it must be used to store the value

g
in the range of 0 - 255 (00 - FFH). Since the 8051 is an 8-bit microcontroller, it is

in
one of the most widely used data type.

er
Use unsigned data type when there is no need for signed data.

e
C
compiler uses the signed data type as the default. Thus when we want to use

in
unsigned data type, we must use unsigned keyword.
.

ng
S bit data type should be used to access bit addressable registers. It allows use to
access single bits of the SFR registers.
fE
SFR data type should be used to access the byte size SFR registers.

Logical operations in 8051C


O
One of the most frequent operations required in embedded applications is monitoring
e

a single or a group of bits of a port, checking the status of a bit and controlling an
g

external device connected to a bit of an output port. allows logical operations such as
C
le

3.2.2
AND, OR, Exclusive-OR as well as shifting a byte to the left and right. The Table
ol

shown below provides the syntax for such operations.


C

Operation In assembly In C Example in C


A = -A;
u

NOT CPL A
ad

ANL A, #DATA & A = A & DATA


AND
ORL A, #DATA A = A DATA
iln

OR

EX-OR XRL A, #DATA A =A ^ DATA


m

RRA A = A >>n
Shift right by n-bits
Ta

RLA << A =A <«n


Shift left by n-bits
Table 3.2.2 Examples of logical operations in
C and assembly
Programming Examples
Example 3.24 Write an 8051 Cprogram to send binary
counter values from 00-FFH to port P1.

Solution:
#include <reg51,h>
vold main(void)

-
TECHNICAL PUBLICATIONs an up-thrust for knowledge
<br>

Page 87 of 446

Intemuets
Embedded Systems and loT Design 3-8 8051 VO Ports, Timers, Serial Ports and

unsigned char c;
for(c=0; c<=255; c++)
P1=c;

for ASCII characters of 0, 1, 2,


Example 3.2.5 Write an 8051 C program to send hex values

g
3, A, B, C, X, Y and Z.

in
Solution:
#include <reg51.h>

er
void main (void)

e
unsigned char mycharl]="0123ABCXYZ":

in
unsigned char c;
for(c=0; c<=10; c++)

ng
P1=mychar (cl:
}
fE
Comment : Program displays values 30H, 31H, 32H, 33H, 41H, 42H, 43H, 58H, 59H
and 5AH on port P1.
O
Example 3.2.6 Write an 8051 C program to toggle all the
bits of port PO and P1
continuously such that wohen PO = FFH, PO = 00 and vice-versa.
e

Solution:
g

#include <reg51.h>
le

void main(void)
ol

for(::) / repeat continuously /


C

PO=0x00 / [0X indicates data in /


u

Pl=0xFF / hex] I
ad

NOP / (wait for some /


NOP
P0=0xFF
iln

Pl=0x00
NOP / [wait for some /
m

NOP / time)/
Ta

Example3.2.7 Write an 8051 C program to send the sum -


of values 12 and 15 to port Pl.
(Use of signed numbers).
Solution:
#include <reg51.h>
void main(void)

TECHNICAL PUBLICATIONS - an up-thrust for


knowedge
<br>

Page 88 of 446

Embedded Systems and loT Design 3-9 8051 VO Ports, Timers, Serial Ports and Interrupts

signed char i, j:
i=-12;
j= 15;
P1 =i + j:

Example 3.2.8 Write an 8051 C program to toggle bit the port P1 (P1,0) 20,000 times.
0 of

g
Solution:

in
#include <reg51.h>
sbit PORTBIT = P1^0;

er
/* sbit is declared outside of main function */
void main(void)

e
unsigned int i;

in
for(i = 0; i<=20000; i+ +)

ng
{
PORTBIT = 0;
PORTBIT = 1; fE
O
Comment : P1^0 represents bit 0 of port 1.
Example 3.2.9 Write an 8051 C program to flash LEDs 10 times.
g e

:
Solution
le

#include <reg51.h>
void DELAY(void);
ol

void main(void)
{
C

unsigned char N;
N=0;
u

do
ad

{
P1=0xFF: /* Turn all LEDs ON */
/* Wait for some time */
iln

DELAY0:
P1=0x00; * Turn all LEDs OFF */
* Wait for some time */
m

DELAY(0:
N=N+1;
Ta

} while(N<10);

void DELAY(void)

unsigned char i, j:
for(i=0; i<=255; i=i+1)

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 89 of 446

Embedded Systems and loT Design 3-10 8051 VO Ports, Timers, Serial Ports and Intermupt

Start
for(j=0; j<=255; j=j+1)

N= 0

Tum LEDs ON

g
Comment Program illustrates the use of do-while loop.
:

in
Equivalent assembly language program

er
Wait
ORG O

SJMP START

e
ORG 30H

in
Turn LEDs OFF
START: MOV A,#00
MAIN:

ng
MOV P1, #0FFH
CALL DELAY
MOV P1, #00H Wait
CALL DELAY
INC A
fE
CJNE A, #10, MAIN N=N+1
O
END
e

DELAY: MOV RO, #00H


No
g

LOOP1: MOV R1, #00H Is


N> 107
le

LOOP2: INC R1
CJNE R1, #255, LOOP2
ol

INC R0 Yes
CJNE RO, #255, LOOP1
C

End
RET
Fig. 3.2.2 Flowchart
u

Exmple:3.210 Eight LEDs are connected to port P2. Write an 8051 C program
ad

that shous
the count from 0 to FFH (0000 0000 to 1111 1111 in binary) on the LEDs.
iln

Solution:
#include <reg51.h>
m

#define LED P2 /* define P2 as LED */


void main(void)
Ta

LED=0; /*clear port P2 "/


for(:) /'repeat continuously */
{

LED++; /"increment P2 *

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 90 of 446

Embedded Systems and loT Design 3-11 8051 VO Ports, Timers, Serial Ports and Interrupts

Example 3.2:11 Write an 8051 Cprogram to get a byte of


data from P1 and then send it to P2.
:
Solution
#include <rog51.h>
#define INP P1
#define OUTP P2
void main(void)

g
in
unsigned char mybyte;
INP=0xFF; /*Configure port P1 as an input port */

er
while(1)

e
mybyte = INP; /*read a byte from Pi */

in
OUTP = mybyte; /*send it to P2 */

ng
}

Example 3.242 Write an 8051 C program to read a byte of data from PO.
fE fit is less than
send it to otherwise, send it to P2.
50, Pi;
O
Solution:
#include <reg51.h>
e

void main(void)
g

{
;
unsigned char mybyte
le

P0=0xFF; /* Configure port PO as an input port */


/ read a byte from P0 */
ol

mybyte=PO;
if(mybyte<50)
C

P1=mybyte; /* send it to Pi if less than 50*/


else
u

P2=mybyte; /* send it to P2 if more than 50*/


ad

Example-3.213 Write an 8051 C program to read the content of port P1.


is greater than If it
iln

msec and
200, wait for 250 msec and send the data to port P2. otherwise wait for 150
m

Send the data to port PO,


Solution:
Ta

#inciude <reg51.h>
void Delay (unsigned int);
void main (void)

unsigned char mybyte i

P1=0XFF; /* Configure port P1 as an input port */


mybyte=P1; /* read a byte from P1 */
if(mybyte> 200)

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


<br>

Page 91 of 446

Embedded Systems and loT Design 3-12 8051 VO Ports, Timers, Serial Ports and Interrupts

{
Delay (250); /* wait for 250 msec*/
P2=mybyte; /* send byte to port P2*/

else

Delay (150); /*wait for 150 msec*/

g
PO=mybyte; / send byte to port P0*/

in
er
void Delay (unsigned int count)
{

e
unsigned int i, j:

in
for (i=0; i<count; i++)
for j=0; j<1200; j++)

ng
Example 3.2.14 Write an 8051 C
fE
program to toggle only bit PO.5 continuously.
O
Solution:
/" toggling an individual bit */
e

#include <reg51.h>
sbit portbit = P0^5;
g

/*declaration of single bit is using sbit/


void main(void)
le

{
ol

while(1)
{
C

portbit=1; /*tum on PO.5 */


portbit=0; * tum off P0.5 "/
u
ad

Example 3.215 Write an 8051


C program to monitor bit P1.5.
If it is high, send 0OH to PO;
iln

otherwise, send 00H to P2.


Solution:
m

#include <reg51.h>.
sbit portbit = P0^5;
Ta

/ declaration of single bit using sbit */


void main(void)
{

portbit=1; /* configure mybit an input


*/
if(portbit==1)
P1=0x00;
else
P2=0xFF;

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 92 of 446

Embedded Systems and loT Design


3- 13 8051 VO Ports, Timers, Serial Ports and Interrupts

Example 3.2.16 Write an 8051 C program to a given message, "My program on the
send
LCD connected to PO. Every time to latch the data into the LCD,
it is necessary to make
its enable (En) pin from high to low.
:
Solution
#include <reg51.h>
#define LCD Data PO

g
sbit En=P1^0;
vold main(void)

in
{
unsigned char message|]="My program";

er
unsigned char C;

e
for(C=0; C<10; C++) * send 10 characters */

in
{
LCD Data = mnessage [c]:

ng
En=1; /* Make En high /
En=0; /* Make En Low */
fE
Example 3.2.17 Write an 8051 C program to toggle all the bits
O
of PO and P2 continiuously
S with a some delay. Use the sfr keyword to declare the port addresses.
e

:
Solution #include <reg51.h>
g

/* Accessing ports as SFRs using the sfr data type */


le

sfr P0 = 0x80; /* declaration of PO using sfr data type /


=
sfr P2 OxA0; /* declaration of P2 using sfr data type */
ol

void Delay (unsigned int);


C

void main(void)
u

while(1) /* read it continuously "/


ad

PO=0x55;
P2=0x55;
iln

Delay(250); /* delay "/


P0=0xAA;
m

P2=0xAA;
Delay(250);
Ta

void Delay (unsigned int count)

unsigned int i, j:
for (i=0; i<count; i++)
for (j=0; j<1200; j++)

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 93 of 446

Embedded Systerms and loT Design 3-14 8051 /O Ports, Timers, Serial Ports and Interupts

Example3.2,18..Write an 8051 C program to turn bit PO.5 on and off 10,000 times.
Solution :
sbit PORTBIT = 0x85; /* another way to declare bit P0^5 */
void main(void)

unsigned int i;

g
for(i=0; i<10000; i++)

in
{
PORTBIT=1;

er
PORTBIT=0;

e
in
PO.0, complemnent it and
Example3.219. Write an 8051 C program to get the status of bit

ng
send it to P1.5 continuously.
Soiution:
#inciude <reg51.h>
sbit inbit = P0^0;
fE
sbit outbit = P1^5;
O
bit tempbit;
void main(void)
g e

while(1)
le

{
tempbit=inbit; /" read a bit from PO.0 */
ol

if(tempbit==1) /* complement the bit */


tempbit=0;
C

else
tempbit=1;
u

outbit=tempbit; /*send it to P1.5 */


ad
iln

Exanmple32.20 To illustrate some of the abo0ve operations, let us write a program that
monitors switch S0 and when pressed, it flashes the single LEDO ten times.
m

Solution:
Ta

#include <reg51.h>
void DELAY (unsigned int);
sbit S0= P0^0; * switch is connected to port 0.0 */
sbit LED = P1^0; /* LED is connected to port Pi.0 */
unsigned char c;
void main(void)

TECHNICAL PUBLICATIONS - an up-thrust for knowedge


<br>

Page 94 of 446

Embedded Systems and loT Design 3-15 8051 VO Ports, Timers, Serial Ports and Interupts

SO = 1; Conigure PO.0 an input */


do /* Check whether SO is pressed or not */

while (S0 == 0);


for (c=0; c<20; c++) /* flash LED ten times */
{

g
LED=-LED;/* invert the status of LED */

in
DELAY(1500):

e er
void DELAY (unsigned int count)

in
unsigned int i, j:

ng
for (i=0; i<count; i++)
for (j=0; j<1200; j++)
}
fE
Example 3.2.21 In a home guard system, a door sensor is connected to the P1.0 pin, window
O
sensor is connected to the P1.1 pin, and the a siren is connected to P2.0. Write an 8051 C
e

program to monitor the door and window sensor. When any one gets open, sound th
g

wave of a few hundred Hz.


siren. We can sound the siren by sending a square
le

Solution:
ol

#include <reg51.h>
void DELAY (unsigned int):
C

sbit Dsensor = P1^0;


sbit Wsensor = P1^1;
u

sbit Siren = P2^0;


ad

void main (void)


Dsensor = 1 / Configure P1.0 and P1.1 an input "/
iln

Wsensor = 1
while(Dsensor=1 Wsensor==1)
m

=~siren ;
/ invert the status of siren"/
siren
Ta

DELAY(150);

void DELAY (unsigned int count)


{
unsigned int ij:
for (i=0; i<count; i++)
for (j=0; j<1200; j++)

TECHNICAL PUBLICATIONS -an up-thrust for knowledge


<br>

Page 95 of 446

Embedded Systems and loT Design VO Ports, Timers, Serial Ports and Interrupts
3-16 8051
P2
Example 3.2.22 Write an 8051 C program to toggle all the bits
of
PO and continuously

with a some delay. Use the Ex-OR operator.


Solution:
#include <reg51.h>
vold Delay (unsigned int);
vold main (void)

g
PO=0x55:

in
P2=0x55;
while(1)

er
PO=P0^OxFF;

e
P2=P2^ OxFF;

in
Delay(250);

ng
}
void Delay(unsigned int count)

unsigned int i,j:


for (i=0; i<count; i++)
fE
for (j=0;j<1200; j++)
O
e

Example 3,2.23 Write an 8051 Cprogram to get


bit P1.0 and send it to P2.7 after inverting it.
g

Solution:
le

#include <reg51.h>
ol

sbit inbit = P0^0;


sbit outbit = P1^5; /*sbit is used to declare port (SFR) bits"/
C

bit tempbit; /"It is bit-addressable memory*/


void main(void)
u

while(1)
ad

tempbit=inbit; /*read a bit fromn P0.0


outbit=~tempbit; /*invert it and send it /to P1.5*/
iln
m

Example 3.2.24 Write an 8051 C program to


read the P1.0 and P1.1 bits and issue an
Ta

character to PO according to the status of bits ASCI


given in the following Table 3.2.3.
P1.1 P1.0 Action
send 'A' to PO
0 1
send 'B' to P0
1 send 'C to P0
1
send 'D' to PO

Table 3.2.3

TECHNICAL PUBLICATIONS - an up-thrust


for knowledge
<br>

Page 96 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Interupts
3-17
Solution:
#include <reg51.h>
void main(void)
{
unsigned char c
c=P1; read P1 */
C =c & Ox3: / mask the unused bits, i.e. ADD C with 00000011 */

g
switch(c) /* make decision */

in
case (0):

er
{
P0='A'; /* issue ASCII A "/

e
break;

in
case (1) :

ng
PO='B; /* issue ASCII B */
break; fE
case (2):
O
P0='C; /* issue ASCII C */
break;
g e

case (3):
le

{
P0='D'; /* issue ASCII D */
ol

break;
C
u

two keys '5' and '6 to


Example 3.2'25Write an 8051 C program to convert ASCII digits of
ad

packed BCD and display them on P1.


iln

Solution:
Procedure
to unpacked BCD, and then
m

To convert ASCII to packed BCD, it is first converted


on pressing keys 5 and 6 keyboard gives
combined to make packed BCD. For example,
Ta

process :

39H and 36H, respectively. Let see the conversion

Key pressed 5 6

ASCII in HEX 35H 36H

0011 0101 0011 0110


ASCII in binary
0000 1111 0000 1111
Masking pattern
0000 0101 0000 0110
Unpacked BCD
0101 0110
Packed BCD

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 97 of 446

3-18 8051 WO Ports, Timers, Serial Ports and Intermupts


Embedded Systems and loT Design

Program
#include <reg51.h>
void main(void)
unsigned char K1 = '5;
unsigned char K2 = '6;
K1 = K1 & 0x0F; /*Apply mask patterm to get unpacked BCD*/

g
K2 = K2 & Ox0F; /*Apply mask patterm to get unpacked BCD*/
upper nibble */

in
K1 = K1 >> 4; /*Shift 4 times so that lower nibble
P1 = K1 K2; /* Make packed BCD */

er
to ASCII and display
Example 3.2.26 Write an 8051 C program to convert packed BCD 0x47

e
in
the bytes on Pl and P2.
Solution:

ng
Procedure
To convert packed BCD to ASCII conversion, it is first converted to unpacked BCD,
fE
and then ORed each BCD with 30H to get ASCII bytes. For example, 0100 0111 packed
BCD can be converted to ASCII as shown in the Table 3.2.4.
O
Packed BCD 0100 0111
e

Unpacked BCD 0000 0100 0000 0111


g

ORing 30H 0011 0000 0011 0000


le

ASCII bytes 0011 0100 0011 0111


ol

Tabie 3.2.4
Program
C

#include <reg51.h>
void main(void)
u
ad

unsigned char x, y, z;
unsigned char PBCD = Ox47;
x=
iln

PBCD & 0xOF: /* mask lower 4 bits *


= x
P1 Ox30; /* make it ASCII */
y= PBCD & /* mask upper 4 bits */
m

0xF0;
y=y>> 4; /* shift it to lower 4 bits */
Ta

=
P2 yOx30; /™
make it ASCII */

Example 3.2.27. Write an 8051 C program to convert 1111 1011 (FBH) to decinal and thn
ASCI, and display the digits on PO sequentially (MSD first).
Solution :
Procedure
One way to convert binary number to decimal is to divide it by 10 successively and
keep the remainders. This is illustrated in Fig. 3.2.3. The first remainder gives the LSD
and last remainder gives the MSD. These digits are then added with 30H to get the
ASCII equivalent.

TECHNICAL PUBLICATIONS- an up-thrust for knowiadge


<br>

Page 98 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Interrupts
3-19
Assume:Hex number is 7BH

12
10) 123 A) 7BH 01
- 120 78H 02
03 03
1 1
10) 12

g
10 - A

in
+
2 2
01 304 31H

er
02 +31 32H
103 AJ 1 03 +
30H33H

e
in
41 1

ng
Fig. 3.2.3
Algorithm
1. Divide the number by 10 and save the remainder.
fE
2. Save the quotient as a number.
O
3. Repeat steps 1 and 2 until quotient is 0.
e

4. Retrieve each remainder and add 30H to convert it to ASCII.


g

Program
le

#include <reg51.h>
ol

void rmain (void)


C

unsigned char Abyte, i,0;


u

unsigned char R[3]:


ad

Abyte = 0XFB;
i=0;
iln

do
m

Q=Abyte/10; / divide by 10 */
R[i]=Abyte%10; * find remainder and save it */
Ta

save quotient as number*/ a

Abyte=Q;
i= i+1;
/* Repeat until quotient= 0 */
while(Ql= 0)
for(; i>0; i-)
{
P0=R[i-1]+0x30; Make binary to ASCII */

-
TECHNICAL PUBLICATIONs an up-thrust for knowledge
<br>

Page 99 of 446

Embedded Systems and loT Design 3-20 8051 VO Ports, Timers, Serial Ports and Interupts

:
Example 3.2:28 a) Find the checksum byte for the hexadecimal data 18H, 5AH, 46H and
69H. b) Perform the checksum to ensure data integrity. c) With an example show how
checksum detects the error.
one extra byte is stored at
Solution : To ensure the data integrity of the ROM contents,
by
the end of a series of data bytes called checksum byte. This byte is calculated
performing two operations :

g
• Add all data bytes without considering carry.

in
• Take 2's complement of the resulted sum.

er
a) Let us.find the checksum byte

e
18H + 5AH + 46H + 69H = 121H

in
Ignoring carry we have sum = 21H. Taking 2's complement
we have checksum

ng
byte = DFH.
b) To ensure data integrity all the bytes including checksum byte are added. Ignoring
fE
the carry if sum is 00H then the data integrity is ensured. Let us check this
18H + 5AH + 46H + 69H + DFH = 200H
O
Ignoring carries we have sum equal to zero and therefore, we can say that data is
valid and not corrupted.
g e

) Let us consider that the last of data is corrupted and it is now 68H instead of 69H.
le

By adding all byte with checksum byte we get,


18H + 5AH + 46H + 68H + DFH = 1FFH
ol

Ignoring carry in the sum, result is not zero and hence we can say that data is
C

corrupted.
u

Example 3:2.29 Write an 8051 C program to find the checksum byte


of data stream 30H,
ad

4AH,65H and 10OH. Convert the binary value of checksum into decimal and display
the
value of the BCD digits on ports PO, P1 and P2.
iln

Solution :
m

#include <reg51.h>
void main (void)
Ta

{
unsigned char datal|={0X30,0X4A,0X65,0X10}:
unsigned char sum=0;
unsigned char chksumbyte,i, d1, d2, d3;
for(i=0; i<4; it+)
{
sum=sum+ data[i]; * since sum is declared as byte data type,
carriesare ignored automatically */
}
chksumbyte = ~sum+1; /*Take 2's complement*/
= chksumbyte /10; /*divide by 10*/

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 100 of 446

Enbedded Systems and loTDesign 3- 21 8051 VO Ports, Timers, Serial Ports and Interupts

di = chksumbyte % 10;
/*store the remainder (LSD)"/
d2 = i % 10;
/*store middle digit*/
d3 = i/10; /*store most significant digit/
PO = d1; /* send LSD to P0*/
P1 = d2; *send middle digit to P1*/
P2 = d3; /*send MSD to p2*/

g
in
Example 3.2.30 Write an 8O51 C program to send byte 24H serially one bit at n
time via
P2.0. Send LSB first.

er
:
Solution

e
#include <reg51.h>

in
sbit outbit = P2^0;
sbit ALSB = ACC^0;

ng
void main (void)
{
unsigned char mybyte = 0X24;
fE
unsigned char i;
ACC = mybyte;
O
for (i=0; i<8; i++)
e

outbit = ALSB;
g

ACC = ACC>>1;
le
ol
C
u

Aq Ao P2.0
ad

A4 Ag Ag
Az As A
Register ACC
iln

Write an 8051 C program to send byte 24H serially one bit at a time via:
Example 3.2.31
m

P2.0. Send MSB first.


Ta

Solution:
#include <reg51.h>
sbit outbit = P2^0;
sbit AMSB = ACC^7;
void main (void)

unsigned char mybyte = 0X24;


unsigned char i;
ACC =mybyte;
for (i=0; i<8; i++)

outbit = AMSB;
TECHNICAL PUBLICATIONS- an up-thrust for
knowledge
<br>

Page 101 of 446

Embedded Systems and loT Design3- 22 8051 I/O Ports, Timers, Serial Ports and Intermupte

ACC =
ACC<<1; : t

P2.0 A7 As As A4 Ag Ag A
Ao

g
in
Register ACC
Example 3.2,32 Write an 8051 C program to receive byte serially one bit at a
time nin P2.0.

er
The first bit is LSB.

e
Solution :

in
#include < reg51.h>
sbit inbit = P2^0;

ng
sbit AMSB = ACC^7;
void main (void) fE
unsigned char i;
O
for (i=0; i<8; i++)

AMSB = inbit:
e

ACC = ACC>>1;
g
le
ol
C

P2.0 A7 A As A4 A
Ag A4 Ao
u

Register ACC
ad

Example'3.233 Write an 8051 C program to receive byte serially one bit at a time via P2.0.
The first bit is MSB.
iln

Solution:
m

#include <reg51.h>
sbit inbit = P2^0;
Ta

ntgioë
sbit ALSB = ACC^0;
void main (void)
{

unsigned char i;
for (i=0; i<8; i+ +)
{
ALSB = inbit;
ACC = ACC<<1;

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 102 of 446

Embedded Systems and loT Design


3-23 8051 VO Ports, Timers, Serial Ports and Interrupts

A A6
A A4 Ag Az A
Ao P2.0

Register ACC

g
Example Write an 3051 C program to perform data integrity check for data given
3.2.34
in

in
example. f data is not corrupted, send ASCIl character "V (valid) on port
P1; otherwis

er
send C (corrupted) on port P1.
:
Solution

e
#include <reg51.h>

in
void main (void)

ng
{
unsigned char data[] ={0X18,0X5A,0X46,0X69,0XDF}:
unsigned char chksum=0; fE
unsigned char i;
for(i=0; i<5; i++)
O
chksum=chksum+data[il:
e

}
g

if(chksum==0)
le

P1=V;
else
ol

P1='C;
C

Example 3.2.35 Write an 8051


program to toggle all the bits of P1, P2 and
C
PO
u

continuously with a 250 ms delay. Use SFR keyword to declare the port addresses.
ad

Solution:
#include reg51.h>
iln

void Delay (void);


void main (void)
m

{ while
(1)/* Repeat continuously */
Ta

toggle all bits of PO */


PO=0 x 55; /*
p1=0 x 55; /* toggle all bits of P1 */
toggle all bits of P2 */
P2=0 x 55; /*
Delay (250); /* wait for 250 ms */
/* toggle all bits of PO */
P0=0× AA; */
P1=0× AA; * toggle all bits of P1 */
P2=0 x AA; /* toggle all bits of P2
Delay (250) /* wait for 250 ms */

-
TECHNICAL PUBLICA TIONS an up-thrust for knowledge
<br>

Page 103 of 446

Embedded Systems and loT Design 3-24 8051 VO Ports, Timers, Serial Ports and Intemupts

void Delay (unsigned int count)


{
unsigned int i,j:
for (i=0; i < count ; i++)
for (j=0;j< 1275; jt+);
}

g
with
PO and P2 continuously
Example 3.2.36 Write a C-program to toggle all bits of

in
250 msec delay. Use inverting operator.

er
:
Solution
#include<reg51.h>

e
void MSDelay (unsigned int);

in
void main (void)

ng
PO = Ox55;
P2 = Ox55;
while (1) fE
PO = ~P0;
O
P2 = ~P2;
MSDelay (250);
e

}
g

}
le

void MSDelay (unsigned int count)


{
ol

unsigned int i, j:
for (i = 0; i < count; i++)
C

for (j = 0; j < 1275; j++)


}
u

Example 3.2.37 Write a 8051 C-program to convert a gioen hex-data OFF


ad

into its equivalent


decimal data and display the result digits on PO, P1 and P2.
iln

:
Solution
#include<reg51.h>
m

void main(void)
Ta

unsigned char x, binbyte, d1, d2, d3;


binbyte= 0xFF;
x=binbyte/10;
d1=binbyte% 10;
d2 = x%10;
d3 = x/10;
PO=d1;
P1=d2;
P2=d3;

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 104 of 446

Embedded Systems and loT Design


3-25 8051 WO Ports, Timers, Serial Ports and Interupts

3.3 8051 Timers


AU : May-08, Dec.-09, 11, 13, 15
s051 has two timers, timner 0 and timer 1.
Basically both, timer 0 and timer 1 are
16-bit registers. Since 8051 is an 8-bit microcontroller,
as low-byte register(TL)
each 16-bit register can be accessed
and high-byte register(TH). Fig. 3.3.1 shows the timer 0 and
timer 1 registers. These registers can be accessed like other registers (A, B, RO, R1
etc.) in
8051.

g
Timer 1 register

in
Timer 0 register

er
TH1 TL1 THO TLO
(8 - bit) (8 - bit)

e
(8-bit) (8 - bit)

in
ng
Timer control (TCON) register
fE
Timer mode (TMOD) register
O
Fig. 3.3.1 Timer registers
e

3.3'1 Structure of TMOD Register


g
le

Timer/counter mode control (TMOD) is the special function register in 8051 having
format as shown in Fig. 3.3.2.
ol

(MSB) (LSB)
C

GATE CT M1 MO GATE cT M1 MO
u

Timer 0
ad

1
Timer
Fig. 3.3.2 TMOD register
The TMOD register is responsible for configuring the timers for the following
iln

operations :
Select Timer 0 to operate as a counter or timer
m

Select Timer 1 to operate as a counter or timer


Ta

Select the mode in which timer should operate.


M1,MO: These bits select the timer mode. There are four different modes of timer,
mode 0, mode 1, mode 2 and mode 3. All these modes are discussed in the further
section.

M1 MO Operating mode
0 &-bit Timer/Counter "THx" with "TLX"'s 5-bit prescaler.
no prescaler.
16-bit Timer/Counter "THX" with "TLx" are cascaded; there is
0

TECHNICAL PUBLICATIONS-an up-thrust for knowledge


<br>

Page 105 of 446

Embedded Systems and loT Design 3-26 8051 VO Ports, Timers, Serial Ports and Intemupts

8-bit auto-reload Timer/Counter "THX" holds value which is to be reloaded


1
a
into "TLx' each time it overflows.
o
(Timer 0) TLO is an 8-bit Timer/Counter controlled by the1 standard Timer
bits.
control bits. THO is an 8-bit timer only controlled by Tmer control
(Timer 1) Timer/Counter 1 stopped.

g
is cleared (C/T = 0) for selecting 'timer' operation and is set (C/T= 1)
C/T: This bit

in
for selecting 'counter operation.

er
"INTX" pin
GATE:Gating control when set. Timer/Counter "x" is enabled only while
"TRX"
is high and "TRx" control bit is set. When cleared Timer "x" is enabled whenever

e
in
control bit is set.

ng
3.3.2 Structure of TCON Register
fE
The Fig. 3.3.3 shows the format for the TCON register of 8051.
(MSB) (LSB)
O
TF1 TR1 TFO TRO IE1 IT1 IEO ITO
g e
le

Symbol Position Name and significance


ol

IF1 TCON.7 Timer 1 Overflow Flag. Set by hardware on timer/counter overflow. Cleared when
interrupt processed.
C

TR1 TCON.6 Timer 1 Run control bit. Set/cleared by software to turn tmer/counter on/off.
u

TFO TCON.5 Timer 0 Overflow Flag. Set by hardware on timr/counter overflow. Cleared when
ad

interrupt processed.
TRO TCON.4 Timer 0 Run control bit. Set/cleared by software to turn timer/counter on/off.
iln

IE1 TCON.3 Interrupt 1 Edge Flag. Set by hardware when external interrupt edge detected.
wen nterrupt processed.
m

Cleared when

IT1 TCON.2 Interrupt 1Type control bit. Set/cleared by software to specify falling edge/low
Ta

level. triggered external interrupts.

IEO TCON.1 Interrupt 0 Edge Flag Set by hardware when external interrupt edge detected.
Cleared when interrupt processed.

IO TCON.0 Interrupt 0 Type, control bit. Set/cleared by software to specify faling edge/low
level triggered external interrupts.

Fig. 3.3.3 TCON-timerlcounter


control/status register
The TCON register controls the following timer operations :
Start and stop timer 0 and timer 1
Provides status of timer/counter overflows

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 106 of 446

Embedded Systemns and loT Design


3-27 8051 VO Ports, Timers, Serial Ports and interrupts

Provides status of external interrupts


Configures external interrupts as either low level triggered or
falling edge
triggered.
Example3.3.1 Indicate the effect of following 8051 instructions.
a. MOV TMOD, #00010000B b. c.
MOV TMOD, #00000001B MOV TMOD, #04

g
Solution:

in
a. MOV TMOD, #00010000B :
The effect of this instruction is to set Timer 1 in
mode 1 and Gate = 0 for internal clocking.

er
b. MOV TMOD, #00000001B: The effect of this instruction is to set Timer 0 in mode

e
1
and Gate = 0 for internal clocking.

in
c. MOV TMOD, #04 : The effect of this instruction is to select timer 0 to run in the
counter mode.

ng
Example 3.3.2 Perform the following operations using bit addressable instructions
a., Start Timer 1
b.
fE
Stop Timer 0
Solution :
a) SETB TR1 ; starts timer 1 by setting TCON.6 = 1
O
b) CLR TRO ; stops timer 0 by clearing TCON.4 = 0
e

Review. Questions
g
le

1. Explain the timerlcounter functional unit of microcontroller 8051 with relevant dingrams.
ol

EAUMay-08, Marks 16
C

2. Discuss in detail the on chip timers supported by 8051, bringing out the various modes of
operation of these timers. AUF Deéc.-09, Marks i16
u

3. Draw the TMOD register format and explain. AU Det 11, Marks 4
ad

4. Discuss about the timers in 8051 tvith suitable examples. AU Dec13, Marks 16
iln

34 8051 Timer Modes and Programming


FAU Dc-07,11,15, May-10,il,12,14,17
m

3. All these
There are four modes of timer, mode 0, mode 1, mode 2 and mode
Ta

modes and their programming are discussed in this section. Mode


1
and mode 2 are
Widely used, so wwe will discuss them in detail.
a divide-by-32 prescaler. This
Mode 0 : Both Timers in Mode 0 are 8-bit Counters with
as it applies to
13-bit timer is MCS-48 compatible. Fig. 3.4.1 shows the Mode 0 operation
as a 13-bit register. As the count
1mer 1. In this mode, the Timer register is configured
TF1. The counted input is
Ous over from all 1s to all Os, it sets the Timer interrupt flag
= 1 and either GATE = 0 or INT1 = 1. (Setting
enabled to the Timer when TR1
input INT1, to facilitate pulse
AIE= 1 allows the Timer toa be controlled by external GATE
dtn measurements.) TR1 is control bit in the Special Function Register TCON
is in TMOD.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 107 of 446

Embedded Systems and loT Design 3-28 8051 I/O Ports, Timers, Serial Ports and Interupts

OSC +12

TL1 TH1
(5 Bits) (8 Bits)
TE 1 + Interrupt
ciT=1

g
T1 PIN.

in
TR1

er
Control
GATE

e
in
INT1 PIN

ng
Timer/ counter control logic

Fig. 3.4.1 Timerlcounter 1 fE


mode 0 :
13-bit counter

The 13-bit register consists of all 8 bits of TH1 and the lower 5 bits of TL1. The upper
O
3 bits of TLI are indeterminate and should be ignored. Setting the run flag (TR1) does
not clear the registers.
e

Mode 0 operation is the same for Timer0as for Timer 1. Substitute TRO, TFO and
g

INTO for the corresponding Timer 1 signals in Fig. 3.4.1. There are two different GATE
le

bits, one for Timer 1 (TMOD.7) and one for Timer 0 (TMOD.3).
ol

Mode 1: Both Timers in Mode 1 are 16-bit Counters As the count rolls over
from all 1s
C

to all Os, it sets the Timer interrupt flag TF. The counted input is enabled
to the Timer
when TR = 1 and either GATE = 0 or INT1 = 1. (Setting GATE = 1 allows the Timer to
u

be controlled by external input INT1, to facilitate pulse width measurements.)


ad

Timer 0 Mode 1 Programming :


The Fig. 3.4.2 shows the timer control logic for timer 0
iln

in mode 1.
m

THO TLO
Ta

OSC +12 (8 Bits) (8 Bits) TFO Interrupt


cIT=0

TRO
GATE(TMOD.3) Control

INTO PIN

Timer0 control logic


1
Fig. 3.4.2 Timer 0 in mode

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 108 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Intemupts
3- 29
A time delay can be generated using mode 1
of the timer 0 using following steps :

1. Load TMD register indicating timer 0 is used and mode 1 is selected.


7 6 5 4 3 2 1

TMOD X 0 1 = 01

g
2. Load TLO and THO registers with count values.

in
3. Start the timer by setting TRO bit = 1.

er
4. Monitor the timer flag (TFO) with the JNB TFO, target address instruction. When it

e
is raised, get out of the loop.

in
5. Stop the timer by clearing TRO bit = 0 with CLR TRO instruction.

ng
6. Clear TFO flag with CLR TFO instruction.
When start and stop of timer is done using software, no external hardware is needed
fE
for the same. This is illustrated in the Fig. 3.4.3.
O
e

OSC +12 THO TLO


crT=0 (8 Bits) (8 Bits) TFO Interrupt
g
le

TRO
ol

Timer0 control logic when GATE = 0 and INTO =1


C

Fig. 3.4.3 Timer 0 in mode 1, no external hardware is used to start and stop timer
u

:
Timer 1 Mode 1
Programming The Fig. 3.4.4 shows the timer control logic for timer 1
ad

in mode 1.
iln

TH1 TL1
m

OSC +12 (8 Bits) (8 Bits) TF1 Interrupt


cT=0
Ta

TR1
GATE(TMOD.7) Control

INTT PIN

Timer1 control logic


1 in mode 1
Fig. 3.4.4 Timer

TECHNICAL PUBLICATIONs an up-thrust for knowledge


-
<br>

Page 109 of 446

Embedded Systems and loT Design 3-30 8051 VO Ports, Timers, Seial Ports and Intemupts

steps:
A time delay can be generated using mode of the timer using following
1 1

1 is selected.
1. Load TMOD register indicating timer 1 is used and mode
1
7 6. 5 2
= 10H
TMOD 0 1Xx X X

g
2. Load TL1 and TH1 registers with count values.

in
3. Start the timer by setting TRI bit = 1.

er
4. Monitor the timer flag (TF1) with the JNB TF, target address instruction. When it

e
is raised, get out of the loop.

in
5. Stop the timer by clearing TRI bit = 0 with CLR TR1 instruction.

ng
6. Clear TF1 flag with CLR TF1 instruction.
When start and stop of timer is done using software, no external hardware is needed
fE
for the same. It is illustrated in the Fig. 3.4.5.
O

OSC +12
e

TH1 TL1
C/T=0 (8 Bits) (8 Bits) TF1 + Interrupt
g
le

TR1
ol

=0 and INT1 =1
Timer1 control logic when GATE
C

Fig. 3.4.5 Timer 1 in mode 1, no external hardware is used to start and stop timer
Mode 2 : Mode 2 configures the Timer register as an 8-bit Counter (TL) with automatic
u

reload, as shown in Fig 3.4.6. Overflow from TL only sets TE, but als0 reloads TL with
ad

the contents of TH, which is preset by software. The reload leaves TH unchanged.
iln

Timer 0 Mode 2 Programming :


The Fig. 3.4.6 shows the timer control logic for timerU
2.
in mode
m
Ta

TLO
OSC +12 TFO Interrupt
(8 Bits)
cT=0

TRO
GATE(TMOD.3) THO
Control.
(8 Bits)
INTO PIN

Timer0 control logic


Fig. 3.4.6 Timer 0 in mode 2

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 110 of 446

Ernbedded Systems and loT Design 3- 31 8051 I/O Ports, Timers, Serial Ports and Interrupts

A time delay can be generated using mode 2 of the timer 0 using following steps :

1. Load TMOD register indicating timer0 is used and mode 2 is selected.


7 6 5 3 2
= 02H
TMOD X 00
2. Load THO register with count value.

g
3. Start the timer by setting TRO bit = 1.

in
4. Monitor the timer flag (TFO) with the JNB TFO, target address instruction. When it

er
is raised, get out of the loop.

e
5. Clear the TFO flag, with CLR TFO instruction.

in
6. Go back to step 4. There is no need to load THO register again since Mode 2 is

ng
auto-reload.
When start and stop of timer is done using software, no external hardware is needed
fE
for the same. It is illustrated in the Fig. 3.4.7.
O

OSC +12 TLO Interrupt


e

(8 Bits) TFO
CIT=0
g
le

TRO
ol

INTO =1
Timer0 control logic when GATE =0 and THO
C

(8 Bits)

external hardware is used to start and stop timer


u

Fig. 3.4.7 Timer 0 in mode 2, no


ad

1
Timer 1 Mode 2 Programming
:
The Fig, 3.4.8 shows the timer control logic for timer
iln

in mode 2.
m

TL1
+12
(8 Bits)
TF1 + Interrupt
OSC
Ta

CT-0

TR1 TH1
GATE(TMOD.7) Control (8 Bits)

PIN
INTT

Timer1 control logic


Fig. 3.4.8 Timer
1 in' mode 2

TECHNICAL PUBLICATIONS- an up-thrust for knowiedge


<br>

Page 11I of 446

Embedded Systems and loT Design 3-32 8051 /O Ports, Timers, Serial Ports and Intemupte

A time delay can be generated using mode 2 of the timer 1 using following steps:
1. Load TMOD register indicating timer 1 is used and mode 2 is selected.

6 5 4 3 2 1 0
TMOD 1 0 X X =20H

g
TH1register with count value.

in
2. Load

the timer by setting TR1 bit = 1.

er
3. Start
4. Monitor the timer flag (TF1) with the JNB TF1, target address instruction. When it

e
is raised, get out of the loop.

in
5. Clear the TF1 flag, with CLR TF1 instruction.

ng
6. Go back to step 4. There is no need to load TH1 register again since Mode 2 is
auto-reload. fE
When start and stop of timer is done using software, no external hardware is needed
for the same. It is illustrated in the Fig. 3.4.9.
O
g e

OSC
le

+12 TL1
CT=0 (8 Bits) TF1 Interrupt
ol
C

TR1
Timer1 control logic when GATE = 0 and INT1 =1
u

TH1
(8 Bits)
ad

Fig. 3.4.9 Timer 1 in mode 2, no external hardware is used to start and stop timer
iln

Mode 3:
Timer 1 in Mode 3 simply holds its count. The effect is the same as settirg
m

TR1 = 0. Timer 0 in Mode 3 establishes TLO


and THO as two separate counters. n
Ta

logic for Mode 3 on Timer is shown in Fig. 3.4.10. TLO uses the Timer 0 control bits
C/T, GATE, TRO, INTO, and TFO. THO is locked into a timer mode (counting
machs
cycles) and takes over the use of TRI and TF1 from Timer 1.
Thus, THO now contro®
the : Timer 1 interrupt.

TECHNICAL PUBLICATIONS - an
up-thrust for krnowledge
<br>

of 446
Page 112

Embedded Systems and loT Design 3-33 8051 WO Ports. Timers, Seral Ports and Interupts

OSC +12 1/12fosc

CT=0 TLO
TFO Interrupt
CT=1 (8 Bits)
TO PIN

g
in
TRO

er
GATE Control.

e
INTO PIN

in
THO Interrupt
TF 1

ng
1/12f osC (8 Bits)

Control
TR1
fE
Fig. 3.4.10 Timerlcounter 0 mode 3: Two 8-bit counters
O
The Table 3.4.1 summarizes the modes of timers.
e

Brief description
g

Mode
le

Mode O 13-bit timer (TL-5-bits and TH-8-bits).


flag.
Counter overflow is indicated by time interrupt
ol

Mode 1 16-bit timer (TL-8-bits and TH-8-bits)


C

Rest is same as mode 0.


(TL-8-bit) overflow from
Automatic reload mode. 8-bit counter
u

Mode 2 also reloads TL with the contents of TH.


TL not only sets 1I but
ad

seperate conters.
Mode 3 Establishes TL and TH as two
mnodes
iln

Table 3.4.1 Summary of timer


m

Review Questions
Ta

operation of timers in 8051.


1. Describe the different modes of Marks 16
AU Dec.-07,11, May-10;11,14,17,
diagrams.
Timers 8051 miçrocontroller twith appropriate
2. Explain the of AU Dec-15, Marks 16

AU':Dec.-12
S.5 8051 Counter Programming TL registers are
as a counter, the TMOD, TH and
When the timer/counter is used
same as for the timer studied in the last section.
tSed, functioning the
PUBLICATIONs an up-thrust for knowledge
TECHNICAL
<br>

Page 113 of 446

Embedded Systems and loT Design 3-34 8051 VO Ports, Timers, Serial Ports and Interrupts

cT Bit in TMOD Register : As seen earlier, the C/T bit in the TMOD register decides
the timer/counter functioning as a counter or a timer. When C/T bit in the TMOD
register is 0, the timer mode is selected. When timer/counter is used as a timer, the
s051's crystal is used as a source of the frequency. When C/T bit in the TMOD register
is 1, the counter mode is selected. When timer/counter is used as a counter, it gets its
pulses from outside the 8051. The pin P 3.4 (pin number 14) and pin 3.5 (pin number
15) of 8051 are used for applying pulses counter 0 and counter 1 respectively. These two

g
pins belong to port 3. The counter counts up for each clock pulse applied at this pin.

in
These pins are called To (timer 0 clock input) and T1(timer 1 clock input).

er
Counter 0 in Mode 1 : The Fig. 3.5.1 (a) shows the block diagram of counter 0 in

e
mode 1 and the Fig, 3.5.1 (6) shows the block diagram of counter 0 in mode 1 when

in
GATE = 0 and INTO = 1. Here, counter 0 counts up when the logic signal on
pin T0
goes from high level to low level.

ng
TO(P3.4)
fE THO TLO
(8 Bits) (8 Bits) TFO Interrupt
cIT=1
O
e

TRO
g

GATE(TMOD.3) Control
le

INTO PIN
ol

Counter0 control logic


C

Fig. 3.5.1 (a)


u
ad

TO(P3.4)
iln

THO TLO
c/T=1 (8 Bits) (8 Bits) TFO Interrupt
m
Ta

TRO

Counter 0 control logic when GATE = 0 and INTO =1

Fig. 3.5.1 (b)

To operate counter 0 in mode we have to perform following steps :


1

1. C/T bit in TMOD register (Bit 2) is set to 1 to allow counter


mode operation.
2. M1 : MO bits (bits 1 :
0) in TMOD register are set to 01 to select
mode 1.
3. When Gate bit (Bit 3) in TMOD register is cleared to
0, TRO bit (bit 4 of TCON) is
set to 1 to start the counter.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 114 of 446

Embedded Systems and loT Design


3-35 8051 WO Ports, Timers, Serial Ports and Interupts

A When Gate bit (Bit 3) in TMOD register is set to 1, counter will run
set to 1
only if TRO is
and the logic signal on external interrupt pin INTO is
high.
7 6 5 4 3 2 1 0
TMOD X X 1 0 =05H

g
7 5 4 1

in
TCON 0 1
0 0=10H

er
Fig. 3.5.2 Counter 0 control register settings for mode 1
operation

e
Counter 1
in Mode 1: The Fig. 3.5.3 (a) shows the block diagram of counter 1 in

in
mode 1 and the Fig. 3.5.3 (b) shows the block diagram of counter 1 in mode 1 when
GATE = 0 and INTO = 1.

ng
T1(P3.5) -
fE TH1
(8 Bits)
TL1
(8 Bits)
TF1 Interrupt
cIT=1
O
e

TR1
g

GATE(TMOD.7)
le

INT1 PIN
ol

Counter1 control logic


C

Fig. 3.5.3 (a)


u
ad

TH1 TL1
T1(P3.5) TE1 Interrupt
cIT=1 (8 Bits) (8 Bits)
iln
m

TR1

=0 and INT1 =1
Ta

Counter1 control logic when GATE


Fig. 3.5.3 (b)
4 3 2 1 0
7 6 5
1 X X X = 50H
TMOD0 0

2 1
5 4 3
7 6
0 = 40H
TCON 1 0
1 operation
Fig. 3.5.3 (c) Counter 1 control register settings for mode

TECHNICAL PUBLICATIONS an up-thrust for knowledge


-
<br>

Page 115 of 446

Embedded Systems and loT Design 3-36 8051 V/O Ports, Timers, Serial Ports and Interrupts

The operation of counter 1 in mode 1 is same as counter 0 operation. The only


difference is that here registers for counter 1 are programmed instead of counter 0.

Counter in Mode 2: In this mode, counter is used in auto-reload mode instead of


16-bit counter. Rest of the operation is exactly same as that of Mode 1. The Fig. 3.5.4 (a)
shows the block diagram of counter 0 in Mode 2 and the Fig. 3.5.4 (b) shows the block
diagram of counter 0 in Mode 2 when GATE = 0 and INTO = 1

g
in
er
TO(P3.4) TLO
TFO Interrupt
(8 Bits)

e
CIT=0

in
ng
TRO
GATE(TMOD.3) THO
Control
hss INTO PIN
fE (8 Bits)
O
Counter0 control logic
Fig. 3.5.4 (a)
g e
le

TO(P3.4)
TLO
CIT=0E
ol

(8 Bits) TFO Interrupt


C

TRO
u

Counter0 control logic when GATE=0 and INTO =1


ad

THO
(8 Bits)
iln

Fig. 3.5.4 (b)


Example 35.1 Write a program for counter 1
in mode 2 to count the pulses and display
m

the
stäte of TL1 count on port 2. Assume that clock
input is connected to T1 pin (P 3.5).
Ta

AU Dec.-12,-Marks 8
:
Solution
MOV TMOD, #01100000B Initialize counter 1 in Mode 2,
MOV TH1, #0 C/T=1
Clear TH1
SETB P3.5 Make T1 input
START: SETB TR1 Start the counter
BACK: MOV A, TL1 Get the count from TL1
MOV P2, A Sent it to port 2
JNB TF1, BACK If TF1 = 0repeat

TECHNICAL PUBLICATIONS- an
up-thrust for knowledge
<br>

Page 116 of 446

Embedded Systems and loTDesign


3-37 8051 VO Ports. Timers, Serial Ports and Interrupts

CLR TR1 ;
Otherwise stop counter 1
CLR TF1 ;
Make TE1=0
SJMP START :
Repeat
Note When 8051 is powered up ports are configured as input ports. To make them
work as output port we have to send high output on it. Therefore, to
behave T1 as
input P 3.5 is set.

g
in
Example 3.5.2 Write a program to display counter 0 on 7-segment LEDs.Assume that clock

er
input is connected to pin (P 3.4).

e
:
Solution

in
MOV TMOD, #00000110 Initialize counter 0 in Mode 2, c/T=1

ng
MOV THO, #00H Reset counter value
SETB P3.4 Make T0 as input
START:
BACK:
SETB TRO
MOV A, TLO
fE
Start counter 0
Get the count value
ACALL CONVBCD
O
MOV P2, A Send count value in BCD on port 2
JNB TFO, BACK If TFO = 0 repeat
e

CLR TRO Otherwise stop counter 0


g

CLR TFO Make TF0=0


le

SJMP START Repeat


:
CONVBCD ADD A, #00H (Use DAA for
ol

DA A BCD conversion]
C

RET Return to main program


Example 3.5.3 Assume that XTAL = 11.0592 MHz. Write a program to generate a square
u

wave of 2 kHz frequency on pin P1.5.


ad

Solution:T=1/f 1/2 kHz = 500 us is period of square wave. 1/2 of it= for high and
=
-
iln

=
low portion of the pulse is 250 us. 250 us/1.085 us 230 and 65536 230 65306 which
in hex is FF1AH.
m

=
TL = 1AH and TH FFH
Ta

Program is as follows
MOV TMOD, #10H timer 1, mode 1
AGAIN : ; low byte of timer
MOV TL1, #1AH
MOV TH1, #0FFH i high byte of timer

SETB TR1 Start timer 1


BACK: ; Stay until timer rolls over
JNB TF1, BACK
iStop timer 1
CLR TR1
Complement P1.5
CPL P1.5
Clear timer flag
CLR TF1
SJMP AGAIN
; reload timer

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 117 of 446

3-38 8051 VO Ports, Timers, Serial Ports and Interrupts


Embedded Systems and loT Design
1 in mnode 1, on Pin
Example. 3.5.4 Generate a sqtuare wave of frequency 1 kHz using timer
the
P1.2. Explain the TMOD word used to configure the timer for this application. Show
1

necessary calculations to find the value of count to be loaded into TH1 and TL1 registers.
Assume XTAL frequency = 11.0592 MHz.

Solution :

g
T of square wave = 1/f = 1/2 kHz = 500 us

in
500 us =
ToN = TOFF = 250 us

er
2
12
T of clock = = 1.085 us

e
11.0592 x 106

in
TON 250 us =
Count =

ng
230
T of clock 1.085 us

Count to be loaded in THI and TL1 = 65536


fE – 230 = 65306 = FF1AH

THI = FF and TL1 = 1AH


O
Program
MOV TMOD, #10H ;Timer 1, mode 1 (16-bit)
e

AGAIN: MOV TL1, #1AH ;Load lower byte of timer


g

MOV TH1, #0FFH ;Load higher byte timer of


le

SETB TR1 ;Start


timer 1
ol

:Wait for
BACK: JNB TF1, BACK timer rolls over
CLR TR1 :Stop timer 1
C

CPL P12 ;Complement P1.2


;
CLR TF1
u

Clear timer flag1


SJMP AGAIN ; Reload timer 1 and continue
ad

Example 3.5:5 Explain the steps to program timers in model and write an 8051 program to
iln

generate a square wnve of 50 % duty cycle on the pin P1.5.


wave
m

Solution: Square
MOV TMOD, #01 ;Timer 0 mode 1
Ta

Here: MOVTLO, #OF2H ;


Load TLO - OF2
MOVTHO, #0FFH A:Load THO - OFF
CPL P1.5 ; toggle input on P1.5
ACALL Delay
SJMP Here
Delay :
SETB TRO :Start Timer 0
again :
JNB TF0, again ;Monitor Timer 0 flag until
it rolls over
CLR TRO
CLR TFO
RET

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 118 of 446

Embedded Systems and loTDesign


3- 39 8051 I/O Ports, Timers, Serial Ports and Interrupts

Example 3.5.6 Write an ALP to generate square wave on pin Hz (approximately)


P1.5 of 500
with a subroutine to provide a time delay of 30.38 us
using timer O. Assume that crystal
frequency of 8051 is 11.0592 Hz.

Solution:
12
T = 12 = 1.085 us
Crystal frequency

g
11.0592x 106

in
30.38 us
Number of counts for roll over = = 28
1.085 us

er
65536 - 28 = 65508 = FFE4H

e
: To get a delay of 30.38 we have to load THO = FFH and TLO =

in
E4AH.

ng
1
For square wave T = = 2 mns
500
TON = TOFF = T/2 = 1 ms fE
Thus we have call delay routine (1 ms/30.38 us) = 33 = 21H times
O
Program
e

MOVTMOD, #01 ;TimerO, mode1


g

HERE: MOV TLO, #E4H ;Load TLO = E4H


le

MOVTHO, #FFH :
Load THO = FFH
;toggle P1.5
ol

CPL P1.5
MOV RO, #21H ;Load count in RO
C

wait for 30.38 us x 33


=

BACK :
ACALL Delay
; 1ms
DJNZ RO, BACK
u

SJMP HERE
ad

DELAY :
SETB TRO ; start tmer 0

AGAIN: JNB TF0,AGAIN Wait for TFO to roll over


:
iln

CLR TRO istop timer 0


;Clear TFO
m

CLR TEFO
; Return
RET
Ta

Example 3.5.7 Find the delay generated by timer 0 in the


following code. Calculate the delay
What count has to be loaded in TLO and
generated excluding the instruction overhend.
msec ?
1H0 if delay has to be increased to 25
CLR P2.3
HERE MOV TMOD, #01
MOV TLO, #3Eh
MOV THO, #0B8h
SETB TEO

TECHNICAL PUBLICATIONs
- an up-thrust for knowledge
<br>

Page 119 of 446

Embedded Systems and loT Design 3-40 8051 VO Ports, Timers, Serial Ports and Interrupts

AGAIN: JNB TFO, AGAIN


CLR TFO
CLR TRO
CLR P2.3

Solution:

g
Timer count = B83E
.

in
(FFFF- B83E + 1) = 47C2H = (18370) 10

er
Assuming XTAL = 11.0592 MHz

e
12
T = = 1.085x 10-6

in
11.0592>x 106

ng
Delay = 1.085x 10- x 18370 = 19.93 ms
For 25 msec delay fE
Decimal count = 25 ms = 23041
O
1.085x 10-6
= 5A01 H
g e

:. TLO, = 01H and THO = 5AH


le

Example 3.5.8 Find out Hex. number to be loaded


in THO, to produce delay of 4.096 msec in
ol

mode 0' operation. Assume clock frequency


of 12 MHz.
C

Solution : Timer clock frequency = Crystal frequency + 12 = 12 MHz + 12


u

1 MHz
ad

Timer clock period = 1 us


Maximum count in mode 0 is 1FFFH (8191) and we have to count
for 4096 counts to
iln

get a delay of 4.096 ms


..
m

Count to be loaded in timer is 1FFFH


(8191 in decimal) – 4096 = FFFH (4095 in decimal)
Ta

Therefore, we have to load OFH in THO and FFH in TLO.


Example 3.5.9 Using autoreload mode
of timer 0 in 8051, generate a frequency of 10 kHz on
pin P1.0. Write assembly language program
for it.
Solution : Assume XTAL frequency = 12 MHz. To generate a
frequency of 10 kHz, one
half of the cycle is of period 0.05 ms. Since XTAL frequency = 12
MHz we have cyde
period is lus. Therefore, we have to decrement count equal to 50.
to be loaded in THO = (256 – 50) = 206. Thus the initial value

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 120 of 446

Embedded Systemns and loT Desian 3- 41 8051 VO Ports, Timers, Serial Ports and Inteupts

Program
;
MOV TMOD,#2H Timer 0, mode 2 (8-bit auto reload)
MOV TH0,#206 :THO = 206
SETB TRO ;Start timer 0
BACK: JNB TF1, BACK ; Stay till
timer rolls over
CPL P1.0 ;Complement P1.0

g
CLR TFO ;Clear timer flag 0

in
SJMP BACK ; Continue

Write an assembly language program to make LED ON and OFF connected

er
Example 3.5.10
to P l.0 continuously with ON time 20 msec and off time 40 msec.

e
in
:
Solution Assume crystal frequency 12 MHz
Time for one instruction = (1/12 MHz) *12 =1usec.

ng
Count to be loaded in THO:TLO = >20 usec/1 u sec. = 20000 (Decimal)
65536 – 20000 = 45536 = BIEOH
fE
ORG O000H
O
:
START MOV TMOD,#01H
MOV TH0,#0B1H
e

MOV TLO,#0EOH
g

SETB P1.0
le

ACALL DELAY
ol

CLR P1.0
ACALL DELAY
C

ACALL DELAY
SJMP START
u

DELAY20MS: SETB TRO


ad

HERE: JNB TEFO, HERE


CLR TFO
iln

CLR TFO
RET
m

wave of frequency
Write an assembly language program to generate square
a
Example 3.5.11
Ta

202 kHz on pin P3.0 using auto reload mode


of
timer0in 8051.
=
Solution: and T/2 100
For 5 1/5 kHz
=
200us
kHz T=
one cycle is 1 us. So the value of THO
SSume clock frequency 12 MHz so time for
and TL0 is 255 - 100 = 155
ORG 0000H
Timer 0 in mode 2
MOV TMOD, #02H
; THO = 155
MOV TH0,#155
SETB TRO Start timer 0

knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>

Page 12l of 446

Embedded Systems and loT Design 3-42 8051 VO Ports, Timers, Serial Ports and Intemupts

HERE : JNB TF0, HERE


CPL P3.0
ORG 001BH
CLR TEFO
SJMP HERE

g
3.5.1 Programming Timers in 8051 C

in
The general purpose registers of 8051, such as RO-R7, A and B are under control
of

er
the C compiler and are not accessed directly by C statement. However, in case of SFRs

e
entire RAM space of 80H-FFH is directly accessible to 8051 C statements. In this section

in
we discuss the accessing of timers using C statements.

ng
Accessing Timer Registers in C
fE
In 8051 C, we can access the timer registers TH, TL and TMOD directly with the
inclusion reg51.h file in the program. We can also acess TR and TF bits directly. This is
illustrated in example.
O
Example 3.5.12 Write an 8051 C program to toggle all bits of port PO continuously. Use
e

timer 0 to generate delay of 1 sec between each toggle.


g

Solution:
le

#include <reg51.h>
ol

void DELAY (void);


void main (void)
C

while(1) /* Repeat forever */


u

{
ad

P0=0x00; Make PO bits all zero */


DELAY(): * Wait for 1 sec */
= 0xFF;
iln

PO Make PO bits all one */


DELAY): * Wait for 1 sec */
m
Ta

void DELAY)

unsigned char i;
for(i=0; i<20; i++)

TMOD = 0x01; Configure timer 0


in mode 1 */
TLO = Ox28; /* Load count in TLO *I
THO = Ox29; * load count in THO */
TRO = 1; Turn on TO */
while(TFO == 0); /* Wait for TFO to rollover */
TRO = 0; /* turn off TO */
TFO = 0; /* clear TFO */

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 122 of 446

Embedded Systems and loT Design 3-43 8051 I/O Ports, Tinmers, Serial Ports and InterTupts

Timer Count Calculations


Assume crystal frequency = 12 MHz
12
T = = 1 us
12x10-6

g
in
Let us determine the count to get a delay of 50 ms

er
ms =
:: We need 50 50000 clocks.
1us

e
. Count = 65536 – 50000 = 10536 = 2928 H

in
To get a delay of 1 sec we have to repeat the delay of timer0 20 (1/50 msec) times.

ng
Example 3.5,13 Write an 8051 C program to toggle only pin P1.0 continuously every 500 ms.

Solution:
fE
Let ususe mode 2 of timer0 to create the delay. Mode 2 is an 8-bit auto reload mode.
O
#include <reg51.h>
void Delay(void);
e

sbit portbit = P1^0;


g

void main(void)
le

unsigned char ij:


ol

while(1)
C

{
portbit =~ portbit; /* toggle P1.0 */
for(i=0; i<500; i++)
u

for(j=0; j<40; j+ +)
ad

Delay();
iln

void Delay(void)
m

/* Time 0, mode 2(8-bit auto-reload) */


TMOD=0x02;
Ta

THO=-25; * load THO (auto-reload value) */


/* tum on TO */
TRO=1;
/* wait for TFO to roll over */
while(TF0==0);
TRO=0; /* tun off TO */
/* clear TFO "/
TFO=0;
= 12 MHz.
Delay calculations
:
Assume XTAL frequency
T= 12/12 MHz =1 us
256 - 25 = 231

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 123 of 446

Embedded Systems and loT Design 3-44 8051 VO Ports, Timers, Serial Ports and Interrupte

25 x 1.0us = 25 us
Total delay = 25 us x500x 40 500 ms
=

Note Due to inclusion of for loop of C in delay generation, the delay may be slightly
can adjust delay loop count by
more
than expected. To get a correct delay we
observing frequency of port 1.0 on oscilloscope.

g
in
on pin P2.0.
Exanple 3:5.14 Write an 8051 C program to create a frequency of 2 kHz

er
create the delay. Mode 2 is an 8-bit auto
Solution: Let us use mode 2 of timer1 to

e
reload mode.

in
#include <reg51.h>
void Delay(void);

ng
sbit portbit=P2^0;
void main(void)

while(1)
fE
O
portbit=portbit; * toggle P2.0 */
Delay():
g e

void Delay(void)
le
ol

TMOD=0x20; * Timer 1, mode 2(8-bit auto-reload) */


TH1=-250; / load Th1(auto-reload value) */
C

TR1=1; /* turn on T1 *l
while(TF1==0); * wait for TF1 to roll over */
u

TR1=0; * turn off T1 */


ad

TF1=0; /* clear TF1 */

Delay calculations : Assume XTAL frequency = 12 MHz


iln

T= 12/12 MHz=1 us
m

1/2 kHz = 0.5 ms


Ta

0.5 ms/2 = 0.25 ms


0.25 ms / 1 us = 250
Examplè 3.5.15 Two switches are connected to pin P1.0
and P1.1, respectively. Write at
8051 C program to monitor switches
and create the following frequencies on pin P2.0
according switch positions.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 124 of 446

Embedded Systems and loT Design


3- 45 8051 I/O Ports, Timers, Serial Ports and Intermupts

SW1 SWo Frequency


0
100 Hz

1 200 Hz
0 300 Hz
1

g
1
400 Hz

in
Use timer 0, mode 1 for both of them.

er
Solution:
#include <reg51.h>

e
sbit sw0=P1^0;

in
sbit sw1=P1^1;

ng
sbit portbit=P2^0;
void Delay(unsigned char);
void main(void) fE
SW0=1; /* Make P1.0 an input */
O
SW1=1; /* make P1.1 an input */
while(1)
e

{
g

portbit=~portbit; /* toggle P2.0 "/


le

if(sw1==0&sw0==0) / check switch /


Delay(1):
ol

if(sw1==0&sw0==1)
Delay(2);:
C

if(sw1==1&sw0==0)
Delay(3);:
u

if(sw1==1&sw0==1)
ad

Delay(4);:
iln

void Delay(unsigned char c)


m

TMOD=0x01;
do
Ta

TL0=0x78;
THO=0xXEC;
TRO=1;
while(TFO==0);
TRO=0;
TF0=0;
c=c-1;

while(cl=0);

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


<br>

Page 125 of 446

Embedded Systems and loT Design 3-46 8051 VO Ports, Timers, Serial Ports and Inteupts

EC78H= 60536
65536 - 60536 = 5000
5000 x 1 us = 5 ms
1/ (5 ms x
2) = 100 Hz

C Programming of Timers 0 and 1 as Counters

g
Let us see how to use timers 0 and 1 as event counters. A timer can be used as a

in
counter if we provide external clock instead of using the frequency of
the crystal

er
oscillator as the clock source. By feeding pulses to the TO (P3.4) and T1 (P3.5) pins, we
can use timer 0 and timer 1 as counter 0

e
and counter 1, respectively. Following
examples show us how timers 0 and 1 are programmed as counters

in
using the C
language.

ng
Example 3.5.16 Assume that a 1-Hz external clock is being fed into pin T1. Write n C

program for counter 1 in mode 2 fE


(8-bit auto reload) to count up and display the state of
the TL1 count on P0. Start the count from 00H.
O
Solution:
#include <reg51.h>
e

sbit T1 = P3^5;
g

void main(void)
{
le

T1=1; ./* make T1 an


input *l
ol

TMOD=0x60;
TH1=0; /* set count to 0 */
C

while(1) /* repeat forever */


{
u

TR1=1 /* start timer */


ad

do
{
iln

PO=TL1; /* place value on port P0 */


m

while(TF1==0); /* wait for TF1 to rollover*/


TR1=0; /* stop timer *l
Ta

TF1=0; /* clear flag */

Example 3.5:17 Assume that a 1


Hz external clock is being fed into pin TO.
program for counter 0 in Write a C
mode 1 (16 bit) to count the pulses and
display the THO and
TLO registers on
P1and P0, respectively.
Solution:
#include <reg51.h>
void main(void)

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 126 of 446

Embedded Systems and loT Design 3-47 8051 WO Ports. Timers. Serial Ports and Interrupts

TO=1; * make TO an input */


TMOD=0x05;
TL0=0; * set count to 0 */
THO=0; * set count to 0 */
while(1) /* repeat forever */
TRO=1; * start timer */

g
do

in
P0=TL0; /* place value of TLO on port 0 */

er
P1=THO; /* place value of THO on port 1 */

e
while(TFO==0); * wait here */

in
TRO=0; /* stop timer */
TFO=0; /*clear flag */

ng
Example 3.5,18 Assume that a2
fE
Hz external clock is being fed into pin T1. Write a C
program for counter 0 in mode 2 (8-bit auto reload) to display the count in ASCII. The
O
8-bit binary count must be converted to ASCII. Display the ASCII digits (in binary)
on
e

PO serialy. Display least significant digit first.


g

we must convert 8 bit binary data to ASCII.


Solution: To display the TL1 count
le

#include <reg51.h>
ol

void BinToASCII(unsigned char);


void main()
C

unsigned char value;


u

T1=1;
ad

TMOD=0x06;
THO=0;
iln

while(1)
m

do
Ta

TRO=1;
value=TL0;
BinToASCII(value);

while(TFO==0);
TRO=0;
TF0=0;

value)
void BinToASCII (unsigned char
unsigned char Abyte, i,Q;
unsigned char R[31:
an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 127 of 446

Embedded Systems and loT Design 3-48 8051 VO Ports, Timers, Serial Ports and Interupte

Abyte = 0XFB;
i=0;
do

Q=Abyte/10; /* divide by 10 */
R[i]=Abyte%10; /* find remainder and save it "/
Abyte=0; /* save quotient as a number */

g
i=i+1;

in
while(Q!= 0) /* Repeat until quotient = 0 */

er
for(; i>0 ; i--)

e
PO=R[i-1]+0<30; /* Make binary to ASCII /

in
ng
Example 3.5.19 Assume that a 100 Hz external clock is being fed into pin T0. Write a
C program fE
for counter 0 in mode 2 (8-bit auto-reload) to display the seconds and minutes
on PO and P1, respectively.
O
Solution:
#include <reg51.h>
e

void Time(unsigned char);


g

void main(void)
le

unsigned char val=0;


ol

TO=1;
TMOD=0x06; /* TO, mode 2,counter */
C

THO=100; /* sec=100 pulses "/


while(1)
u

TRO=1; /" start timer */


ad

while(TF0==0);
Time(val);
iln

val+ +;
TRO=0; /* stop timer */
m

TFO=0; /* clear flag */


Ta

void Time(unsigned char value)


{

unsigned char sec,min;


min=value/60;
sec=value % 60;
P0=sec;
P1=min;

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 128 of 446

Embedded Systems and loT Design


3-49 8051 VO Ports, Timers, Serial Ports and Interrupts

Example 3.5.20 Write an 8051 C program to generate a rectangular wvave of 2 kHz with
60 % duty cycle in pin P.2. Assume G ysta! frequency as 11.0592 MHz. Use Timer - 0
in mode-1 operation. Show delay calculations.

Solution: For 2 kHz rectangular wave,


1
T= = 0.5 ms
2 kHz

g
0.5 msx10 =

in
For 60 % duty cycle :
ToN = 0.3 ms
100

er
0.5 msx 40 =
ToFF 0.2 ms

e
100

in
12
Time for 1 T-state = = 1.085 us

ng
11.0592x106
Count for ToN = 0.3 ms - 276
1085 nms fE
Count for ToFF = 184
O
Count to be loaded for Tox =
65536 – 276 = 65260 = FEECH
e

THO = FEH, TLO = ECH


g

Count to be loaded for TorF = 65536 – 184 = 65352 = FF48H


le

THO = FFH, TLO = 48H


ol

#include <reg51.h>
sbit mnybit = P2 ^ 1;
C

void TOM1D (unsigned char)


u

void main (void)


ad

while (1)
iln

mybit = 1; /'Make P2.1 High/


TOM1D (1): /* Wait for 0.3 msec /
m

mybit = 0; /'Make P2.1 Low"/


TOM1D = (0): /*Wait for 0.2 msec'/
Ta

void TOMID (unsigned char i)


{

TMOD = 0x 01; /Timer 0, mode 1/


if (i = = 0)

TLO= ECH: /Load FEECH'/


THO = FEH;

TECHNICAL PUBLICATIONS an up-thrust for knowedge


<br>

Page 129 of 446

Embedded Systems and loT Design 3-50 8051 WO Ports, Timers, Serial Ports and
Interrupts

else
{
TLO = 48H; /*Load FF48H*/
THO = FFH;

TRO = 1; /*Turn ON Timer 0*/


while (TFO = = 0); /*Wait for TF0 to roll over */
TRO = 0; /*Turn OFF Timer 0 *l

g
TFO = 0; /*Clear TFO*/

in
e er
in
Revjew Question

ng
1. Write a note on counter programming of 8051.

3.6 8051 Serial Port AUMay-05, 10, fE 12, Dec-08,.09, 11; 13,14,:17, June-07

The serialport of 8051 is full duplex, means it can transmit and receive
O
simultaneously. It uses register SBUF to hold data. Register SCON controls data
communication, register-PCON controls data rates and pin RxD (P3.0) and TxD (P3.1) do
g e

the data transfer.


le

SBUF is RxD
(P3.0) SBUF
ol

an 8-bit Shift register CLK TxD


(Write only) (P3.1)
register CLK
C

dedicated
Baud rate clock
for
u

serial (Transmit)
Baud rate clock
ad

commurnicat (Receive)
SBUF
ion in 8051. (Read only)
Its address
iln

is 99H. It
m

can be
8051 Internal bus
addressed
Ta

Fig. 3.6.1
like any
other register in 8051. Writing to SBUF loads data to be transmitted and reading Sp
transmit
accesses received data. There are two separate and distinct registers, the
write-only register, and the receive read-only register. This is illustrated in Fig. 3.6.1
during
The way in which SBUF is used for the transmission and reception of the data
serial communication is explained below.
pin, the
Transmission : When a byte of data is to be transmitted via the TxD
SBUF, it
SBUF is loaded with this data byte. As soon as a data
byte is written into
pin.
is framed with
the start and stop bits and transmitted serially via the TxD
TECHNICAL PUBLICATIONS an up-thrust for knowledge
<br>

of 446
Page 130

Embedded Systems and loT Design


3- 51 8051 VO Ports. Timers, Serial Ports and Interrupts

Reception : When 8051 receives data serially via RxD


it. The start and stop bits are
pin of it, the 8051 deframes
separated out from a byte of data. This byte is
placed in SBUF register.
Rit pattern of SCON register : The 8051 provides four programnmable
modes for serial
data communication. A particular mode can
be selected by setting the SM0 and SM1 bits
in SCON. The mode selection also

g
decides the baud rate. The Fig. 3.6.2 shows the bit
patterns for SCON.

in
(MSB)

er
7 6 5 4 3 Pue
2 1

e
e
SMO SM1

in
SM2 REN TB8 RB8 TI RI buisaeubu3

ng
Symbol Position Name and Significance
SMO SCON.7 Serial port Mode control bit 0.
fE
Set/cleared by software (see note).
O
SM1 SCON.6 Serial port Mode control bit 1.

Set/cleared by software (see note).


g e

SM2 SCON.5 Serial port Mode control bit 2.


is zero.
le

Set by software to disable reception of frames for which bit8


ol

REN SCON.4 Receiver Enable control bit.


Set/cleared by software to enable/disable serial data reception.
C

TB8 SCON3 Transmit Bit 8.


u

Set/cleared by hardware to determine state of ninth data bit trarismitted in 9-bit


ad

UART mode.

RB8 Receive Bit 8.


SCON.2
iln

Set/cleared by hardware to indicate state of ninth data bit received.


m

TI SCON.1 Transmit Interrupt flag.


Set by hardware when byte transmitted. Cleared
by software after servicing.
Ta

RI SCON.0 Receive Interrupt flag.


Cleared by software after servicing.
Set by hardware when byte received.
:

Note: The state (SMO, SM1) selects


of
Mode SMO SM1
=
0 0 Shift register ; baud f/12
0
rate.
1 8-bit UART, variable data
1 ;
9-bit UART, fixed data rate baud
f/32 or f/64
1
2 rate.
1 1 9-bit UART, variable data
3
Fig. 3.6.2 SCON-Serial
port control/status register

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 13l of 446

Embedded Systems and loT Design 3-52 8051 VO Ports, Timers, Serial Ports and Interrupts

Bit pattern of PCON register:


(MSB) (LSB)

7 6 5 4 3 2 1

SMOD GE1 GFO PD IDL

g
in
Symbol Position Name and significance

er
SMOD PCON.7 Serial baud rate modifjy bit. It is 0 at reset. It is set to 1 by program to double the

e
baud rate.

in
PCON.6-4 Not defined

ng
GF1 PCON.3 General purpose user flag bit 1. Set/cleared by program.
GFO PCON.2 General purpose user flag bit 0. Set/cleared by program.
PD PCON.1
fE
Power down bit. It is set to 1 by program to enter power down
configuration for CHMOS microcontrollers.
O
IDL PCON.O Idle mode bit. It is set to 1 by program to enter idle mode configuration
for CHMOS microcontrolers.
e

wwwww

:
Note PCON is not bit addressable
g
le

Fig. 3.6.3 PCON register


ol

3.6.1. Operating Modes for Serial Port


C

Mode 0 : In this mode, serial data enters and exits through RxD. TxD outputs the shift
clock. 8 bits are transmitted /received : 8 data bits (LSB first). The baud rate is fixed at
u

1/12 the oscillator frequency.


ad

Mode 1: In this mode, 10 bits are transmitted (through TxD) or received


iln

(through RxD) : A start bit (0), 8 data bits (LSB first) and a stop bit (1), On receive, the
stop bit goes into RB8 in Special Function Register SCON. The baud rate is variable.
m

Mode 2 : In this mode, 11 bits are transmitted (through TxD) or received


Ta

(through RxD): A start bit (0), 8 data bits (LSB first), a programmable gh data bit, and
a stop bit (1). On Transmit, the 9h data bit (TB8 in SCON) can be assigned the value of
0 or 1. Or, for example, the parity bit (P, in the PSW) could be moved into TB8. On
receiv, the 9 data bit goes into RB8 in Special Function Register SCON, while the stop
bit is ignored. The baud rate is programmable to either 1 or 1 the oscillator frequency
32 64

Mode 3: In this mode, 11 bits are transmitted (through TxD) or received


(through RxD): A start bit (0), 8 data bits (LSB first), a programmable
9 data bit and
stop bit (1). In fact, Mode 3 is the same as Mode 2 in all respects except
the baud ra
The baud rate in Mode 3 is variable.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 132 of 446

Embedded Systerms and loT Design 3- 53 8051 VO Ports, Timers, Serial Ports and Interupts

In all four modes, transmission is initiated by any instruction that uses SBUF as a
destination register. Reception is initiated in Mode 0 by the condition RI = 0 and
REN = 1. Reception is initiated in the other modes by the incoming start bit if REN = 1.
The Table 3.6.1 summarizes the four serial port modes provided by 8051.

Mode Transmission format Baud rate

g
in
0 8-data bits. oscillator frequency,

er
10-bit (start bit + 8-data bits + stop bit). Variable.

e
2

in
11-bit (start bit + 8-data bits + programmable Programmable to either 32 64
gth data bit + stop bit).
oscillator frequency.

ng
3 Variable.
11-bit (start bit + 8 data bit + programmable
gh data bit + stop bit). fE
Table 3.6.1 Summary of serial port modes
O

3.6.2 Generating Baud Rates


e

a fixed baud rate which is 1/12 of the oscillator


g

Serial Port in Mode 0: Mode 0 has


none of the Timer/Counters need to be
frequency. To run the serial port in this mode
le

set up. Only the SCON register needs to be defined.


ol

Oscillator frequency
C

Baud rate = 12
u

can be
Serial Port in Mode Mode 1 has a variable baud rate. The baud rate
1 :
ad

generated by either Timer 1 or Timer 2 (8052 only).


iln

Using Timer/Counter to Generate Baud Rates


1

2 (Auto-Reload).
For this purpose, Timer is used in mode
1
m

Kx Oscillator frequency
Ta

Baud rate = 32 x 12 x [(256-TH1)]

If SMOD = 0, then K= 1.
= the PCON register)
If SMOD =1, then K 2. (SMOD is
rate and needs to know the reload value
Most of the time the user knows the baud can be written as :
tor TH1. Therefore, the equation to calculate TH1
Oscillator frequency
TH1 = 256 - Kx
384 × Baud rate

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 133 of 446

Embedded Systems and loT Design 3-54 8051 IWO Ports, Timers, Serial Ports and Interrupts

TH1 must be an integer value. Rounding off THI to the nearest integer may not
produce the desired baud rate. In this case, the user may have to choose another crystal
frequency.
Since the PCON register is not bit addressable, one way to set the bit is logical ORing
the PCON register. (i.e. ORL PCON, #80). The address of PCON is 87H.
The Table 3.6.2 shows the values to be loaded into TH1 to get the correspornding

g
baud rate. It also shows that the baud rates are doubled when SMOD = 1.

in
er
TH1 (HEX) Baud rate (SMOD= 0) Baud rate (SMOD = 1)

e
FD 9600 19,200

in
FA 4800 9600

ng
F4 2400 4800

E8 1200 2400

Note : XTAL = 11.0592 MHz


fE
O
Table 3.6.2
Using Timer/Counter 2 to Generate Baud Rates
e

For this purpose, Timer 2 must be used in the baud rate gernerating mode. If Timer 2
g

is being clocked through pin T2 (P1.0) the baud rate is :


le

Timer 2 overflow rate


ol

Baud rate =
16
C

:
And if it is being clocked internally the baud rate is
u

=
Oscillator frequency
ad

Baud rate
32 x [65536 -(RCAP2H, RCAP2L)]
iln

To obtain the reload value for RCAP2H and RCAP2L the above equation can be
rewritten as :
m

Oscillator frequency
RCAP2H, RCAP2L = 65536
Ta

32 × Baud rate

Serial Port in Mode 2


1 1
The baud rate is ixed in this mode and is of the oscillator frequenc)
Or
32 64
depending on the value of the SMOD bit in the PCON register. In this mode none of the
Timers are used and the clock comes from the internal phase 2 clock.
1
SMOD = 1, Baud rate = Oscillator frequency
32

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 134 of 446

Embedded Systems and loT.Design 3- 55 8051 VO Ports, Timers, Seial Ports and InteTupts

SMOD = 0, Baud rate


=
1
64
Oscillator frequency
:
To set the SMOD bit ORL PCON, #80H. The address of PCON is 87H.
Note By changing SMOD bit in PCON from 0 to 1 we can double the baud rate in

g
8051

in
Serial Port in Mode 3

er
The baud rate in mode 3 is variable and sets up exactly the same as in mode 1.

e
3.6.3 Programming 8051 for Serial Data Transfer

in
To program 8051, to transfer data serially we have to perform following
sequence of

ng
:
actions
1. Load the TMOD register
fE
with the value 20H to use timer 1 in mode 2
(8-bit auto-reload) to set the baud rate.
O
2. Load TH1 to set the desire baud rate for serial data transfer.
use serial mode 1, where an 8-bit data
Load SCON register with the value 50H, to
e

3.
is framed with start and stop bits.
g
le

4. Set TR1 to to start timer 1.


1

Clear TI with CLR TI instruction.


ol

5.
register.
Write a character to be sent in to the SBUF
C

6.
XXXX to see if the character has
7. Check the TI flag bit with instruction JNB TI,
u

been transferred completely.


ad

next character.
O. Go to step 5 to transfer the
Example 3.6.1 8051 uses 11.0592 MHz crystal. To get 9600 hertz baud rate how will you
iln

?
a ProgTam it for serial transmission
m

a'
standard baud rate of 9600 bertz is
oolution: When 11.0592 MHz Crystal is used and
can be found as,
Ta

quired then, the setting of TH1


kxOscillator frequency
TH1 = 256 - 384 x Baud rate
11.0592 x 106 = 253 = FDH
1 x
= 256
384 x 9600
:Initialize timer 1 in mode 2
Frogran: MOV TMOD, #020 1
MOV SCON, #4CH
Initialize serial mode
;

;Make SMOD =1
ORL PCON, #8OH
MOV TH1, #FDH
:Load count
- an up-thrust for knowedae
TECHNICAL PUBLICATIONS
<br>

Page 135 of 446

Embedded Systems and loT Design 3-56 8051 VO Ports, Timers, Serial Ports and Intemun.

program to transfer letter "A" serially at


Example 3.6.2 Write an 8051 assembly language
9600 baud rate, continuously.

Solution:
MOV TMOD, #20H
;timer 1, mode 2 (auto reload)
MOV TH1, #FDH ;9600 baud rate

g
MOV SCON, #50H ;8-bit, 1 stop REN enabled

in
SETB TR1 ;start timer 1
; Letter "A" to be transferred

er
START: MOV SBUF, #"A"
:Wait for the last bit to transfer
HERE: JNB TI, HERE

e
CLR TI ;Clear TI for
the next character

in
SJMP START ;Go to send the character again

ng
Example 3.6.3 Write an 8051 ssembly language program to transfer the message
"HELLO"serially at 9600 baud, 8-bit data, 1 stop bit.

Solution :
fE
MOV TMOD,#20H ;timer 1, mode 2
O
MOV TH1,#FDH ;9600 baud rate
MOV SCON,#50H ;8-bit, 1 stop bit, REN enabled
e

-
SETB TR1 ; start timer 1
g

START: MOV A, #"H" ;


transfer "H"
le

ACALL TRANS
MOV A, #"E"
ol

transfer "E"
ACALL TRANS
C

MOVA, #L" ;transfer "L"


ACALL TRANS
u

MOV A, #"L" itransfer "L"


ad

ACALL TRANS
MOVA,#"O" itransfer "O"
iln

ACALL TRANS ;Serial data


transfer subroutine
TRANS: MOV SBUF, A ;Load SBUF
m

HERE: JNB TI, HERE ; wait for


the last bit to transfer
:Clear TI for
Ta

CLR TI the next character


RET
The importance of the TI flag
bit: When a data is to be transmitted via TxD pin,
a data byte is loaded into
the SBUF register. A start bit, a data byte and then ist
the stop
bit are transmitted sequentially via TxD pin. During the transmission of the stop bil
8051 sets the TI flag, i.e. TI = 1. This indicates
the end of data byte transmission ano
8051 is ready for the transmission and 8051 is
ready for the transmission of next dat
The programmer has to clear the TI flag, ie. TI = 0, with the 'CLR TI' instruction
transmit next data. The TI flag bit should be monitored to make sure
that the SBU
register is not overwritten. If we write the next byte to be transmitted into the SBU

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
<br>

Page 136 of 446

Embedded Systems and loT Desian


3- 57 8051 /O Ports. Timers, Serial Portsand Interrupts

register before setting the TI flag bit, the untransmitted portion of will
Le lost. The programmer can check the previous byte
the TI flag bit by NB TI XX instruction or by using
an interrupt.

R64 Programming 8051 for Receiving Data Serially


To program 8051, to receive data serially we have to perform following sequence of

g
in
actions :
1. Load the TMOD register with the value 20H to use timer

er
1 in mode 2
(8-bit auto-reload) to set the baud rate.

e
2. Load TH1 to set the desire baud rate for serial data trarnsfer.

in
3. Load SCON register with the value 50H, to use serial mode 1, where an 8-bit data

ng
is framed with start and stop bits.
4. Set TRI to 1 to start timer 1. fE
5. Clear RI with CLR RI instruction.
O
6: Check the RI flag bit with instruction JNB RI, XXXX to see if an entire character
has been received yet.
e

If RI is set, SBUF has the byte. Save this byte.


g

7.
le

8. Go to step 5 to receive the next character.


ol

Example 3.6.4 Write an 8051 assembly language


program to receive bytes serially with baud
to port 2.
rate 9600, 8-bit data and 1 stop bit. Simultaneously send received bytes
C

SPECIAATI

Solution :
u

MOV TMOD, #20H mode 2 (auto reload)


;timer 1,
ad

MOVTH1, #FDH :9600 baud rate COpY

MOV SCON, #50H ;8-bit, 1 stop, REN enabled


iln

start tmer 1 FOR

SETB TR1
HERE:
:
wait for character receive completely
m

JNB RI, HERE


MOVA, SBUF
; save the received character
: send character to port 2
Ta

MOV P2, A
CLR RI
;
Get ready to receive next byte
;Go to receive next character
SJMP HERE
a is to be received via RxD pin, first
the
Importance of the RI flag bit When dataare
:
e
one bit at time received sequentially via RxD pin.
atart bit, and a data bvte with a byte is formed and the
SBUF register is
When a data byte is received,
the last bit of
During the reception of the stop bit,
loaded with stop bit is received.
this byte. Then the= entire data byte has been
8051 sets RI 1. This indicates that the
the RI flag, ie. SBUF register, should be placed to safe
a

received. This data byte which is loaded in the


lost. The programmer has to clear the
place such as any register or memory before it is

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 137 of 446

Embedded Systems and loT Design 3-58 8051 VO Ports, Timers, Serial Ports and Interrupts

RI flag, ie. RI = 0, with the CLR RI instruction to receive next data and place it
in

SBUF register. The RI flag bit should be monitored to make


sure that the entire byte has
one to ensure the
been received. This monitoring of the RI flag bit till it becomes
copy it to the safe place and then
reception of complete data place it in SBUF register,
'CLR RI instruction are the necessary steps to avoid
any loss of
make RI zero with
received data.

g
in
3.6:5 Doubling the Baud Rate in the 8051

er
We can double the baud rate in 8051 using two way,

e
By doubling the crystal frequency.

in
By making SMOD bit in the PCON register from 0 to 1.

ng
a program to receive message fromn PC to 8051. Message string is
Example3.6.5 Write
"Hello". After this microcontroller sends imessage to PC "Fine".
fE
Solution: The Fig. 3.6.4 shows the connections between 8051 and PC.
MOV TMOD, #20H ; Initialize timer in mode 2
1
O
MOV TH1, #0FDH ; Load count to get 9600 8051
;
baud rate
e

TxDs
MOVSCON, #50H ;8-bit, stop, REN enabled
1 (P3.1)
g

;Start timer 1 To PC
le

SETB TR1 COM Port


MOVDPTR, #2000H ;Initialize memory pointer to RxD
ol

;save received data (P3.0).


; Initialize
C

MOV R0,#05H counter to read


;5 characters Fig. 3.6.4
u

RECV: JNB RI,RECV ;wait for character


ad

MOV A,SBUF ;Read the character


MOVX @DPTR,A ;Save it in memory
iln

INC DPTR ;increment memnory pointer


CLR RI ;Get ready for next character
m

DJNZ RO, RECV :If not last character repeat


MOV DPTR, #MYDATA ;Initialize pointer for message
Ta

CLR A
MOV RO, #4H : Initializecounter to send 4 characters
MOVC A, @A+DPTR ;Get the character
MOV SBUF, A : Load the data
HERE: JNB TI,HERE ;Wait for complete byte transfer
CLR TI ; get ready for next character

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 138 of 446

Embedded Systems and loT Design


3- 59 8051 VO Ports, Timers, Serial Ports and Interrupts

R6.6 8051 Connection to RS 232C


Io RS 232C the voltage level +3 V to + 15 V is defined as logic 0; from
defined as
logic 1.
-3 V to
The control and timing signals are compatible with the TTL
-15 is
V

Javel. Because of the incompatibility


of the data lines with the TTL logic, voltage
wanslators, called line drivers and line receivers, are required to interface TTL
logic with
he RS 232C signals. The Fig. 3.6.5 shows the connection between RS 232C and 8051.

g
Here, MAX 252 chip is used as a line driver and line receiver. We know that 8051

in
assigns two pins RoD (P 3.0) and TxD (P 3.1) for reception and transmission of serial

er
data, respectively. These pins are TTL compatible; therefore, they require line driver and
Iline receiver to make them RS 232C compatible. The MAX 232 has two sets of line

e
drivers and line receivers for transmitting and receiving data. Only one set is required

in
for one serial communication.

ng
8051 TTL
MAX 232
RS 232

P 3.0
side fE side

RxD
R OUT
O
R
IN

TxD P3.1 OUT


e

T IN T2
g

R, OUT R,IN DB-9P


le

connector
RS 2320C
ol

OUT
T, IN T,
C

Fig. 3.6.5 Connection between RS 232C and 8051


u
ad

C
3.6.7|Serial Communication Programming in
registers of the 8051 are accessible directly in 8051 C compilers by inclusion
iln

The SFR
of the reg51.h file. However, to use second serial port
we have to declare the byte
m

SCONV1 using SFR data type. In


dddresses of the new SFR registers, i.e. SBUF1 arnd
RI1 using bit data type.
dddition, we have to declare bit addresses for TI1 and
Ta

to transfer the letter "C" serially at


Ckample 3.6.6 Write n C program for the 8051
e

9600 baud continuouslu. Use 8-bit data and l stop bit.


Solution:
#include<reg51.h>
void main
(void)

TMOD= Ox20;
TH1 = 0XFD;
SCON = 0x50;

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

of 446
Page 139

Embedded Systems and loT Design 3-60 8051 VO Ports, Timers, Serial Ports and Inteupte

TR1 = 1;
while(1)

SBUF='C;
while(TI==0);
TI=0;

g
in
Example 3.6.7 Write a program that continuously receives a single bit of data from P1.0
C

er
and sends it to P2.0, while simultaneously creating a square wave of 400 us period on pin
P2.5. Use timer 0 to create the square zuave. Assume that XTAL = 11.0592 MHz.

e
Solution : We will use timer 0 in mode 2 (auto-reload). One half of the period is 200 s.

in
200/1.085 us = 184 and THO = 256 - 184 =72 or 48H.

ng
#include <reg51.h>
sbit IBit = P1^0;
sbit Obit = P2^0;
sbit SWAVE = P2^5;
fE
void timerO(void) interrupt 1
O
SWAVE = ~ SWAVE; /* toggle pin P2.5 */
ge

void main(void)
le

Obit = 1; / make P1.0 input */


ol

TMOD = 0x02;
THO = Ox72; * THO =-184 */
C

IE = 0x82; /* enable interrupts for timer 0 */


while(1)
u
ad

Obit = Ibit; /* send received bit to P2.0 */


iln

Example 3.6.8 Write a C program that continuously gets a


single bit of data from P1.0 and
m

sends it to P2.0 in the main, while simultaneously


(a) creating a square wave of 400
s
Ta

period on pin P2.5, and (b) sending letter "A' through


'Z' to the serial port. Use timer 0
to create the square wave. Assume
that XTAL = 11.0592 MHz. Use the 9600 baud rate.
Solution: We will use timer 0 in mode 2 (auto-reload). THO = -
200/1.085 Lus = 184
which is 72H.
#include <reg51.h>
sbit Ibit = P1^0;
sbit Obit = P2^ 0;
sbit SWAVE = P2^5;
unsigned char ch='A';
void timerO(void) interrupt 1

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 140 of 446

Embedded Systems and loT Design 8051 WO Ports, Timers, Serial Ports and Interrupts
3- 61

SWAVE=~SWAVE; / toggle pin 2.5 *I

void serial0(void) interrupt 4

if(TI == 1)
{
SBUF = ch;

g
/* send character to serial port */
TI = 0; /* clear interrupt */

in
ch++;

er
if(ch >= Z)
ch ='A;

e
in
else

ng
RI = 0; /* clear interrupt */

void main(void)
fE
O
Ibit = 1; * make switch input */
TH1 = -3; /* 9600 baud */
e

TMOD = 0x22; /* set mode 2 for both timers */


g

THO = Ox72; /* load 72H as a timer count */


le

SCON = 0x50;
TRO = 1;
ol

TR1 = 1; /* start timer */


IE = 0x92; /* enable interrupt for TO*/
C

while(1) /* stay here */


u

{
Obit = Ibit: * send received bit to bit P2.0 */
ad

}
iln

Example 3.6.9 Write a C program using interrupts to do the following :


m

to PO,
a) Receive data serially and send it
a copy to P2,
b) Read port P1, transmit data serially, and give
Ta

on P0.1.
c) Set timer 0, generate aa square onve of 2.5 kHz frequency
rate at 9600.
Assume that XTAL = 11.0592 MH. Set the baud
Solution:
#include <reg51.h>
=
sbit SWAVE PO^1;
1
void timero () interrupt

SWAVE = ~ SWAVE; /* toggle pin */

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 14l of 446

Embedded Systems and loT Design 3-62 8051 VO Ports, Timers, Serial Ports and Interrunte

void serial0() interrupt 4

if(TI == 1)
{
TI = 0; /* clear interrupt "/

else

g
{

in
PO = SBUF; put value on pins */
RI = 0; /* clear interrupt */

e er
void main()

in
ng
unsigned char c;
P1 = 0xFF; /" make 7P1 an input */
TMOD = 0x22; fE
TH1 = OxF0; /* 9600 baud rate */
SCON = 0x50;
O
THO = 0x72; 2.5 kHz has T= 400 s
/
IE = 0x92; /* enable interrupts */
e

TR1 = 1; /* start timer 1 *l


TRO = 1;
g

/* start timer 0 */
while(1)
le
ol

C= P1; /* read data byte from port P1 */


SBUF = C;
/ put data byte in buffer "/
C

P2 = c; * send data byte to port P2 */


u
ad

Example 3.6.10 Write a 8051 program that continuously gets a single bit of data from
C
P1.7 and sends it to P1.0, which creates a square wave of 200 uS period on pin P2.0.
iln

XTAL frequency = 11.0592 MH. AU Dec. 13, Marks.


16
m

Solution : We will use timer 0 in mode 2 (auto-reload). One half of the period is 100
100/1.085 us = 92 and THO = 256 - 92 = 164 or A4H.
Ta

#include <reg51.h>
sbit IBit = P1^7;
sbit Obit = P1^0;
sbit SWAVE = P2^5;

void timer0(void) interrupt 1

SWAVE =~SWAVE; / toggle pin P2.5 */


void main(void)

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 142 of 446

Embedded Systems and loT Design 3- 63 8051 /O Ports, Timers, Serial Ports and Interrupts

Obit = 1; /* make P1.7 input */


TMOD = 0x02;
THO = OxA4; /* THO= -92 */
IE = 0x82; /* enable interrupts for timer 0 */
while(1)
{
Obit = Ibit; /* send received bit to P1.0 */

g
in
Example 3.5.11 Write an 8051 C program to i) Continuously read the status of switch

er
connected to pin P1.2 and send it to pin P2.1 in the main program and ii) Generate a

e
square wave 100 usec period on P2.3 and end character * continuously serially using
of

in
timer and serial interrupt routines, respectively. Use XTAL frequency as 11.0592 MHz

ng
and 8 bits data, one stop bit, 4800 baud rate fornat.
Solution:We will use timer 0 in mode 2 (auto-reload).

For square wave ToN = T/2 = 50 usec


fE
O
12
1
T-state = 1.085 usec
11.0592x106
e

50 usec
=- 46
g

THO = 1.085 usec


le

= 256 - 46 = 210 = D2H


ol

#inciude <reg51.h>
C

sbit SW = P1^2:
P2^1:
=
ST
sbit
u

sbit SWAVE = P2^3;


ad

1
void timer 0 (void) interrupt
{
/* toggle pin */
iln

Swave= Swave;
}
void serial 0( interrupt 4
m

if (TI =
Ta

=
1)

SBUF = : /*send t* to serial port*/


TI = 0;
clear interrupt */

else
{
RI = 0; /* clear interrupt */
}

- an up-thrust for knowiedge


TECHNICAL PUBLICATIONs
<br>

Page 143 of 446

bedded Systems and loT Design 3-64 8051 /O Ports, Timers, Serial Ports and Intemupte

void main ()

SW = 1; /* Make switch input */


TH1 = -6; * 4800 baud rate */
TMOD= 0X22; * Mode 2 for both timers */
THO = 0XD2; * Load count D2H for timer 0 */

g
SCON = 0X50; " 8-bit data, 1-stop bit */

in
TRO = 1; /* start timer 0 */

er
TR1 = 1; /* start timer 1 */
IE = 0X92; /* Enable interrupt for TO */

e
While (1) /* wait for interrupt */

in
ng
ST = SW; /* send status of SW to pin P2.1 */
fE
O
Review Questions
e

1. Discuss the serial interface of 8051.


AUMay-05, Marks8
g

2. Discuss in detail, the hardware and software support provided


by 8051 for serial communication.
le

AU Dec -09,17, Marks 16


ol

3. Describe how the serial communication is performed in 8051.


C

:
AU May-10, Dec.-08,11, Marks 8
4. Draw the flowchart for programming of
serial port of 8051.
AU: Dec.-11, Marks 2
u

5. Explain the different serial communication modes


in 8051.
ad

AU : June-07, Marks 8
6. Write 8051 ALP to transmit "Hello
World" to PC at 9600 baud for external
crystal frequency of
11.0592 MHz.
iln

AU: June-07, Marks 8

3.7 8051 Interrupt Structure


m

AU,:June-07, Dec.-07,12,14,16, May-11,13, 14,16


The 8051 provides 5 interrupt sources.
Ta

The 8052 provides 6. These are shown n


Fig. 3.7.1. The external Interrupts INTO
and INT1 can each be either level-activated or
transition-activated, depending on bits ITO
and IT1 in Register TCON. The flags that
actually generate these interrupts are bits IEO
and IE1 in TCON. When an external
interrupt is generated, the flag that generated it is
cleared by the hardware when the
service routine is vectored to only
if the interrupt was transition-activated. I
interrupt was level-activated, then the external
requesting source is what controls
request flag, rather that the on-chip hardware. th
The Timner 0 and Timer 1 interrupts are
a rollover in their respective generated by TFO and TF1, which are set
Timer/Counter registers (except see Timer 0
in Mode
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 144 of 446

Embedded Systems and loT Desian


3- 65 8051 VO Ports, Timers, Serial Ports
and Interrupts
The timer flag set upon
generation of interrupt is
cleared by the on-chip
hardware when microcontroller INTO ITO
IE0
starts execution of particular
interrúpt service routine.

g
in
The serial port interrupt is TFO

er
generated by the logical OR of
RI and TI. Neither of these

e
flags is cleared by hardware

in
Interrupt
when the service routine is INTT E1 sources

ng
vectored to service routine.
In fact, the service routine will
normally have to determine
TF1
fE
whether it was RI or TI that
O
generated the interrupt and the TI

bit will have to be cleared in RI


g e

software.
Fig. 3.7.1 MCS-51 interrupt structure
le

371 Interrupt Control (Enabling and Disabiing Interrupts using IE)


ol

are enabled by software. AIl. of


is reset, all interrupts are disable. These
C

When 8051
same result
ne bits that generate interrupts can be set or cleared by software, with the
es though it had been set or cleared by hardware. That is, interrupts can be generated
or
u
ad

Pending interrupts can be canceled in software.


Lach of these interrupt sources
can be individually enabled or disabled by setting or
iln

3.7.2). IE contains also a


global disable
clearing a bit in Special Function Register IE (Fig.
which disables all interrupts at once.
bit, EA,
m

Note in position IE.6 is unimplemented. In the 8051s, bit position


Ta

Fig. 3.7.2 that bit


IE.5 is User software should not write 1s to .these bit positions,
also unimplemented.
since they products.
may be used in future MCS-51
(LSB)
(MSB)
EX1 ETO EX0
ET2 ES ET1
EA

Symbol Name and significance


Position
IE.7 Enable all control bit. all interrupts, independent of the state of
to disable
Cleared by software
IE.4-IE.0.
<br>

Page 145 of 446

bedded Systems and loT Design 3-66 8051 VO Ports, Timers, Serial Ports andInterrupts

IE.6 (Reserved)
ET2 IE.5 (Reserved)
ES IE.4 Enable Serial port control bit.
Set/cleared by software to enable/ disable interrupts from TI or RI las

g
ET1 IE.3 Enable Timer 1 control bit.
Set/ cleared by software to enable/disable interrupts from timer/counter
1

in
er
EX1 IE.2 Enable External interrupt 1 control bit.
Set/cleared by software to enable/ disable interrupts from INTI.

e
ETO IE.1 Enable Timer 0 control bit.

in
Set/cleared by software to enable/disable interrupts from timer/counter 0.

ng
EXO IE.0 Enable external interrupt 0 control bit.
Set/cleared by software to enable/disable interrupts from INTO.
fE
Fig. 3.7.2 IE-interrupt enable register
Example 3.7.1 Write a program to
O
enable serial interrupt, Timer 1 interrupt and external
hardvare interrupt 0 (EX0)
e

Solution:
g
le

EA ES ET1 EX1 ETO EX0


1
ol

0 1 1 0 0 1

MOV IE, #1001 1001B


C

enable serial, Timer 1, EXO


Example 3.7.2 Write an instruction to disable all interrupts.
u

Solution:By making EA = 0 we can disable


ad

all interrupts.
CLR IE.7 Clear EA bit in the IE register
iln

Example 3.7.3 Write a program to enable Timer


0 interrupt using bit manipulati
instructions.
m

Solution:
Ta

SETB IE.7 Enable interrupts


SETB IE.1 Enable timer 0 interrupt

3.7.2 Interrupt Priority and Interrupt Destinations (Vector


Locations)
Each interrupt source can also be individually
programmed to one of two prio
levels by setting or clearing a bit
in Special Function Register IP (Fig. 3.7.
low-priority interrupt can itself be interrupted
by a high-priority interrupt, but no
another low priority interrupt. A high-priority
other interrupt source.
interrupt can't be interrupted by

TECHNICAL PUBLICATIONS - an up-thrust


for knowledge
<br>

Page 146 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and nterrupts
3- 67
(MSB) (LSB)

PS PT1 PX1 PTO PX0

Symbol Position Name and significance


IP.7 (Reserved)

g
IP.6 (Reserved)

in
IP.5 (Reserved).

er
PS IP.4 Serial port Priority control bit.

e
Set/cleared by software to specify high/low prioríty interrupts for Serial

in
port.

ng
PT1 IP.3 Timer 1 Priority control bit.
Set/cleared by software to specify high/low priority interrupts for

PX1 IP.2
timer/counter 1. fE
External interrupt 1 Priority control bit.
Set/cleared by software to specify high/low priority interrupts for INT1.
O
PTO IP.1. Timer 0 Priority control bit.
e

Set/cleared by software to specify high/low priority interrupts for


g

timer/counter 0.
le

PX0 IP.0 Exterrnal interrupt 0 Priority control bit. Set/cleared by software to specify
interrupts for INTO.
ol

high/low priority enlsivaww


Fig. 3.7.3 IP-interrupt priority control register
C

If two requests of differernt priority levels


are received simultaneously, the request of
same priority level are received
higher priority level is serviced. If requests of the
u

request is serviced.
simultaneously, an internal polling sequence determines which
ad

a structure determined by the


Thus within each priority level there is second priority
iln

:
polling sequence, as follows
m

Vector location Priority within level


Interrupt
(highest)
Ta

0003H
External hardware interrupt 0 (NT0)
000BH
Timer 0 interrupt (TFO)
0013H
External hardware interrupt 1 (INT1)
001BH
Timer 1 interrupt (TF1)
0023H (lowest)
Serial communicationinterrupt (RI and TI)
(IVT) and priority levels
Table 3.7.1 Interrupt Vector Table
to resolve simultaneous
Note that the "priority within level" structure is only used
requests of the same priority level.

TECHNICAL PUBLICATIONS- an up-thrust for knowledae


<br>

Page 147 of 446

Embedded Systems and loT Design 3-68 8051 I/O Ports, Timers, Serial Ports
and Inteupts

Review Questions

1. Explain the register IE format of 8051.


2. Exvlain the interrupt structure of 8051 microcontroller
and explain how interrupts are prioritized
AU: June-07, Dec.-07, Marks 8
3. Explain the interrupt structure with the associated registers in 8051 microcontroller.

g
in
AU May-11, Dec.-12, Marks 8
4. Explain the vectored interrupts in 8051 microcontroller.

er
AU :
May-13, Marks 8
5. Explain interrupt structure of 8051 in detail.
AU: Dec.-14; 16, Marks 16

e
6. Explain the vectored interrupts in 8051 microcontroller.

in
AU: May-16, Maks 8
3.8 Programming Interrupts

ng
"AU: May-11

384 Programming Timer Interrupts


fE
O
The Timer 0 and Timer 1
interrupts are generated by TFO and TF1, which are set by
a rollover in
their respective Timer/Counter registers (except see Timer0 in Mode 3).
e

When a timer interrupt is


generated, the flag that generated it is cleared by the on-chip
g

hardware when the service


routine is vectored.
le

We have seen the use of timer 0


and timer 1 with the polling method. Here, we are
ol

dIscussing the use of interrupts to program 8051 timers. We


know that the timer flag
C

(IF) is set (=1) when the timer rolls over. In polling method, the TF is
monitored with
the instruction JNB TF, target address'. We have to wait
until the TF is raised. The
u

Problem with this polling method is that 8051 can not do anything else
until TF is set to
ad

gh. This problem can be solved using interrupt method. If the timer interrupt in the IE
register is enabled, TF is set whenever the timer is rolled over and the 8051 15
iln

nterrupted. Thus the 8051 can perform anything else until it is interrupted. After
terruption (timer rolling over) only the 8051 remains busy in executing interrupt
m

service routine.
Ta

Example381 Write an 8051 ALP that continuously read 8-bit data from port it
and sends 2.

o port 0. Af the same time it should generate square wave of 500 us period on port 1.0.
Assume the crystal frequency = 11.0592 MHz.
Solution: We use timer 0 in autoreload mode, ie. mode 2. To generate square
will
wave of 500 us we have to
toggle port 1.0 pin after every 250 us.
11.0592x 106
Timer clock frequency = = 921.6 kHz
12

THO 256 - 250 us x


921.6x 103 26 = 1 An

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 148 of 446

Embedded Systems and loT Design 3-69 8051 VO Ports, Timers,. Serial Ports and Interupts

Programn :
ORG 0000H
LJMP MAIN iAvoid using memory space allocated to interrupt vector table
ORG 000BH ;ISR for Timer interrupt
CPL P1.0 ;Complement P1.0 bit
RETI ;return from ISR

g
ORG 0030H ;Start main program after interrupt vector table

in
;
MAIN: MOV TMOD, #02H Initialize timer 0 in mode 2
MOV P2, #0FFH ;Configure port 2.as input

er
MOV THO, #AH ;Load timer count

e
MOV IE, #82H ;Enable timer 0 interrupt

in
SETB TRO ;Start timer 0
BACK: MOV A,
P2 ;Read data from P2

ng
MOV PO, A ; Send it on PO
SJMP BACK ;Repeat fE
END
Write a C program using interupts to do the following
O
Example 3.8.2
a) Generate a 10000 Hz frequency on PO.1 using timer 0 8-bit auto-reload,
on P2. The
b) Use timer 1 as an event counter to count up. a 1 Hz pulse and display it
g e

pulse is connected to EX1.


le

nt 9600.
Assume that XTAL = 12 MHz. Set the baud rate
ol

Solution:
#include <reg51.h>
C

sbit SWAVE = P0^1;


unsigned char cnt;
u

1
void timer0 () interrupt
ad

{
SWAVE =~SWAVE; /* toggle pin P0.1 */
iln

void timer1 () interrupt 3


m

{
/* increment counter */
cnt++; count value on port P2 */
/* display
Ta

P2 = nt;

void main(void)

cnt = 0; * set counter to zero */


TMOD= Ox42;
THO = Ox-50; * Load count to generate 10000 Hz */
/* enable interrupts */
IE = 0x86;
TRO = 1; /* start timer0 */
TR1 = 1; /* start timer1 */
/* wait until interrupted */
while(1);

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 149 of 446

Embedded Systems and loT Design 3-70 8051 /O Ports, Timers, Serial Ports and
Interrupts

:
Counter count calculations
T= 12/12 MHz= 1us
1/10 kHz = 100 us. Half cycle period = 100 us/2 = 50 s
50 us / 1 us = 50

g
3.8.2 Programming External Hardware Interrupts

in
Pins, P 3.2 (pin number 12) and P 3.3 (pin number 13) in port 3 are used as external

er
hardware interrupts INTO and INT1, respectively. The external Interrupts INTO and INITI
can each be either level-activated or transition-activated,
depending on bits ITO and I1

e
in register TCON.

in
In the level triggered mode, external interrupt pins INTO and INT1 are normally high

ng
and if a low-level signal is applied to them, if triggers the interrupt. On the other hand,
in edge trigger mode, high to low input signal transition its the interrupt.
fE
The flags that actually generate these interrupts are bits IE0 and IE1 in TCON. When
an external interrupt is generated, the flag that
generated it is cleared by the hardware
O
when the service routine is vectored to only if the interrupt was transition-activated. If
the interrupt was level-activated, then the external requesting source
e

is what controls the


request flag, rather than the on-chip hardware.
g

If ITx = 0, external interrupt x is triggered by a detected


le

low at the INTx pin. If


ITx =1, external interrupt x is edge-triggered.
In this mode if successive samples of the
ol

INTX pin show a high in one cycle


and a low in the next cycle, interrupt request flag
IEx in TCON is set. Flag bit IEx then requests
C

the interrupt.
Since the external interrupt pins are sampled once
each machine cycle, an input high
u

or low should hold for at least 12 oscillator ensure sampling. If


periods to
interrupt is transition-activated, the external source has to hold the request the
external
ad

at least one machine cycle, and then hold it pin high tor
low for at least one machine cycle to ensure
iln

that the transition is seen so that interrupt request flag. IEx


automatically cleared by the CPUwhen the service routine is called. will be set. IEx will be
m

If the external interrupt is level-activated, the external source


active until the requested interrupt is actually has to hold the request
Ta

generated. Then it has to deactivate the


request before the interrupt service routine is
completed, or else another interrupt Ww
be generated.
Exámplé 3.8.3 Write an 8051 ALP to
glow LED for. a fraction of second when externa
interrupt INTO is activated.
Solution:
ORG 0000H
LJMP MAIN ;Avoid using memory space allocated to interupt vector table
ORG 0003H
SETB P1.0 ;Turn ON LED

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 150 of 446

Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Intemupts
3-71

BACK: MOVE R2, #0FFH :Load count


DJNZ BACK ;
Decrement count and if not zero, repeat
CLR P1.0 ;
Turn OFF LED
RETI ;Return to
main program
ORG 0030H ;Start main program after interrupt vector table
MAIN: MOV IE, #10000001B ;Enable external
interrupt 0

g
HERE :
SJMP HERE ;wait for interrupt

in
END

er
3.8.3 Programming the Serial Communication Interrupts

e
The Serial port interrupt is generated by the logical OR of RI and TI. Neither of these

in
flags is cleared by hardware when the service routine is vectored to. In fact, the service

ng
routine will normally have to determine whether it was RI or TI that generated the
interrupt, and the bit will have to be cleared in software.
fE
Here, we are discussing interrupt based serial communication. In this case, the 8051
can perform other tasks in addition to serial communication, i.e. sending and receiving
O
data from serial communication port.
The transmit interrupt (TI) flag is set (=1) when the last bit of the framed data (stop
e

bit) is transmitted. This indicates that the SBUF register is ready to transmit the next
g

byte. The receive interrupt (RI) flag is set (=1) when the complete frame of data (with
le

stop bit) is received. RI indicates that the received byte needs to be picked up before it
is lost by new incoming serial data.
ol

or an interrupt. Only
All the above concepts are applied equally using polling
C

difference is in serving the serial communication needs. In polling method,


the flag
is set to high.
(TI or RI) is monitored. The 8051 can not do anything else until this flag
u

8051 has received a byte or is


This problem is solved using interrupt method. When
ad

or TI flag respectively is set. Any other work can be


ready to send the next byte, the RI
are served. There is a single interrupt
performed while the serial communication needs
iln

set aside for serial communication. If IE register (E.4) is enabled,


when RI or TI is set
written at 0023h is executed by
(-1), the 8051 is interrupted. When interrupted, the SR
m

to check which one caused the


8051. In ISR, the TI and RI flags must be examined
Ta

response is given.
interrupt and according to flag the
read 8-bit data from port 2 and sends it
Example. 3.8.4- Write an 8051 ALP that continuously
data from serial port at baud rate
to port 0. Af the same time it should read incoming
9600 and send it to port 1. Assume that
crystal frequency = 11.0592 MHz.

Solution:
ORG 0000H
LJMP MAIN
;Avoid using memory space
allocated to interrupt vector table
ORG 0023H
:If RI is low goto skip
JNB RI, SKIP
knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>

Page 151 of 446

Embedded Systems and loT Design 3-72 8051 I/O Ports, Timers, Serial Ports and IInterrupts

MOV A, SBUF ;Otherwise receive serial data


MOV P1, A ; Send it to port 1
; Clear RI
CLR RI
RETI ;Return to main program
SKIP :
CLR TI ;Clear TI
RETI ; Return to main program

g
ORG 10OH
;Configure P2 as an input port

in
MAIN:. MOV P2, #0FFH
MOV TMOD, #20H ;Initialize timer 1 in mode 2

er
MOV TH1, #FDH ;
Load count to get 9600 baud rate

e
MOV SCON, #50H ;Select serial mode with receiver enabled
MOV IE, #10010000B ;Enable serial interrupt

in
SETB TR1 ; Start timer 1

ng
BACK :
MOV A, P2 ;Read data from port 2
MOVP0, A ;Send it to port0
SJMP BACK
END
;Repeat fE
Example 3.8.5 Write an 8051 ALP that continuously
O
read 8-bit data from port 2 and sends it
to port 0. At the same time it should same on
transmit the data serial port. Assume that
e

crystal frequency = 11.0592 MHz.


g

Solution :
le

ORG 0000H
LJMP MAIN
ol

;Avoid using memory space allocated


; to interrupt vector
table
C

ORG 0023H
JNB TI, SKIP ; If TI
is low goto SKIP
u

MOV SBUF, A ;Transfer data serially


ad

CLR TI ;Clear TI
RETI :Return to main program
:
SKIP
iln

CLR RI
;Clear RI
RETI ;Return to main program
m

ORG 10OH
MAIN :
MOV P2, OFFH ;Configure P2 as an
Ta

MOV TMOD, #20H ;Initialize timer 1


input port
MOV TH1, #FDH ;Load count
in mode 2
MOV SCON, #40H
to get 9600 baud rate
:Select
MOV IE,#10010000B
serial mode
;
Enable serial interrupt
SETB TRI ;Start timer 1
MOV A, P2
:Read data from port 2
MOV SBUF,A
;Send the first byte serially
BACK: MOV A, P2
MOVP0, A
;Read data fromport 2
;Send it to port 0
SJMP BACK
Repeat
END

TECHNICAL PUBLICATIONS
an up-thrust for
knowledge
<br>

Page 152 of 446

UNIT I : 8051 MICROCONTROLLER

TWO MARKS QUESTIONS WITH ANSWERS


Name any four additional hardware features

g
Q.1 available in microcontrollers when
compared to microprocessors.

in
:
AU May-04
Ans.: The microcontroller has built-in

er
ROM, RAM, parallel I/0, serial I/O,
timer /counters and a clock circuit.

e
Q.2 Write the memory capacity of microcontroller 8051.

in
:
AU Dec.-08
Ans. :
The memory capacity of microcontroller 8051 is 64 kbytes.

ng
Q.3 What are, the flags available in 8051 ? AU May-09 :

OR What are fE
the flags supported by 8051 microcontroller ? AU :Dec.-19

Ans. The flags available in 8051 are CY (Carry flag), AC (Auxiliary carry flag), OV
: :
O
(over flow flag) and P (Parity flag).

Q,4 What is meant by SFR in 8051 ? Give an example. AU: May-09, 17


e

Ans. The group of registers, implemented to perform special function and are located
:
g

immediately above the 128 bytes of RAM are called special function registers for
le

on.
example, all port registers, TCOM, SCON, IE, IP, and so
ol

Q.5 Give the memory size of 8051 microcontroller. AU: May-10


C

memory and 64 kbytes of data


Ans. :
The 8051 can access. upto 64 kbyte program
memory.
u

1.3.1)
details of PSW of 8051. (Refer section ÅU May-10, 14
ad

Q.6 Give the


(Refer section 1.1)
Compare microprocessor and microcontroller.
Q.7 AU May-18
iln

8051 microcontroller ? AU : May-12


Q.8 What are the applications of
Some applications of
:
Microcontrollers are more preferred in embedded products.
m

Ans.
microcontroller are :
Ta

Accounting systems
Calculators
Data acquisition systems
•Game machines
• Mobile systems Complex industrial controllers
Military applications
Traffic light control systems
Communication systems microcontroller.
Q,9 SFRs in 8051
Explain the significance of
Ans. : The
group of registers, implemented
to perform special function and are located
immediately are called special function registers. They are
128 bytes of RAM
above the port, parallel ports and interrupt control.
responsible for operation of ALU, timer, serial

(3 - 73)
<br>

Page 153 of 446

Embedded Systems and loT Design 3-74 UNITI

Q.10 What is mean by microcontroller ?


Ans. : A device which contains the microprocessor with integrated peripherals like
memory, serial ports, parallel ports, timer/counter, interrupt controller, data acquisition
interfaces like ADC, DACis called microcontroller.
AU ;
Q.11 List the features of 8051 microcontroller. (Refer section 1.2) May-12,16, Dec.-17

g
in
Q,12 State the function of RS1 and RSO bits in the flag register of Intel 8051

microcontroller ?

er
Ans. : RS1 and RS0 are bank selection bits. They are used to select working register

e
bank of 8051 as given below:

in
0
00 Bank •0 1
Bank 1

ng
• Bank 2 • 3
10 11 Bank
0,13
Q.14 Explain the function of the PSEN pin of
fE
Give the alternate functions for the port pins of port3. (Refer Table 1.3.2)
8051.
AUMay-14
O
Ans. :
PSEN :PSEN stands
for program store enable. In 8051 based system in which
an external ROM holds the program code, this pin is connected to the OE pin of the
e

ROM.
g

Q.15 Explain the function of the EÃ pin of 8051. AU May-14


le

:
Ans. EA : It stands for external access. When the EA pin is connected to Vcc,
ol

program fetched to addresses 0000H through OFFFH are


directed to the internal ROM
and program fetches to addresses 1000H through FFFFH are directed to external
C

ROM/EPROM. When the EA pin is grounded, all


addresses fetched by program are
directed to the external ROM/EPROM.
u
ad

Q.16 Explain the 16-bit registers DPTR of 8051 or


what is a function of DPTR ?
AUMay-18
Ans. :
DPTR : It stands for data pointer. DPTR consists
iln

of a high byte (DPH) and a


low byte (DPL). Its function is to hold a 16-bit address. It may
be manipulated as a
m

16-bit data register or as two independent 8-bit registers. serves as a


It base register in
indirect jumps, lookup table instructions and external data transfer.
Ta

Q.17 Explain the function of the SP register of 8051.


Ans. : SP : It stands for stack pointer. SP is a 8-
bit wide register. It is incremented
before data is stored during PUSH and CALL instructions.
The stack array can reside
anywhere in on-chip RAM. The stack pointer is initialised to 07H after a reset. This
causes the stack to begin at location 08H.
Q.18 Name the special function registers available in 8051.
Ans. :
The special function registers available in 8051 are :

Accumulator B Register
Program Status Word.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 154 of 446

Embedded Systems and loT Design


3-75 UNITI

Stack Pointer.
Data Pointer.
Port 0
Port 1
Port 2 Port 3
Interrupt priority control register. Interrupt enable control register.
Q.19 How is stack implemented in 8051 ?

g
in
:
Ans. The 8051 LIFO Stack can reside anywhere in the internal RAM. It has 8 bit
:

stack pointer to indicate the top of the stack using PUSH and POP instructions.

er
During PUSH the SP is incremented by one and POP the SP is decremented by one.

e
Q.20 What is the maximum frequency of the clock signal that can be counted by

in
8051 counter ?

ng
Ans. : The maximum frequency of the clock signal that can be counted by 8051 counter
is 1/12 x crystal frequency.
Q.21 What are the features of ROM and RAM in 8051
fE microcontroller ?
O
Ans. : The 8051 has 128-byte internal RAM. It is accessed using RAM address register.
The internal RAM of 8051 is organized into three distinct areas
:
e

Register Bank Bit addressable • General purpose.


g

The 8051 has 4 kbyte of internal ROM with address space from 0000H to OFFFH. It is
le

or
programmed by manufacturer when the chip is built. This part cannot be erased
altered after fabrication. This is used to store final version of the program. It is accessed
ol

using program address register.


C

Q,22 What is the function of program counter in 8051 ?


u

memory
Ans. : The 8051 has a 16-bit program counter. It is used to hold the address of
ad

location from which the next instruction is to be fetched.


over microprocessor.
List the advantages of microcontroller
iln

Q.23
over microprocessor are
:

Ans. :
The advantages of microcontroller
m

peripheral support they provide single chip


Because of built-in
Ta

microcontroller system.
Less hardware required.
Less hardware increases reliability.
access time.
Supports internal memory which reduces
AU: Dec.-12
Which ports of 8051 are bit addressable
?
Q.24
- 1, port 2 and port 3 are bit addressable.
Ans. :
AIl ports of 8051 port 0, port
MHz. What is the range of frequency that
Q.25 A given 8051 chip has a speed of 16
?
can be applied to the XTAL and XTAL pins
1 2

- an up- thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 155 of 446

Embedded Systems and loT Design 3-76 UNITI

Ans. : The range of frequencies that can be applied to the XTAL 1 and XTAL 2 pins is
1
MHz to 16 MHz.
Q.26 Compare the 8051, 8031 and 8751 microcontroller. (Refer table 1.2)
Q.27 What happens in power down mode of 8051 microcontroller ?
Ans. :
In the Power Down Mode (PD = 0), the CPU puts the whole chip to sleep by

g
turning off the oscillator. In case if it is running from an external oscillator, it also gates

in
off the path to the internal phase generators, so no internal clock is generated even if
the external oscillator is still running. The on-chip RAM, however, saves its data, as

er
long as Vcc is maintained. In this mode the only Ice that flows is leakage, which is

e
normally in the micro-amp range.

in
Q.28 What are on-chip resources ? List those available in the 8051 microcontroller.

ng
AU: Dec.-10
:
Ans. The advance microcontrollers are supported
with on-chip peripherals such as
program memory, data memory, parallel ports, PWM
clock), Timers/counters, Serial ports,
fE output, ADC, RTC (Real time
IC interface and so on. These are known as
on-chip resources. The resources available in 8051 are:
O
• 4096 byte on-chip program memory
e

128 bytes on chip data memory


g

32-bit bi-directional I/O lines


le

Multi-mode serial port


ol

• Two multi-mode 16-bit


timers/counters
C

Q.29 Quantify the number


of register banks in 8051 and say
which bank is currently in use. (Refer how the CPU knows
u

section 1.3.1)
Q.30 Justify your choice AU : Dec.-10
ad

between UV-EPROM and flash EPROM


in an 8051 microcontroller application. for an external ROM
Ans. : Flash EPROMS can AU: Dec.-10
iln

be erased electrically with selective erase


UV-EPROMS cannot facility. However,
be erased electrically, they
need around 20 minutes to erase need ultraviolet light source. EPROMS
m

EPROM is more preferable and entire EPROM is erased at a time. Thus


during development stage. However,, flash
Ta

ready we can use EPROM as an external memory. once the product 15


Q.31 What do you understand
by bit addressable RAM
(Refer section 1.4.1.2) in 8051 microcontroller
?
Q.32 What is the AU : Dec.-10
function of R registers in 8051
(Refer section 1.4.1.1) microcontroller ?
AU
: May-13
Q.33 What is the purpose of overflow
flag in 8051 microcontroller
(Refer section 1.3.1) ?
AU: Dec.-13

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 156 of 446

Embedded Systems and loT Design


3-77
UNITI
Q.34
List the on-chip peripherals
of 8051 microcontroller. (Refer
section 1.3)

a Mention the size of DPTR


and stack pointer in 8051 microcontroller.
AU: May-11|

(Refer section 1.3)


E AU My-11 &
List the alternative functions
assigned to Port 3 pins of 8051 microcontroller.
(Refer section 1.3.2)

g
AU,:May-11
a37 What is program status word of
8051? (Refer section 1.3)

in
AU :
May-12
038 Mention the purpose of PSEN
and EA in 8051 microcontroller.

er
(Refer section 1.3.2)

e
0.39 What is meant by PSW ? (Refer section 1.3)
AU: Dec.-15

in
0.40 State any four inbuilt features of 8051 microcontrollers.

ng
(Refer section 1.2) :
AU Dec.-18
Q.41 What is the use of PSW ?
AU: Dec.-16
Ans. : PSW (Program Status Word) is fE
used to determine whether or not to execute
conditional instructions. In case of 8051, it is also
used to select the working register
O
bank.

Q42 What is the significance of PSEN and EA pin in 8051 microcontroller ?


e

(Refer section 1.3.2)


g

AU Déc.16
le

Q43 What is the time taken to execute MUL instruction in 8031 ?


(Refer section 2.5.4)
ol

AU May-05
Q44 Give the PSW setting for making register bank 2 as default register bank in
C

8051 microcontroller ? (Refer program 2.10.9) AU June-07


u

Q45 What is the operation carried out when 8051 executes the instruction MOVC A,
ad

@A+ DPTR ? (Refer section 2.3.2) AU:Dec-07

46 Name any four bit manipulation instructions in microcontroller 8051.


iln

(Refer section 2.6) AU .May-08

47 How can you perform multiplication using 8051 microcontroller ?


m

(Refer section 2.5.4) ÂU: May-08


Ta

0 Write the /O related instructions in microcontroller 8051.


AU :
(Refer section 2.3) Dec.-08, 11, 14
Q.49
What is output of the program ?

MOVR0,A
XRL A, #3FH
AU :
XRL A, RO June-09
Ans. :
The contents of A will be 3FH and contents of R0 will be
the initial
register
contents
of A.
Q,50 section 2.8.2) AU :
June-09, May-17
Explain about the instruction DJNZ. (Refer

TECHNICAL PUBLICA
TIONS - an up-thrust for knowledge
<br>

Page 157 of 446

Embedded Systems and loT Design 3-78 UNITI

Q.51 Write an 8051 program to divide two 8-bit numbers.


(Refer program 2.10.10) AU :Dec.-09
Q.52, What are the uses of LCALL and LJUMP instructions of 8051?
(Refer section 2.8) AU': Dec.-09

Q.53 List the different types of 8051 instructions.


(Refer sections 2.2, 2.3, 2.4 and 2.5) AU : May-10

g
Q.54 What are the various operations performed by boolean variable instructions of

in
8051 ? (Refer section 2.6) AU :May-10, 11

er
Q.55 Explain DJNZ instructions of Intel 8051 microcontroller ?
Ans.: 1.DJNZ Rn, rel : Decrement the content of the register Rn and jump if not zero.

e
in
2. DJNZ direct, rel : Decrement the content of direct 8-bit address and jumpif
not zero.

ng
Q.56 Write a program using 8051 assembly language to change the data 55H stored

:
fE
in the lower byte of the data pointer register to AAH using rotate instruction.
Ans. MOV DPL, #55H
O
MOV A, DPL
RL A
e

Q.57 Specify the single instruction, which clears the most


significant bit of B
g

register of 8051, without affecting the remaining bits.


le

Ans. :
Single instruction, which clears the most significant
bit of B register of 8051,
ol

without affecting the remaining bit is CLR B.7.


Q.58
C

Explain the contents of the accumulator


after the execution of the following
program segments :
u

MOV A, #3CH
ad

MOV R4, #66H


ANL A, R4
iln

:
Ans A =3C
R4 = 66
m

A = 24
Ta

Q.59 Write a program to load accumulator A, DPH


and DPL with 30H.
: MOV A, #30
Ans.
MOV DPH, A
MOV DPL, A
Q.60 Write a program to subtract the contents of R1
of Banko from the contents 0
RO of Bank2.

Ans. :
MOV PSw, #10
MOVA, RO

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 158 of 446

Embedded Systems and loT Design UNIT I

3-79

MOV PSW, #00


SUBB A, R1
Q,61 List the 8051 instructions that affect the overflow flag.
Ans. :
ADD, ADDC, DIV, MUL, SUBB
Q.62 List the 8051 instructions that always clear the carry flag.

g
Ans. : CLR C, DIV, MUL

in
Q.63 List the 8051 instructions that affect all the flags.

er
Ans. :
ADD, ADDC and SUBB

e
Q.64 What are the addressing modes supported by 8051 ? AU:Det.09;17, May13

in
Ans. :
The addressing modes supported by 8051 are :

ng
1. Register addressing 2. Direct byte addressing 3. Register indirect

4. Immediate 5. Register specific


fE 6. Index

Q.65 What does the mnemonics "LCALL" and "ACALL" stand for ?
O
AUS Dec.12
(Refer section 2.8.3)

Give an example for DA instruction of 8051 microcontroller.


e

Q.66
AUDec12
g

(Refer section 2.5.5)


in 8051
functions performed by JBC and CJNE instructions
le

Q,67 State the


microcontroller. (Refer section 2.8.2) AUMay14
ol

program to clear the accumulator and add 3


Q.68 Write an 8051 assembly language
C

2.10.24) AU péc-i2
to the accumulator 10 times. (Refer example :

Q.69 What is the operation of the given 8051


microcontroller instructions
u

AU May-11
XRL A, direct ? (Refer section 2.4)
ad

Q.70 Write a program to find 2's


compiement using 8051.
AUMay16
iln

(Refer program 2.10.6)


8051 microcontroller.
Q.71 Mention any four data transfer instructions of
m

(Refer section 2.3)


yes, how ? Give an example.
Ta

in 8051 ? If
Q.72 Can single bit of a port be accessed FAU': Dec.19
(Refer section 2.6)
sequence of 8051 interrupts ?
Q.73 Write the vector address and priority AU June-o7
(Refer section 3.7.2)
in the SCON register of 8051 ?
Q.74 What is the function of SM2 bit FAUDe.07
(Refer section 3.6)
in microcontroller 8051.
Q.75 Name the interrupts available AU: May-08, Dec-08, 13.

(Refer section 3.7)

- an up-thrust for knowledge


TECHNICAL PUBLICATIONs
<br>

Page 159 of 446

Embedded Systems and loT Design 3- 80 UNITI

Q.76 Write a delay routine for 1 millisecond using timer 0 of 8051 for 12 MHz crystal
frequency. AU : June-07

Ans. :
Crystal frequency = 12 MHz
12
T=
12x106 =1 us
i.e. the counter counts up every 1 1s. Out of many 1 us intervals, we have to
make a 1 ms delay.

g
in
We need 1 ms/1 is = 1000 clocks

N = 65536 - 1000 = 64536 = FC18H

er
We have to load TH with FCH and TL with 18H.

e
in
Program:
MOV TMOD, # 10H

ng
DELAY: ;Timer 1, Model
MOV TL1, # 18H ;
TL1 = 18H, Timer 1 lower byte register
MOV TH1, # FCH TH1 = FCH, Time 1 higher byte register
fE
SETB TR1 ; Start timer 1
REPEAT: JNB TR1, REPEAT Monitor timer flag 1 till it becomes 1.
O
CLR TR1 ;
stop timer 1
CLR TF1 ;Clear time 1 flag
e

RET ;Return
to main program
g

Q.77 Explain the register IE format of 8051. (Refer Fig.


3.7.2)
le

Q.78 List the interrupt sources in 8051 microcontroller.


AU May-14, Dec-15
ol

Ans.:
The interrupts are:
C

External interrupt 0 IE0 0003H


u

Timer interrupt 0. TFO


ad

000BH
External interrupt 1 IE1 0013H
iln

Timer interrupt 1 TF1 001BH


m

Receive interrupt RI 0023H


Ta

Transmit interrupt TI 0023H


Q.79 How the RS-232C serial
bus is interfaced to TTL logic device
: ?
Ans. The RS-232C signal voltage
levels are not compatible with
Hence for interfacing TTL devices to RS-232C TIL logic leves
serial bus, level converters are used. T
popularly used level converters are MC 1488
and MC 1489 or MAX 232.

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 160 of 446

Embedded Systems and loT Design


3-81 UNITI

Q.80 Define SBUF register in 8051 and


mention its use.
:
Ans. SBUF is an &-bit register dedicated for serial
communication in 8051. Its address
is 99H. It can be addressed like any other register in 8051.
Writing to SBUF loads data
to be transmitted and reading SBUF accesses
received data,
Q.81 Explain the use of interrupt enable register in 8051 microcontroller.
Ans. : The interrupt enable register in 8051

g
microcontroller allows individually
enabling and disabling of all interrupt sources in 8051.

in
Q,82 What register keeps track of interrupt priority in the 8051 Explain.

er
?
:
Ans. Interrupt priority control registers keeps track
of interrupt priority in the 8051.

e
Each interrupt source can also be individually programmed to one

in
of two priority levels
by setting or clearing a bit in interrupt priority control register.

ng
A low-priority interrupt can itself be interrupted by a high-priority
interrupt, but not by
another low priority interrupt. A high-priority interrupt can't be interrupted
fE by any
other interrupt source.
Q,83 Mention the registers used for serial communication in 8051 microcontroller.
O
(Refer section 3.6) AU Dec.-14
e

Q.84 Write the function of TMOD register in 8051 microcontroller. (Refer section 3.3.1)
g

AU Dec.-13,15
le

Q.85 Explain the interrupts of 8051 microcontroller. (Refer section 3.7) AU: Dec-16
ol

Q.86 Draw the flowchart for programming of serial port of 8051. (Refer section 3.6)
C

AU Deç.-11
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 161 of 446

UNIT II

4 Embedded System Design

g
in
e er
in
Syllabus

ng
Embedded System Design Process - Model Train Controller

fE
O
Contents
4.1 Embedded System Design Process. Dec.-13,16, 21, May-21, Marks 13
e

4.2 Model Train Controller Dec.-12,16,21, May-13,21,


g

Marks 16
le

April -14,
ol
C
u
ad
iln
m
Ta

(4 - 1)
<br>

Page 162 of 446

Embedded Systems and loT Design 4-2 Embedded System Desian

4.1 Embedded System Design Process AU :


Dec-13,16, 21, May-21
Embedded systems are specialized computer systems designed to perform
dedicated functions or tasks within a larger system and desigring
them requires a
structured approach.
• In this section, we aim to provide the
various steps involved in the process of

g
designing embedded systems and also discuss the methodology or
the systematic

in
approach used in designing embedded systems.

er
Design methodology refers to the set of principles,
guidelines and best practices
guiding the entire design process. It involves decisions

e
about the choice of
hardware components, software development

in
techniques, testing procedures and
more.

ng
Importance of design methodology
• A design methodology
reasons :
fE
in embedded system design is important
for three main
1. Ensuring completeness
and optimization : It acts as a
O
or scorecard, ensuring comprehensive checklist
that every essential aspect of
meticulously addressed. the design process is
e

This includes optimizing system


conducting thorough functional performance and
g

testing to verify that


specifications. it meets the required
le

2. Facilitating CAD tool


development: It allows for
ol

computer-aided design the creation of


tools. These tools can automate
C

design process, making it more efficient various aspects of the


the design process into and less error-prone. Breaking
well-defined steps down
u

step-by-step approach to within a methodology a


automating or semi-automating enables
ad

3. Enhancing team these tasks.


communication and
involve interdisciplinary coordination : Embedded system projects
iln

teams with diverse


communication and skills and expertise.
coordination among team Effective
success members are essential
m

of such projects. A for the


common language well-defined design
for team members. methodology serves as a
Ta

task sequences and It clearly defines roles,


expectations, facilitating responsibilities,
members can better smooth collaboration.
understand their Team
should expect from others individual contributions,
at specific stages what they'
upon completing their assigned and what deliverables to
tasks. provide
Major steps in embedded system
design process
Fig. 4.1.1l shows the major steps
in the embedded
shown in Fig. 4.1.1, there are system design process. As
two approaches :
Top-down and Bottom-up.

TECHNICAL PUBLICATIONS -
an up-thrust for
knowledge
<br>

Page 163 of 446

Embedded Systems and loT Desian


4-3 Embedded System Design

Requirements Requirements

Specification Specification

g
in
Architecture Architecture

e er
Components

in
Components

ng
System integration System integration
fE
(a) Top-down design (b) Bottom-up design
O
Fig. 4.1.1
• In the top-down approach of the embedded system design process, the sequential
g e

stages involved :
le

The process begins with understanding and


:
System requirements
documenting the system requirements. This phase sets the goals and
ol

functionalities the embedded system must achieve. It provides a broad


C

overview of what the system needs to do.


u

Specification : The specification outlines how the system should behave and
ad

what specific functions it needs to perform.


Architecture development : Once the specification is in place, the design
iln

process moves on to developing the system architecture. The architecture


or modules. It
defines the system's structure in terms of large components
m

to meet the
outlines how these components interact and work together
Ta

specified behaviors and functions.


next stage involves
Component design With the architecture in place, the
:

up the system. This includes


designing the individual components that make
components that may be
both software modules and any specialized hardware
required.
on the designed components, the complete
System integration : Finally, based
This phase involves
embedded system is built through system integration.
components into a cohesive and
assembling all the hardware and software
functional system.
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 164 of 446

Embedded Systems and loT Design 4-4 Embedded System Design

In contrast to the top-down approach, the bottom-up approach starts with


individual components and gradually builds the system.
Necessity of bottom-up design
Bottom-up design approach is necessary because, in
many cases, designers may
process will unfold.
not have perfect insight into how later stages of the design
decisions made at

g
They might face uncertainties or challenges that could impact

in
earlier stages.
on predictions of future
Decisions made early in the design process are based

er
memory
events : How quickly can we make a certain function run ? How much

e
our estimates are
will we need ? How much system bus capacity do we need If
?

in
incorrect, we may have to backtrack and change our earlier decisions
to reflect the

ng
new facts into account.
Comparison between top-down and bottom-up design fE
Sr. No. Parameter Top-down design Bottom-up design
O
1. Starting point Begins with a top-level Starts with individual
components or small
e

modules, often at a detailed


g

level.
le

2
Progression Designers break down the Individual components are
system into smaller gradually integrated to form
ol

components and sub-systems. a larger system.


C

3. Challenges It may require adjustments if It can be less structured and


initial assumptions change may demand careful
during design. coordination to ensure that
u

components integrate
ad

seamlessly.
4
Advantage It offers structure and clarity, Allows for early testing and
iln

making it suitable for adaptation, making it useful


well-defined projects. for evolving or uncertain
m

project details.
Table 4.1.1 Comparison between top-down and bottom-up
Ta

design
Goals of embedded system design
In embedded system design, i's essential to consider three major goals :
Manufacturing cost : Minimizing production expenses without compromising
quality.
Performance : Achieving efficient operation and meeting deadlines.
Power consumption : Designing for energy efficiency, especially in
battery-powered systems.
Balancing these goals is crucial for successful design.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 165 of 446

Embedded Systems and loT Design


4-5 Embedded System Design

Tasks need to be perform at every step in the design process


In the design process, several recurring tasks
need to be performed at each step to
ensure the system meets its goals :
. Analysis A critical design analysis must assess how it aligns
with the
specified requirements at every stage.
. Refinement : The design must be refined to incorporate additional details.

g
Verification : The design should undergo rigorous verification to confirm that

in
it still aligns with all system goals, including cost-effectiveness, speed

er
and
other performance metrics.

e
in
4.1:1 Requirements

ng
• The requirements phase is the initial stage of the design process, which captures
system's information for use in creating the architecture and components.
fE
During this phase, designers gather information by engaging with clients,
end-users and other relevant parties. The goal is to understand the purpose and
O
functionality of the system or product.
e

• Later, these requirements are refined into a specification that contains enough
g

information to begin designing the system architecture.


le

to consider
When designing and specifying an embedded system, it's essential
ol

both functional and nonfunctional requirements. Since only function requirements


are insufficient, capturing functional and nonfunctional requirements becomes
C

necessary for creating a comprehensive and well-defined system specification.


u

Nonfunctional requirements
ad

requirements.
Table 4.1.2 lists the typical nonfunctional
iln

Nonfunctional requirements
m

'The system's speed is vital, affecting user satisfaction


Performance
and overall cost.
Ta

Performance may be combination of soft


time
performance measures, such as the approximate
a user-level function and hard
required to perform
deadlines for completing a specific activity.

Manufacturing expenses comprise the cost of}

Cost components and assembly.


costs include labor
Nonrecurring engineering (NRE)
costs.
and other system design

PUBLICATIONS. an up-thrust for knowledge


TECHNICAL
<br>

Page 166 of 446

Embedded Systems and loT Design 4-6


Embedded System Design

Physical size and weightDepends upon the application.


Power consumption Power is crucial for battery-powered systems and is
as well.
also often essential for other applications
• It is specified in terms of battery life.

g
Table 4.1.2 Typical nonfunctional requirements

in
Validâting a set of requirements is a psychological effort because it necessitates

er
understanding what people desire and how they convey those demands.

e
• A mock-up is an excellent technique to refine at least the user interface element of

in
a system's needs. In a restricted demonstration, the mock-up may employ canned

ng
data to simulate functionality, which may be executed on a PC or a workstation.
However, it should provide the consumer with a comprehensive understanding of
fE
how the system will be utilized and how the user might react to it. Physical,
nonfunctional representations of products can also provide clients with a better
O
understanding of features such as size and weight.
e

Functional requirements
g

• Functional requirements for an embedded system outline what the system should
le

do and describe its specific functionalities and features.


ol

The typical functional requirements include :


C

Input / output handling : Define how inputs are processed and what outputs
are generated.
u

Data processing:Specify data manipulation, calculations and storage.


ad

Communication : Describe how the system interacts with other devices or


iln

systems.
. User interfaces:Detail user interface elements and interaction
workflows.
m

Control and automation : Explain how the system


controls physical processes
Ta

or devices.
Error handling : Define how errors
and exceptions are managed.
Security : Specify security features and access control.
• The functional requirements
provide a clear and comprehensive understanding
what the embedded system is expected to achieve. of

Requirements form
Requirements analysis for large systems can
process. To facilitate be a challenging and time-consuming
this complex task, beginning with a
format for capturing essential information straightforward and clear
about system requirements is ofter

TECHNICAL PUBLICATIONS®
an up-thrust for knowledge
<br>

Page 167 of 446

Embedded Systems and loT Design 4-7 Embedded System Design

beneficial. This approach helps understand the core aspects of what the system
needs to achieve.
One common technique for this purpose is to use a simple requirements
methodology, such as a requirements form. This form serves as a structurd
checklist for assessing the fundamental characteristics of the system.

g
Requirements form for GPS moving map system

in
• Let us see the requirements for a

er
GPS moving map system. The
Tilak Road
moving map is a handheld

e
device that displays a map of the

in
User's current
terrain around the user's current location

ng
location-the map updates as the
user and the device move. The Latitude: 18.50
Longitude:73.85
fE
device determines its location
using GPS, satellite-based
O
navigation system. Fig 4.1.2
might represent the moving map Fig. 4.1.2 Moving map display
e

display.
g

Table 4.1.3 shows the requirements form for GPS moving map system.
le

Requirement form General description


ol

Entries Requirements
C

Sr. No.

GPS moving map Name of the project


Name
u

Consumer grade moving Brief one or two-line


ad

Purpose
map for driving use. description of the system
iln

3. Power button, two control Types of data Analog,


Inputs or
buttons. digital mechanical inputs
m

Types of I/0 devices


4 LCD display 480 x 272, 5", Buttons, Displays etc.
Outputs
Ta

Show major roads; display More detailed description of


5.
Functions current latitude and what the system does.
longitude of current user When, the system receive an
location.
input, what does it do ?
How do user interface inputs
affect these functions ?
How do different functions
interactwwwww

-
TECHNICAL PUBLICATIONs an up-thrust for knowledge
<br>

Page 168 of 446

Embedded Systems and loT Design 4-8 Embedded System Design

6. Performance Updates Screen within Computational time


0.2 seconds upon movement constraints. It should be
identified early to ensure
that the system works
properly.
7
Manufacturing cost 1500/ Cost of the hardware
Components. It has a

g
substantial influence on

in
architecture.
Battery powered or plugged

er
8
Power Battery powered, 150 mW
into the wall.

e
9 Physical size and No more than 2" x 5.5" Give some insight into the

in
weight 150 gms system's physical dimensions
and weight to aid in making

ng
some design decisions.
Table 4.1.3 Requirements form for GPS moving map system
fE
4.1.2 Specifications
O
Specification acts as a contract between the customer and the architects. It is more
precise description of the system.
e

• Specification must be carefully written so that it correctly reflects the customer's


g

requirement.
le

Specification may include functional and non-functional elements.


ol

Well - defined specification phase is essential to avoid costly and time-consuming


C

mistakes in the later stages of system development. Two


crucial aspects of a
well-defined specifications are :
u

Clear and understandable : A good specification should be clear and


ad

understandable ernough that someone can review it


and verify that the system
being developed meets the specified requirements
iln

and aligns with the


customer's expectations.
m

Unambiguousness : The specification should also be


unambiguous, mearing
that it leaves no room for confusion or misinterpretation.
Ta

precisely understand what they are expected to Designers need to


build based on the
specification.
• The specification
phase serves as a roadmap for designers
the final product meets the intended and helps ensure e
requirements and is of high quality.
Skipping or neglecting this phase can lead to
problems that are difficult an
expensive to rectify in the later stages of the
project.

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 169 of 446

Embedded Systems and loT Design 4-9 Embedded System Design

For example, the specification of the GPS system would. include several
components :
Data from the GPS satellite.
Map data details.
User interface description.

g
Customer requested operations.

in
Background processes and tasks the GPS system must perform to ensure its

er
smooth operation.

e
UML (Unified Modeling Language) is a visual language used for modeling and

in
describing specifications.

ng
4.1.3 Architecture Design
fE
The primary purpose of system architecture is to describe how the system will
implement the functions outlined in the specification. It defines how the various
O
components of the system willwork together to achieve the desired functionality.
The architecture serves as a plan for the overall structure of the system. It outlines
e

the high-level design and organization of the system, providing a blueprint for
g

how different parts will interact and collaborate.


le

It precedes the detailed design of individual components.


ol

• Fig. 4.1.3 shows a block diagram of sample system architecture for the moving
C

map, highlighting necessary operations and information flows between them.


u
ad

GPS Search Renderer Display


iln

receiver engine
m
Ta

User interface
Database

Fig. 4.1.3 GPS moving map block diagram

The block diagram shown in Fig. 4.1.3 is abstract in


nature. It does not specify
on a CPU or by
which operations will be performed by software running

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 170 of 446

Embedded Systems and loT Design 4- 10 Embedded System Design

special-purpose hardware. However, it describes how to implement the functions


described in the system specification.
It highlights the separation of searching the topographic database and rendering
(drawing) the results for display. This separation allows for the potential execution
of these functions in parallel, which can result in smoother screen updates.

g
After creating an initial architecture without diving into implementation details,

in
it's best to refine the system block diagram into two separate diagrams : One for

er
hardware- and one for software. This separation helps maintain a clean and clear
design before specifying the detailed hardware and software components.

e
Fig. 4.1.4 shows the hardware and software architectures for the moving map.

in
ng
GPS receiver
Memory
fE Location
O
User
CPU Display Tímer
interface
e

Frame
buffer
g

Panel Database
Renderer Pixels
le

|Input /Output search


Bus
ol

(a) Hardware architecture


C

(b) Software architecture


Fig. 4.1.4
u

The hardware diagram includes a


ad

central CPU, surrounded by memory


devices. It specifically mentions and I/0
two types of memory :
displayed pixels and a program/data memory A frame buffer for
iln

for general CPUuse.


The software diagram closely
resembles the system block
m

timer to manage button inputs diagram but introduces a


from the user interface and
Screen. data rendering onto the
Ta

4.1.4 Designing Hardware and Software


Components
The architectural description
specifies which components are
component design effort required. Tne
creates components
specifications. that match the architecture and
The components will generally
include hardware (FPGAs,
software modules. boards, etc.) and

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 17l of 446

Embedded Systems and loT Design 4- 11 Embedded System Design

Some of the components are ready-made. For example - CPU, memory chips
and
many others. Some components can be modified from existing designs
and others
must be designed from scratch.
• In the moving map system, although a specialized component, GPS receiver can
often be acquired as a pre-designed standard component.
Standard topographic databases are available and using them in system

g
development is practical. Standard software modules can be employed to access

in
these databases efficiently. This saves design time and provides advantages such

er
as predefined data formats and data compression
techniques, which can enhance
performance in specialized functions like data decompression.

e
in
• While standard components are useful, custom-designed components may still be
necessary. This includes designing Printed Circuit Boards (PCBs) to connect

ng
integrated circuits and custom programming to meet specific system requirements.
fE
• Custom software modules are often required to ensure proper real-time operation
and memory optimization. Developers must use their expertise to manage memory
O
efficiently.
• Power consumption is critical in specific applications, like moving map software.
e

Developers must carefully plan memory access to minimize power usage, as


g

memory transactions can be a significant source of power consumption.


le
ol

4.1.5 System Integration


C

After building the individual components, the process of putting them together to
create a working system is called system integration. This phase involves more
u

as intended.
than simply connecting components; it ensures they function together
ad

Bugs are often found during system integration; effective planning can help
identify and resolve these bugs efficiently. Building the system in stages and
iln

can simplify bug detection.


running carefully selected tests
m

or
Early detection and resolution of simple bugs are crucial because more complex
Ta

tested.
obscure bugs may only become apparent when the system is rigorously
system in
During the architectural and component design phases, designing the
to ensure a smoother
phases and testing functions independently is essential
integration process and robust testing.
computing
Some of the challenges associated with system integration in embedded
are -
system. These
System integration often reveals problems within the embedded
and it is
issues can range from hardware conflicts to software bugs
wrong.
challenging to identify exactly what is
TECHNICAL PUBLICATIONs an up-thrust for knowledge
<br>

Page 172 of 446

Embedded System Design


Embedded Systems and loT Design 4- 12

limited
These problems can be because embedded systems typically have
debugging capabilities compared to desktop systems.
causes of problems can
Even when issues are identified, determining the root
be complex.
facilities during the
Careful planning and incorporating appropriate debugging

g
design phase can simplify system integration.

in
er
Review Questions

e
1. Discuss the importance of design methodology.

in
process with a suitable diagram. AU: Dec.-13, Marks 10|
2. Explain the embedded system design

ng
3. Describe top-doron and bottom-up design approaches.
EAU Dec:-21; Marks 2
4. Compare and contrast top-dozwn and bottom-up design. fE AUMay-21;- Marks 13
5. Demonstrate the goal of design methodology in detail.
O
6. Describe the nonfunctional requirements of embedded systems.

7. List the functional requirements of embedded systems.


e

8. Analyse the requirements for designing a GPS moving map in the embedded system design proces.
g

AU Dec.-16,. Marks 8
le

9. List the tuo important aspects of well-defined specifications.


ol

10. List various components of the specification of the GPS system.


sanple system architecture for the moving map.
C

11. Dratv and explain the block diagram of the


12. Explain the hardvare and software architectures for the moving map.
u

13. Discuss the designing hardware and software components for embedded systems.
ad

14. What do you mean by system integration ?


15. Discuss the challenges associated with system integration.
iln

4.2 Model Train Controller AU Dec.-12,16,21, Maý-l3,21, April -14


m

• To study the UML, here we consider the simple model train controller. As usual
Ta

for reactive embedded systems, the model railway contains various sensors
actors.
• Fig. 4.2.1 shows model train control system. Control
box is attached to the e
and user sends message to the train. Control box contains throttle, emergency
button etc. (See Fig. 4.2.1 on next page)

Two rails of the track provide electrical power can send
to
signals to the train over the tracks by modulating
train. The control box
the power supply voltage.

TECHNICAL PUBLICATIONs -
an up-thrust for knowledge
<br>

Page 173 of 446

Embedded Systems and loT Design 4- 13 Embedded System Design

The control panel sends packets over the tracks to the


receiver on the train. The
train includes analog electronics to sense the bits being transmitted and a control
svstem to set the train motor's speed and direction based on those commands.
. Error Correction Code (ECC) is provided with packet to rectify transmission
errors.
.

g
The model train cannot send commands back to the user, so it is a one-way

in
communication system.

e er
in
receiverMotor

ng
Power
fE
supply
O

Console
g e
le
ol

Address Command ECC


Header
C

Fig. 4.2.1 Model train control system


u

4.2.1 Requirements
ad

train control system.


Basic requirements for the model 1
iln

a) Console to control 8
trains on track.
directions (Forword and Reverse)
Throttle with at least 63 levels in both
m

b) to
atleast 8 level to adjust responsiveness of the train
Inertia control with
Ta

)
commanded changes in speed.
d) Emergency stop button.
scheme for sending error-free messages.
e) Error detection system.
requirement form for the model train controller
T'able 4.2.1 shows the
Requirements
Sr. No. Entries
Model train controller
Name trains
Control speed of up to eight model
Purpose running on one track
ww

PUBLICATIONS® - an up-thrust for knowledge


TECHNICAL
<br>

Page 174 of 446

4- 14 Embedded System Design


bedded Systems and loT Design

Inputs Throttle, inertia setting, emergency stop


button, train number

4. Outputs Train control signals

5
Functions Set engine speed based on inertia settings;
respond to emergency stop

g
at least five times
Performance Can update train speed

in
6.
pe second
P

er
7
7, Manufacturing cost 2500/

e
Power 10 W, plus into wall

in
9. Physical size and weight The console should be large enough to use
a
with two hands and around the size of

ng
regular keyboard; the weight is 1 kg.
fE
Table 4.2.1 Requirement form for the model train controller system

4,2.2 Digital Command Control (DCc)


O
Digital command control is a mechanism for controlling locomotives and therefore
e

trains, in a more realistic fashion. The National Model Railroad Association


g

developed the Digital Command Control (DCC) standard to support interoperable


le

digitally controlled model trains.


ol

• DCC does not specify the control panel,


CPUtype, programming language
many other features of an actual model railway system.
C

The standard focuses on


system design characteristics required for interoperability.
u

The data signal oscillates between two voltages around


the power supply voltage
ad

According to DCC standards, bits are encoded in the


time between transitions, n0
by voltage levels. A 0 is at least 100 1s while a 1 is nominally 58 us.
This D
iln

illustrated in Fig. 4.2.2.


m

0
Ta

-Time

->100 us

58 us
Fig. 4.2.2 Bit encoding in DCC
• To keep the DC value constant,
the durations of the high (above nominal
and low (below nominal voltage) sections of a voltas
bit are equal. The specification
gives the acceptable variations in bit times
that a conforming DCC receiver n
to
be able handle.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

of 446
Page 175

Embedded Systems and loT Design


4- 15 Embedded System Design

In addition to specifying the timing between transitions for encoding bits, the DCC
standard also defines
Allowable transition times for signals.
, How individual
bits are combined into packets.
Meaning and purpose of essential packets.
.

g
The basic packet format can be expressed as a regular expression : PSA (sD) + E,

in
where

er
P (Preamble) is a sequence of at least ten 1 bits. The command station should
send at least 14 of these 1 bits.

e
in
S
(Packet Start Bit) is a 0 bit.

ng
A (Address Data Byte) specifies the unit's address.
s (Data Byte Start Bit) is a 0 bit.
fE
D (Data. Byte) may contain an address, instruction, data or error correction
information.
O
E
(Packet End Bit) is a 1 bit.
e

The instruction data byte in DCC communication carries multiple pieces of


g

:
information
le

a
Bits 0
-3: Represent 4-bit speed value.
ol

Bit 4 Additional speed bit, interpreted as the least significant speed bit.
:
C

Bit 5 : Indicates the direction, with 1 representing forward and 0 representing


reverse.
u

8: Bits are set at 01 to show that this instruction provides both speed
ad

-7
Bits
and direction information.
iln

• The error correction data byte is generated by taking the bitwise


exclusive OR
(XOR) of the address and instruction data bytes.
m

frequently. Packets
DCC standard recommends that command units send packets
Ta

5 milliseconds between them.


should be sent with a separation of at least

4.2.3 DCc Components


:

(DCC) system consists of several parts


The most basic Digital Command Control run it
a command station, a booster, a decoder and a power supply to
A throttle,
all. Fig. 4.2.3 shows the DCC system setup.
also known as the cab, is often handheld. It is
:
Throttle The throttle controller, or
to control model train locomotives. It features a knob, lever
the device used
adjustment, braking, lighting
buttons to command various actions like speed
PUBLICATIONs - an up-thrust for knowledge
TECHNICAL
<br>

Page 176 of 446

Embedded System Design


imbedded Systems and loT Design 4- 16

(Cab)

Command station

g
Motor

in
"Cab bus"

e er
Booster
Decoder

in
ng
fE
O
e

Fig. 4.2.3 DCC system setup


g

control and sound effects. Throttles transmit these commands to the command
le

station for locomotive control.


ol

• Command station : The command


station is the real intelligence of the DCC
system. Its job is to collect inputs from throttles
C

and send those signals to the train


via a booster. It creates a digital packet and
forwards it to the booster.
u

:
Booster The booster receives commands
from the command station, amplifies
ad

them and delivers them to the track.


Decoder: A small electronic device installed inside a
iln

locomotive responsible tor


responding to commands from the command
station. As per the command
decoders determine how much power to
m

deliver to the motors, activate souna


effects and control lighting features.
Ta

4.2.4 Conceptual Specification


Digital Command Control (DCC)
specifies critical aspects of model
systems to ensure interoperability; train contro
it intentionally leaves room for flexibility.
flexibility allows model railroaders to
complement the DCC specification Th
own details to suit with thelt
their specific needs and preferences.
A conceptual specification can be a
useful starting point to create a more
specification. This conceptual specification detaile
doesn't necessarily match wha
commercial DCC controllers do
but serves as a foundation for understandin
system design concepts.
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 177 of 446

Embedded Systems and loT Design 4-17 Embedded System Design

Commands are instructions generated by the command unit. These instructions


typically include information about locomotive speed, direction, lighting, sound
and other functions. Commands are converted into packets by a train control
system.
. Packets are data units
transmitted over the rails to control the locomotives. In
DCC, packets may contain multiple commands or data elements. Additionally,

g
the
DCC standard recommends resending packets if a packet is dropped or corrupted

in
during transmission. Hence, commands and packets may not have a one-to-one

er
correspondence.

e
• Let us model the train control system. It consists of two major subsystems : the

in
command unit and the train-board component, as shown in Fig. 4.2.4.

ng
Command
fE
O
g e
le

Set_inertia Estop
Set speed
ol

value: integer value: unsigned-integer


C
u

Fig. 4.2.4 Class diagram for the train controller messages


ad

These subsystems each have their own internal structure. The basic relationship
iln

between them is illustrated in Fig. 4.2.5.


Fig. 4.2.5 shows a UML collaboration diagram for major subsystems of the train
m

a model
controller system. It illustrates the relationship between subsystems in
Ta

the command
train control system. It emphasizes the communication flow between
unit and the train's receiver.

sequence. message type


1..n: command
console receiver

Pig. 4.2.5 UML COllaboration diagram for major subsystems of the train controller
system

PUBLICATIONws - an up-thrust for knowledge


TECHNICAL
<br>

Page 178 of 446

Embedded Systems and loT Design 4-18 Embedded System Design

The arrow shows that the command unit transmits a series of packets to the train's
receiver. Since the console transmits all the messages, we have numbered the
arrow's messages as 1.n. The notation on the arrow indicates both the type of
message transmitted and its sequence in a flow of messages.
Of course, the messages are transmitted over the railroad. However, the track does

g
not appear in the schematic since it is passive and not a part of the computer.

in
Major subsystems roles

er
• Let's break down the command unit and receiver into their major components.
The major components and their functions for the console (command unit) and the

e
train receiver are as follows :

in
For the console (command unit) :

ng
Read the state of the front panel on the command unit
Format messages. fE
Transmit messages.
• For the train receiver
O
:

Receive messages.
e

Interpret messages, considering current speed


g

and inertia setting.


Control the train motor.
le

Console system class diagram


ol

Fig. 4.2.6 shows the UML class


diagram for console system.
C

console
u
ad

1
1

pane! |fomatter transmitter


iln
m

1
Knobss
sender
Ta

=physical object
Fig. 4.2.6 Console system
The console class is represented class diagram
by
These classes must describe some three classes, one for each major component
behaviors, but for the time
on their basic characteristics : being, we will focus
Console class describes the
command uni's front panel,
and hardware for interfacing with including analog knob5
. Formatter class : digital parts of the system.
Creates a bitstream for the
required message.
TECHNICAL PUBLICATIONs -
an up-thrust for knowledge
<br>

Page 179 of 446

Embedded Systerms and loT Design 4-19 Embedded System Design

Transmitter class : Sends the message along the track.


Panel class : Describes analog knobs and interface hardware.
As shown in Fig. 4.2.6, some special classes ending the name of each with an
asterisk represent analog components. These are :
Knobs*: It describes the actual analog knobs, buttons and levers on the

g
control panel.

in
Sender* :It describes the analog electronics that send bits along the track.

er
system class diagram
Train

e
• Fig. 4.2.7 shows the UML class diagram for train system.

in
ng
train set

fE
train
O
receiver motor
interface
g e

controler
le

detector pulser
ol
C

Fig. 4.2.7 Train system class diagram


u

a It

Train class : This class appears to represent the overall functionality of train.
ad

makes use of three other classes to


manage its operations.
converts
Receiver class : This class receives analog signals from the track and
iln

them into a digital format.


m

Controller class : The controller class is responsible for interpreting commands


motor.
and determining how to control the
Ta

signals to
Motor interface class This class defines how to generate analog
:

control the motor.


on the track and
Detector class : It is responsible for detecting analog signals
converting them into a digital format.
motor control signals
Pulser class : It translates digital commands into analog
to control the motor speed.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 180 of 446

Embedded Systems and loT Design 4- 20 Embedded System Design

4.2.5 Detailed Specification


4.2.5:1 Analog Physical Objects
The detailed specification adds the behaviours and attributes to the classes defined
in the conceptual specification. Fig. 4.2.8 shows the class diagram of analog
physical objects with behaviors and attributes in the train control system.

g
in
pulser

er
pulse-width: unsinged-integer
direction: boolean

e
knobs*

in
train-knob: integer
speed-knob: integer

ng
inertia-knob: unsigned-integer
emergency-stop: boolean
sender detector*
set_knobs()
fE
O
send-bit( ) read-bit(): integer
Fig. 4.2.8 Classes describing analog
physical objects in
e

the train control system


g

The Panel contains three knobs : Train


number (which train is currently being
le

controlled), speed (which can be positive or


negative) and inertia. It also has one
emergency stop button.
ol

Motor speed is controlled by pulse


width mnodulation. It is a method to control
C

power by adjusting the


width of on-off pulses in a signal. This is illustrated in
Fig. 4.2.9. The pulser class specifies
u

the pulse width as an integer value


binary value to control the direction. and the
ad

Pulse
iln

Voltage width
(V)
m

Period Fast
Ta

I
Motor)

Slow

Time
Fig. 4.2.9
The sender and detector classes are
straightforward: They send and a b1
respectively. receive

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 18l of 446

Embedded Systems and loT Design 4-21 Embedded System Design

425.2 Panel and Motor Interface


. Fig. 4.2.10
shows the classes for the panel and motor interfaces.

pane! motor-inteface

g
speed: integer

in
:
Panel _active() boolean
Train
_number() : integer

er
speed() : integer
inertia() : integer
estop() boolean

e
new-settings()

in
ng
Fig. 4.2.10 Class diagram for panel and motor interface
• Panel class : It defines behaviors for the controls on the panel. Instead of using
fE
internal variables, it directly reads values from the physical device. The
"new-settings" behaviour uses the "set-knobs" behavior of the knobs class to
O
change knob settings when the train number setting changes.
• Motor interface class : This class defines an attribute for speed that other classes
e

can set. The controller's role is to adjust the motor's speed incrementally to achieve
g
le

smooth acceleration and deceleration.


• These classes establish the software interface to their respective physical devices.
ol
C

4.2.53 Transmitter and Receiver SPECIAAN

ig. 4.2.11 shows the class diagram for the transmitter and receiver. They provide
u

the software interface to the physical devices that send and receive bits along the
ad

track. COPY
iln

EOR

Transmitter Receiver
m

current: command
new: boolean
Ta

send-speed(adrs: integer, speed: integer) read-cmd()


send-inertia(adrs: integer, val: integer) new-cmd( ): boolean
send-estop(ádrs: integer) rcv-type(msg-type: command)
rcv-speed(val: integer)
rcv-inertia(val: integer)

Fig. 4.2.11 Classes for the transmitter and


receiver

TECHNICAL PUBLICATIONs an up-thrust for knowledge


<br>

Page 182 of 446

Embedded Systems and loT Design 4- 22 Embedded System Design

• Transmitter class : This class is responsible for sending different types of


messages. It defines distinct behaviors for each message type and handles the
message formatting internally.
a
Receiver class : This class provides a "read-cmd" behavior, which is used to read
message from the tracks. It appears that this behavior can run continuously,

g
next
suggesting that the receiver constantly monitors the tracks and intercepts the

in
command when it becomes available.

er
4.2.5.4 Formatter

e
in
Fig. 4.2.12 shows the class diagram for the formatter class.

ng
Formatter

current-train: integer fE
current-speed[ntrains]: integer
current-inertia[ntrains]: unsigned-integer
O
current-estop[ntrains]: boolean

send-command( )
e

panel-active(): boolean
g

operate( )
le

Fig. 4.2.12 Class diagram for the formatter


class
ol

Formatter class : This class holds the current


C

control settings for all the trains. It


has an interface to the transmitter through the
"send-command" method. The
u

"operate" function is responsible for performing


the basic actions of the object.
ad

The formatter's main task is to repeatedly


read the panel's values, check if any
settings have charnged and send out
the appropriate messages when changes are
iln

detected.
A " panel-active " behavior returns true
m

whenever the panel's values do not match


the current values.
Ta

Formatter role during panel's operation


Fig. 4.2.13 uses a sequence
diagram to describe the formatter's role
operation. (See Fig. 4.2.13 on next page) during a panel
• As shown in Fig. 4.2.13,
the formatter periodically checks
whether settings or knob positions have the control panel to see
changed. These changes could be related
to the throttle, inertia, emergency
stop or train number.

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 183 of 446

Embedded Systems and loT Design


4-23 Embedded System Design

Knobs Panel Formatter Transmitter


Change in
Change in control settings Read panel
speed/ inertia /estop Panel settings
Panel-active
Read panel

g
Panel settings
Send Send-speed

in
Read panel Command

er
Panel setings, Send-inertia

e
Change in Send-estop

in
train number Read panel
Change in Panel settings

ng
train number New settings
Set knobs
fE
O
Fig. 4.2.13
• If the formatter detects a change in the control settings for the current train, it
e

decides to send a command. This command is sent to the transmitter, which is


g

responsible for transmitting control signals.


le

These commands are transmitted serially, meaning one bit at a time. This implies
ol

that each command takes some time to be transmitted completely. While the
C

transmitter.sends a command, the formatter monitors the control panel for any
further changes.
u

• If the formatter detects a change in the train number, it must take action to reset
ad

new train.
the knob settings to the appropriate values for the
iln

State diagram for formatter operate behaviour


• Fig. 4.2.14 shows the simplified state diagram for the formatter operate behaviour.
m

-
As showWn in the Fig. 4.2.14, behaviour
Ta

Idle
panel _active( )

New train number


Other

new settings()
send command()

Fig. 4.2.14 State diagram for the


formatter operate behaviour

TECHNICAL PUBLICATIONs- an up-thrust for knowledge


<br>

Page 184 of 446

Embedded System Design


Embedded Systems and loT Design 4- 24

Watches the panel for activity.


If the train number changes, updates the panel display.
Otherwise, causes the required message to be sent.
State diagram for panel-active behaviour
Fig. 4.2.15 shows the simplified state diagram for the panel-active behaviour.

g
Start

in
Panel: read_ knob)

e er
in
current_train currenttrain = train knob
T
update screen
train
knob changed = true

ng
Panel": reaad
speed()
fE
O
e

current_spaed current speed = throttle


changed= true
g

throttle
le
ol

Panel": read_inertia
C
u

current_inertla
current Jnertia interia
ad

knob
inertia_knob changed = true
iln

Panel": read_estop
m
Ta

current_estop
aurrent estop estop button value
estop button value changed = true

Retum changed

Stop

Fig. 4.2.15

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 185 of 446

Embedded Systems and loT Design 4- 25 Embedded System Design

4.2.5.5 Controller
Controller
Fig 4.2.16 shöws the class diagram for the
controller class. current-train: integer
current-speedntrains]: unsigned-integer
The receiver invokes "operate" behavior current-direction[ntrains]: boolean
current-inertia[ntrains]: unsigned-integer
when it receives a new command
message. The "operate" behavior examines

g
the contents of the received message. It operate()

in
utilizes the "issue-command" behavior to issue-command()

er
adjust the speed, direction and inertia
settings based on the information in the Fig. 4.2.16 Class diagram for the

e
message. controller class

in
State diagram for controller operate behavior

ng
• Fig. 4.2.17 shows the simplified state diagram for the controller operate behavior.

Wait for
Command
read command fE issue_command()
from receiver
O
Fig. 4.2.17 State diagram for the controller operator behaviour
e

Fig. 4.2.18 shows a sequence diagram for a set-speed command. received by the
g

a
train. It describes the operation of the controller class during the reception of
le

set-speed command.
ol

Controller Motor-interface Pulser


C

Receiver
u

new-cmd
ad

rcv-type
rcv-speed Set-pulse
iln

Set-speed
m

Set-pulse
Ta

Set-pulse

Set-pulse

Set-pulse

read-cmd operate

train
Fig. 4.2.18 Sequence diagram for a set-speed command received by the
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 186 of 446

Embedded Systems and loT Design 4-26 Embedded System Design

• To determine the message's nature, the controller's operate behavior must carry
out several behaviors. A series of commands must be sent to the motor to
smoothly adjust the train's speed once the speed command has been parsed.
Fig. 4.2.19 shows the refined class diagram for the train controller commands. We
need to specify -

g
The number of bits used to determine the message type. Here, three bits are

in
used to determine message types, allowing for eight possibilities, with ive

er
codes unused.
The number of bits used to determine data field lengths. This depends on the

e
resolution requirements for speed and inertia.

in
Number of parity bits. A single-parity bit is used for basic error detection.

ng
Command
fE
O
type: 3-bits
address: 3-bits
parity: 1-bit
g e
le

Set-speed Set-inertia Estop


ol

type = 010 type = 001


type = 000
C

value: 7-bits value: 3-bits


u

Fig. 4.2.19 Refined


ad

class diagram for the train controller


Review. Questions
commands
iln

1. Describe the various stages involved


in the design of train controller.
m

2. What is DCC ? AU:Dec.-12. Marks 16


3. Write a short note on
Ta

DCC components.
4. Explain the basic packet
format specified by the
5. Which are the major DCC.
subsystems of model
6. train control system ? Explain
Drw and explain the UML class their roles.
7. diagram for console system.
Draw and explain the
UML class diagram
8. Explain in detail the for train system.
design steps of modern
train controller with
suitable diagrams.
9. With simple system namely, AU : May-13, Marks
a model 16
systems ? train controller, how
vill you use the
IML to moue
AU: April-14, Marks 8
TECHNICAL
PUBLICATIONS®
- an
up-thrust for knowledge
<br>

Page 187 of 446

Embedded Systems and loT Design 4-27 Embedded System Design

10. How are the conceptual specifications and detailed specifications written in UML language to
design the model train controller. |AU : Dec.-16, Marks 8
11. Explain how detailed specification differs from conceptual specification.
12. Assuming the design of model train controller, draw a state diagram for a behaviour that sends the
command bits on the track. The machine should generate the addres, generate the correct message
type, include the parameters and generate the Error Correcting Code (ECC).

g
AU: Dec.-21; Marks 13

in
13. Design a model train controller with a suitable diagram and explain. AU:May-21, Marks 13

er
14. Draw and explain a sequence diagram to describe the formatter's role during a panel operation.

e
15. Draw and explain a sequence diagram for a set-speed command received by the train.

in
16. Draw the refined class diagram for the train controller commands.

ng
fE
O
g e
le
ol
C
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 188 of 446

UNIT II

5 ARM Processor

g
in
er
e
in
Syllabus

ng
ARM Processor - Instruction Set Preliminaries.

Contents
5.1 Introduction
fE
O
5.2 Preliminaries
5.3 ARM Processor
e

5.4 Instruction Set


g

ARM Assembly
5.5 Implementation of C Language Statements using
le
ol
C

CPFCIAAN
u
ad

COPY
iln

FOR
m
Ta

(5-1)
<br>

Page 189 of 446

Embedded Systems and loT Design ARM Processor


5-2 \

5.1 Introduction
Studying instruction sets is a fundamental aspect of understanding
set is
microprocessors and their role in computing systems. An instruction
essentially the set of machine-level instructions that a microprocessor can execute.
It serves as the bridge between high-level programming languages and the

g
can run.
hardware, allowing programmers to write software that the CPU

in
While high-level languages are preferred for programmning, the instruction set

er
remains essential for performance analysis. Understanding CPUinstructions allows
for efficient code optimization and exploring alternative ways to implement

e
in
functions.
• In this chapter, we focus on the ARM processor instruction set. ARM processors

ng
are a popular example in the world of microprocessors. They are known for their
energy efficiency and are commonly used in mobile devices, embedded systems
fE
and more. Learning about ARM's instruction set architecture provides valuable
knowledge for a wide range of applications.
O
5.2 Preliminaries
e

5.2.1
Computer architecture is a fundamental field in studying computers
and digital
g

systems. In this section, we will see the different types


of computer architecture
le

and the nature of assembly language.


ol

5.2.1 Computer Architecture Taxonomy


C

There are two fundamental types of computer


architecture: Von Neumann and
u

Harvard architecture. These two architectures


differ primarily in how they hande
ad

memory and data access.

5.2.1.1 Von Neumann Architecture


iln

Fig. 5.2.1 shows a block


diagram
m

for the computer with Von


Neumann architecture. It uses the
Ta

52.1.3
stored program concept. The CPU Address
program instructions and Data
data
share the same memory space, PC
often called "memory" or
"RAM Mem
(read-write memory)." Memory
Fig. 5.2.1 Von
Neumann architecture
It uses a single bus system for both
instruction fetch and data access. Cc
Thus, data and instructions are
same memory, one at a fetched from
time. This can be less efficient for tasks
when it comes to simultaneous instruction that could benen
fetching and data access.
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 190 of 446

Embedded Systems and loT Design 5-3 ARM Processor

The contents of read-write memory are addressable by location (memory address)


without regard to the type of data stored there. Each memory location has a
unique address and we can read from or write to that location regardless of
whether it contains program instructions, numeric data, text, or any other type of
information.
Execution of instructions occurs sequentially (unless explicitly modified), from one

g
instruction to the next.

in
The CPU has many internal registers that hold values that are used internally. The

er
program counter (PC) is one of the CPU registers that keeps track of the memory

e
address of the next instruction to be fetched and executed. It essentially points to

in
the next instruction in memory. When the CPU fetches an' instruction, the program
counter increments to point to the next instruction in sequence. This register

ng
allows for the sequential execution of instructions stored in memory.
fE
Separating instruction memory from the CPU is a fundamental characteristic
distinguishing a stored-program computer from a general finite-state machine.
O
5.2.1.2 Harvard Architecture
Address
e

• Fig. 5.2.2 shows block Data memory


g

Data
diagram for the computer with CPU
le

IR
Harvard Architecture. It has Address
PC
ol

separate memory spaces for Instructions Program memory


program instructions and data.
C

It uses distinct memory Fig. 5.2.2 Harvard architecture


u

pathways and storage for


instruction memory and data memory.
ad

access.
This separation allows simultaneous instruction fetching and data
iln

as
potentially improving performance, especially in real-time applications such
digital signal processing
m

Architectures
5.2.1.3 Comparison between Harvard and Von-Neumann
Ta

Parameter Harvard architecture Von-Neumann architecture

Memory Structure Uses separate memory for Uses a single memory space for both
progranm instructions and data.
instruction and data.
More complex to implement. Simpler to implement.
Complexity
faster execution of May experience slower instruction
Speed Offers
since it allows execution due to potential memory
instructions access conflicts.
simultaneous fetching of instructions
and data.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 191 of 446

Embedded Systems and loT Design 5-4 ARM Processor

Parallelism Instruction fetching can occur in Data and instructions are fetched
parallel with data memory access. from the same memory, one at a!
time.
Example Includes microcontrollers 1like the ncludes most desktop and laptop
PIC microcontroller series. computers.

g
5.2:1.4 Complex Instruction Set Computers (CISC)

in
Computer architectures can also be classified according to
their instructions and

er
how they are executed. This gives us two categories -

e
Complex Instruction Set Computers (CISC)

in
Reduced Instruction Set Computers
(RISC)

ng
CISC is an acronym for complex
instruction set computers or computing.
based on the concept of using very large If is
instruction set having simple as well as
fE
complex instructions and making
instruction set more flexible to
length as small as possible. keep program
O
• In CISC complex instructions may
take multiple cycles for execution.
CISC instructions vary
e

in size, often specify a sequence


require serial (slow) decoding algorithms. of operations, and can
g
le

They tend to have few registers,


and the registers may be special purpose,
restrict the way in which they can which
ol

be used.
• In CISC, there are many
instructions that support memory
C

we can add memory contents reference. For example,


to the registers.
CISC instruction sets are
u

. To add designed to take advantage


of microcode.
ad

the flexibility in the instruction


set, they support more
addressing modes. and complex
iln

Example of CISCs are :


Intel X86, Motorola 68000
series, DEC VAX,etc.
m

5.2.1.5 Reduced Instruction Set Computers (RISC)


Ta

RISC refers to Reduced


Instruction Set Computers
microprocessors are very different from CISC Or Computing. RISC
keeping the instruction set as microprocessors. RISC use
simple as possible to allow concept
program to be written using only the microprocessor's
simple instructions.
• The designer designed RISC
architecture considering following
1.A limited and simple instruction set. points :
2. A large number
of general purpose registers, or the use
to optimize register usage. of compiler technology
3. An enmphasis on optimizing the instruction pipeline.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

of 446
Page 192

Embedded Systems and loT Design 5-5 ARM Processor

:
eISC Instruction execution and characteristics
. In RISC processors, there is an one instruction per machine cycle.
RISC machine instructions are not complicated and can execute about as fast as,
microinstruction on CISC machines.
. The machine instructions are hardwired. These instructions are executed faster

g
than the instructions implemented with microinstructions.

in
.
This architecture encourages the optimization of register use, so that frequently

er
accessed operands remain in high-speed storage to implement register to register

e
operations. For this RISC processors provide multiple sets of registers.

in
• RISC processor provides limited number of instructions, which simplifies the

ng
design of control unit.
. use simple
RISC processor uses simple addressing modes. Almost all instructions
fE
register addressing.
simple instruction formats with fixed instruction length. The
O

RISC processors use
instruction length is aligned on word boundaries. Field locations, especially
e

opcodes are fixed.


g

Because of this, they provide following benefits:


le

can occur
• With fixed fields, opcode decoding and register operands addressing
ol

simultaneously.
unit.
C

• It simplifies the design of control


units are fetched.
Instruction fetching is optimized since word-length
u

RISC uses instruction pipelining.


To speed-up instruction execution,
ad

etc.
RISCs are :
ARM, ATMEL, 8051 family, AVR, MIPS, PIC
Examples of
iln

D1:6 Comparison between RISC and ClSC


m

Sr. No. RISC CISC


Characteristics
Ta

Varies
1
Instruction size Fixed
1, 2,3 or 4
bytes
2 Instruction length 4 bytes
More
3

Number of Instruction Less


decode Serial (slow) to decode
Instruction decoding Easy (quick) to
from simple
5. Instruction sementics Almost always one simple Varies to
complex ; possibly many
operation dependent operations per
instruction

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

of 446
Page 193

ARM Processor
Embedded Systems and loT Design 5-6

Complex addressing modes Supports complex


6. Addressing modes
are synthesized in software. addressing modes.
Slow (depend on complexity
7. Instruction execution Medium
of instruction)
speed
8. By hardware. Simple By microprogram. Complex
Instruction execution
instructions taking one instructions taking multiple

g
cycle. cycles.

in
9
Registers Many,general purpose. Few, may be special
purpose.

er
10. Memory references Not combined with Combined with operations

e
operations, i.e., load/store in many different types of
architecture. instructions.

in
11. Hardware Simple. Complicated.

ng
12. Hardware design Take the advantage of Take the advantage of
focus implementations with one microcoded
fE
pipeline and no microcode. implementations.
13. Memory access Rarely. Frequently.
O
14. Instruction format Regular, consistent Field placement varies.
placement of fields.
e

15. Pipelined Highly pipelined. Not pipelined


g

Or less
pipelined.
le

16. Conditional jump Can be based on a bit Conditional jump is usually


anywhere in memory.
ol

based on status register bit.


17. Compiler Complicated.
C

Simple.
18. Examples ARM, 8051, ATMEL, AVR,
etc.
Intel X86, Motorola 68O00
u

series.
ad

Review Questions
iln

1. Explain the Von Neumann architecture.


m

2. Explain the Harvard architecture.


3. Give the comparison
betveen Von Neumann
Ta

and Harvard architectures.


4. State the characteristics
of CISC architecture.
5. Write a short note on RISC architecture.
6. Give the comparison between RISC
and CISC.

TECHNICAL PUBLICATIONS -
an up-thrust for
knowledge
<br>

Page 194 of 446

Embedded Systems and loT Design 5-7 ARM Processor

5.2.2 Assembly Language


522:1 Features of Assembly Language
Some common features of assembly languages are -
One instruction per line : Each line typically contains one instruction or

g
directive in assembly language. This makes it easier for humans to read and

in
understand the code.

er
Labels : Labels are used to give names to memory locations or code sections.
They appear in the first column. Labels are used for branching and

e
referencing memory addresses.

in
Instructions : Instructions are the actual operations that the processor will

ng
perform. They start in the second column to distinguish them from labels.
Instructions are represented using mnemonics that are specific. to the processor
fE
architecture.
Comments : Comments are used to provide explanations or notes about the
O
code. They are preceded by a designated comment character, which is usually
e

a semicolon () in the case of ARM assembly.


g

are
Assembler directives They, often referred to simply as "directives,"
:
le

commands or instructions in assembly language that provide guidance to the


are not
ol

assembler on how to process the source code. These directives


instructions for the CPU to execute; they control various aspects of the
C

memory
assembly process. Directives are typically used to define data, specify
u

allocation, control program flow and more.


ad

5222 Structure of ARM Assembly Module


for the assembler
iln

Assembly language follows a structured format to make it easier


toparse the code and translate it into machine code.
m

The following' code illustrates various parts of


an ARM assembly language module.
Ta

AREA ARMex, CODE, READONLY


:
Name this block of code ARMex
ENTRY
:
Mark first instruction to execute
start
MOV RO, #10
;
Set up parameters
Cabel
MOV R1, #3
;RO = RO + R1
ADD RO, RO, R1
stop :
Program ends with software interrupt instruction
SWI &11
;Mark end of file
Opcode END Comment
Operands
TECHNICAL PUBLICATIONS
- an up-thrust for knowledoe
<br>

Page 195 of 446

Embedded Systems and loT Design 5-8 ARM Processor

Application entry : The ENTRY directive declares an entry point to the program.
It marks the first instruction to be executed.
Application execution : The application code begins executing at the label start,
where it loads the decimal values 10 and 3 into registers RO and R1. These
registers are added together and the result placed in R0.

g
Application termination : After executing the main code, the application

in
terminates by executing software interrupt instruction to call interrupt service

er
routine.

e
Program end : The END directive instructs the assembler to stop processing this

in
source file. Every assembly language source module must finish with an END
directive on a line by itself. Any lines following the END directive are ignored by

ng
the assembler.
General instruction format for data processing instructions fE
Fig. 5.2.3 shows the general instruction format for data processing
instructions.
O
31 28 27 26 25 24 21 20 19 16 15 •
12 11
Cond 00 I OpCode S
e

Rn Rd Operand 2
g
le

Condition Destination register


field
ol

15 operand register
C

Set condition codes


0= do not alter condition codes
Operation code 1= set condition codes
u

Immediate operand
Opcode
ad

Mnemonic Operation
110= operand 2 is a register4 3
0000 AND Logical AND
Shift Rm 0001 EOR Logical exclusive OR
iln

0010 SUB Subtract


0011 RSB Reverse subtract
m

Second 0100 ADD Add


Shift applied to Rm operand register 0101 ADC Add with carry
0110
Ta

1 = operand 2 is an immediate value SBC Subtract with carry


0 0111 RSC Reverse subtract with carry
1000 TST
Rotate Imm Test
1001 TEQ Test equivalence
1010 CMP Compare
Unsigned 8 bit immediate value 1011 CMN Compare negated
Shift applied to imm 1100 ORR Logical (inclusive) OR
1101 MOV Move
1110 BIC Bit clear
1111 MNV Move not

Fig. 5.2.3 General format of data processing instructions

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 196 of 446

Embedded Systems and loT Design. 5-9 ARM Processor

Bits 28 - 31These bits are put aside for the condition field.
:

Bits 26 - 27 : These bits are 0 for process instructions.


• Bit 25 : Represents type of second operand.
2 is a
I=0:Operand register

g
I=1 Operand 2 is an immediate value
:

in
Bits 24 - 21:Opcode bits, as shown in Fig. 5.2.3.

er
Bit 20: If S = 0, flags are unchanged. If S = 1, flags are updated after execution of
the instruction according to the result.

e
Bits 16 - 19

in
• :
Represent the first operand register.
• Bits 12 - 15

ng
:
Represent the destination register.
Bits 0 - 11 :
(I = 0) Second register : fE
Bits 0 - 3 represent the second operand register and
bits 4- 11 specify the amount of shift/rotate and type of shift/rotate.
O
1) Immediate values : Bits 0 - 7 contain an immediate value, a number
I= & - 11
between 0 OXFF and bits specify the immediate operand rotate field is
e

-
a 4 - bit unsigned integer that specifies a shift operation on the 8 bit
g

immediate value.
le

Example : For the instruction ADDGT r0,r5,#10


ol

the cond field would be set according to the GT condition (1100), the opcode field
C

would be set to the binary code for the ADD instruction (0100), the first operand
Rd would be
register Rn would be set to 5 to represent r5, the destination register
u

set to 0 for r0, and the operand 2 field would be set to the immediate value of 1o
ad

5223 Rules for Labels in Assembly Language


iln

Each label name must be unique.


m

-
The names used for should consist of
uppercase and lowercase,
Ta

Alphabetic letters in both


Digits 0 through 9, and
(_), and
Special characters question mark (?), period (), at (@), underline
dollar sign ($).
The first character of the label must be alphabetic.
as labels in the program.
The reserved words must not be used

-
TECHNICAL PUBLICATIONS an up-thrust for knowledge
<br>

Page 197 of 446

Embedded Systems and loT Design 5-10 ARM Processor

5.2.24 ARM Data Formats


ARM processors support the following four data types :

Bit
Byte:8 bits.
Halfword : 16 bits (halfwords must be aligned to two-byte boundaries).

g
Word :32-bits (words must be aligned to four-byte boundaries).

in
• The data types used by the ARM can
be positive or negative.

er
Data format representation

e
There are several ways to represent a byte of data in the ARM assembler.

in
The
numbers can be in hex, binary, decimal, or ASCII formats.
Table 5.2.1 illustrates

ng
these formats.

Format fE
Representation style Example
Hex number Put Ox (or 0X) in front of the MOV R1 #0xA2
O
number
Decimal number
Nothing before or after it the MOV
e

R1, #34
number
g

Binary number Put 2 in front of the númber.


le

MOV R1, #2 1011


Octal number
Put 8_ in front of the number.
ol

MOV R1, #8 2467


Numbers in any base between 2
Put n in front of the number.
C

jand 9 MOVRI, #5 2431


MOV R1, #7 5163
ASCII haracter
u

Use single quotes


MOV R1, #2
ad

String Use double quotes


with DCB
directive
iln

Table 5.2.1 Illustrates


data representation formats
5.2.2.5 ARM Assembler
Directives
m

There are some instructions


Ta

part of processor in the assembly language program


instruction set. These which are not a
assembler, linker instructions are instructions
and loader. These are
assembler directives. referred to as pseudo-operationsto the
or as
.The assembler directives enable we to
assembles and lists. They act control the way
during in which a progran
generate any executable machine the assemnbly of a program
code. and do not

TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>

Page 198 of 446

Embedded Systems and loT Design 5-11 ARM Processor

AREA Directive
• The AREA directive instructs the assembler to define a new code or data section
of memory.
:
Format
AREA sectionname, attribute, attribute,

g
The memory can have attributes such as CODE, DATA, ReadOnly, ReadWrite, and

in
SO on.

er
Table 5.2.2 lists various attributes and their usage.

e
No. Attribute Usage

in
1. READWRITE Used to define an area of memory that can be read from

ng
and written to. The Assernbler puts the READWRITE
sections next to each other in the SRAM memory for
data storage. fE
2. READONLY Used to define an area of memory that can only be read
from. This section of the program it is by default for
O
CODE.
Used to define an area of memory used for executable
e

3. CODE
machine instruction.
g

Used to define an area of memory used for data, no


le

DATA
instruction (machine instructions) can be placed in this
ol

area.
C

5. COMMON Used to define an area of memory used for data, no


instruction (machine instructions) can be placed. Since it
is used for the program's data section, it is by default a
u

READWRITE memory. In ARM Assembly language, we


ad

"use this area to set aside SRAM memory for scratchpad


and stack.
iln

Used to define an area of memory to indicate how


6. ALIGN memory should be allocated according to the addresses.
m

Table 5.2.2
Ta

Examples :

AREA ASM PROG, CODE, READONLY


AREA PROG_CONSTS, DATA, READONLY
AREA PROG_VARIABLES, DATA,
READWRITE

ENTRY and END Directives


to a program.
The ENTRY directive declares an entry point
reached the end of a source
The END directive informs the assembler that it has
file.
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
<br>

Page 199 of 446

Embedded Systems and loT Design 5-12 ARM Processor

Example:
AREA ASM PROG, CODE, READONLY
ENTRY
LDR R1, =0x30 ; R1 = 0x30
MOV R2, #0x24 ;R2 = Ox24
ADD R3, R2, R1 ;R3 = R2 + R1

g
END

in
Note that, = sign used in the syntax to load R1 with Ox30. This is another way to
load immediate value in the register.

er
INCLUDE Directive

e
The include directive tells the ARM assembler to add the contents

in
of a file to our
program (similar to the #include directive
in C language).

ng
Assembler Data Allocation Directives
• Directives DCB, DCD, DCDU,
fE
DCW and DCWD are used to allocate memory
initialize them. The SPACE directive allocates memory and
without initializing it.
O
Directive
Description
e

DCB Allocates one or more bytes of memory,


g

contents of the memory. and defines the initial runtime


le

DCD and DCDU Allocates one or more


words of memory, aligned on four-byte
ol

boundaries, and defines the initial


DCDUis the same, except runtime contents of the memory.
that the memory alignment is
C

arbitrary.
DCW and DCWU Allocates one or more
halfwords of memory, aligned on
u

boundaries, and defines two-byte


DCWUis the same, exceptthe.initial runtime contents of the memory.
ad

that the mmory alignment is


arbitrary.
SPACE or FILL Reserves a zeroed block memory.
of The FILL directive reserves a
of memory to fill with a
iln

given value. block


EQU
m

The EQUdirective gives a


symbolic name to a
Ta

value or a PC-relative value. numeric constant, a register-relative


We can use EQU directive
to assign SFR addresses,
SO On. internal SRAM addresses
and
Example:
COUNT EQU Ox45

MOV R1, #COUNT ;R1 = Ox45


PORTB EQU 0xFO018 ;SFR Port B
address
L
TABLE EQU Ox20000100 ;Assign RAM
address to LTABLE
TECHNICAL PUBLICATIONSo
- an
up-thrust for knowledge
<br>

Page 200 of 446

Embedded Systems and loT Design 5-13 ARM Processor

RN Directive
. RN directive is used to define name for, a register. It does not set aside separate
storage for the name, but associates a register with that name.
:
Example
NUM1 RN R1 ;defineNUM1 as a name for R1
;define NUM2 as a name

g
NUM2 RN R2 for R2

in
SUM RN R3 ;define SUM as a name for R3

er
ALIGN Directive
• The ALIGN directive aligns the current location to a specified boundary (32-bit

e
word or 16-bit half-word) by padding with zeros or NOP instructions.

in
Examples:

ng
ALIGN 4 ;the next instruction is word (4 bytes) aligned

ALIGN 2 ;the fE
next instruction is half-word (2 bytes) aligned
ADR directive
O
To load registers with the addresses of memory locations we can also use the
ADR pseudo-instruction which has a better performance.
g e

Syntax : ADR Rn, label


le

Example :
ol

NUM EQU Ox20000100; Assign RAM address to NUM


ADR R2, NUM ;Loads R2 with the address of NUM
C

CODE16 Directive
u

The CODE16 directive instructs the assembler to interpret subsequent instructions


ad

as Thumb instructions.
iln

Review: Questions
m

the help of an example.


1. Explain the structure of an ARM assembly language module with
an assembler module.
Ta

Z. Explain the general form of lines in


3. State the rules for labels in ARM assembly language.
4. Write a note on ARM data formats.
directive.
O. What are assembler directives ? Explain AREA
6. Explain any four directives used in ARM assembly language
programming with'suitable examples.
assembler directives.
Describe the function of EQu, SPACE, ALIGN
assembler directives.
O. Describe the function of DCD, DCB, DCW
directive.
Explain the meaning of AREAand ENTRY
10. State the rules for labels in ARM assembly language.

PUBLICATIONSs - an up-thrust for knowledge


TECHNICAL
<br>

Page 201l of 446

Embedded Systems and loT Design 5- 14 ARM Processor

5.3 ARM Processor


5.3.1 Features of ARM Processor
The basic RISC architecture concept of the simple hardware with an instruction set
combined with a few key CISC features allow ARM processors to support
following features -

g
in
1. Load-store architecture
2. Fixed-length 32-bit instructions

er
3. 3-address instruction formats

e
4. High performance

in
5. Low code size

ng
6. Low power consumption
7. Low silicon area (small core
size)fE
8. It has control over both the Arithmetic
Logic Unit (ALU) and shifter in every
data-processing instruction to maximize the use of an ALU
and a shifter.
O
9. Supports auto-increment and
auto-decrement addressing modes to optimize
program loops.
e

10. Supports Load and


g

Store Multiple instructions to maximize


data throughput.
le

11. Supports conditional


execution of all instructions to maximize
throughput. execution
ol

'S3121 ARM Architecture


C

An ARM core is an engine within a system


u

that fetches ARM instructions from


memory and executes them.
ad

ARM cores are very small. Typically


they occupy a few square millimeters chip
of
iln

area.
With advances in modern VLSI technology,
it became possible to build additional
m

system. components such as memory,


cache memory management
application specific hardware on unit or
Ta

the same chip. Application


include signal processing specific may
hardware or further ARM processor cores. hardware
While designing a new system,
selecting the correct processor core
most critical decision. is one of the
5.3.2.1 ARM Core Dataflow Model
Fig. 5.3.1 shows the basic structure
of ARM core and how
different parts. data moves between

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 202 of 446

Embedded Systems and loT Design 5-15 ARM Processor

Data

Instruction Sign extend


decoder

g
in
Write Read

er
Register file
PC(r15) r0-15 Rd

e
Rn Rm Bbus

in
Bbus
Apus Barrel lshifter

ng
Acc Apus

MAC
ALU fE
O
Result bus
g e

Address Register
le
ol

Incrementer
Address
C

Fig. 5.3.1 ARM core dataflow model


is Von Neumann
core dataflow model shown in Fig. 5.3.1
u

• The ARM
implementation of the ARM.
ad

a RISC processor, it uses a load-store


Since ARM processor is basically
types, load and store. for
iln

architecture. This means, it has twO instruction


processor respectively.
transferring data in and out of the
m

memory to registers in the


LOAD : This instruction copies data from
Ta

processor core.
in the processor core to
STORE: This instruction copies data from registers
memory.
not include the instructions that directly
• The ARM processor instruction set does
is carried out only in registers.
manipulate data in memory. The data processing
Data bus
The data enters the ARM
core through the data bus. The data is either in the form
or a data item.
of an instruction opcode
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 203 of 446

5- 16 ARM Processor
Embedded Systems and loT Design

Since Von Neumann architecture is used, data itemns and instructions share the
same bus. This is in contrast with Hardvard architecture which uses two different
buses.
Instruction decoder
This unit decodes the instruction opcode read from the memory and then the

g
instruction is executed.

in
Register file

er
This is a bank of 32-bit registers used for storing data items.
Sign extend :

e
• The ARM core is a 32-bit processor. So most

in
instructions of the ARM processor
treat registers as holding signed or unsigned 32-bit values.

ng
When the processor reads signed 8-bit or 16-bit numbers from memory,
the sign
extend hardware converts these numbers to 32-bit values
fE and then places them in
a register file.
ALU (Arithmetic Logic Unit)
O
and MAC (Multiply-Accumulate Unit)
Most of the ARM instructions are two
operand instructions. The two source
e

registers Rn and Rm are used to store these


operands. These source operands are
read from the R, and Rm registers using
g

the internal buses A and B respectively.


le

The ALUor MACreads the operand


values from R, and Rm registers
via A and
ol

B buses respectively,
performs the operation and stores
internal C bus in destination register, the computed result via
C

Rd and then to the register


file.
The load and store instructions generate
address using ALUand stores
u

address register. it in the


ad

Address register
This holds the address generated
iln

by the load and store instructions


on the address bus. and places it
m

Barrel
. Theshifter
contents of the Rm register
Ta

alternatively can be preprocessed


shifter before applying as an input to the ALU. in the barrel
.A wide range of expressions and addresses can be calculated
shifter and ALU. using the barrel

Incrementer
For load and store instructions,
the incrementer updates the contents
address register before the processor core of the
reads or writes the next
from or to the consecutive memory location. register value

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 204 of 446

Embedded Systems and loT Design 5-17 ARM Processor

The processor core continues the execution of instruction. Only when an exception
or interrupt occurs, the normal execution flow is changed.

5.3.3 ARM Programmer's Model


The register. file in the ARM core contains all the registers, available to a
programmer. The currernt mode of the processor decides the availability of the

g
registers to the programmer.

in
er
5.3.3.1 Processor Modes
are active and the access rights to
• The processOr mode deternmines which registers

e
the cpsr register itself.

in
are protected or
In the ARM7, there are seven operating modes. These modes

ng
own register
exception modes which have associated interrupt sources and their
set. fE system level
Supervisor mnode (Default) This is protected mode for running
:
1.
enters this mode after
code to access hardware or run OS calls. The ARM7
O
reset.
2. FIQ (Fast Interrupt reQuest)
:
This mode supports high speed interrupt
e

handling.
g

: supports all other interrupt sources in a


3. IRQ (Interrupt ReQuest) This mode
le

system.
from an invalid memory location,
ol

an
: instruction or data is fetched
4. Abort If
an abort exception will be generated.
C

an ARM instruction, an undefined


5. Undefined
:
If a fetched opcode is not
u

instruction exception will be generated. we


run the application code. In the user mode
ad

6. User : This mode is used to Program Status Register) and


cannot change the contents of CPSR (Current generated. This mode is also
an exception is
iln

modes can only be changed when


known as Unprivileged mode. system tasks. It uses the
m

: is used for running operating


7. System This mode
same registers as user mode.
Ta

except user mode, are privilege modes.


• All the above modes, mode
modes, user registers r0
-
r7 are common. However, FIQ
For all operating each of the
rO - r7 registers by its own registers r8 to rl4. Similarly,
replaces the
have their own r13 and rl4 registers so that each operating mode has
other modes
and link register.
its own unique stack pointer

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 205 of 446

Embedded Systems and loT Design 5-18 ARM Processor

5.3.3.2 Programming Model

Fig. 5.3.2 shows the programming model of ARM processor.

User and
system

g
in
r1

r2

er
r3

e
r4

in
r5
Fast
r6 interrupt

ng
r7 request
r8 r8 fiq
r9_fiq
fE
r10 r10_fiq
O
r11 r11 fiq Interrupt
r12 r12 fiq request Supervisor Undefined Abort
e

r13 sp r13_fiq n3 irq r13_svc r13_ undef 13 abt


g

r14 Ir n4 fiq r14_irq r14 svc 14 undef 14 abt


le

r15 pc
ol
C

cpsr
spsr fiq spsr irq spsrsvc spsr undef spsrabt
u
ad

Fig. 5.3.2 Programming


model of ARM processor
The ARM processor has a total of 37
iln

can be classified registers. All registers are 32-bits


into two groups as, wide. They
m

General purpose registers


Special purpose registers.
Ta

5.3.3.3 General Purpose Registers


Registers r0 to r12 are
used as general purpose registers.
context, registers
rl3 to rl5 can also be used as general purpose
The general purpose registers hold
Depending upon
registers.
n
either data or an address.

TECHNICAL PUBLICATIONs
an up-thrust for knowledge
<br>

Page 206 of 446

Embedded SystemS and loT Desian


5-19 ARM Processor

S334 Speclal Purpose Registers


Registers r13 to r15, CPSR (Current Program Status Register)
and SPSR (Saved
Program Status Register) are the special purpose
registers.
Registers r13 to r15
. In user mode, registers r13 to r15 are labeled as r13 sp, r14 lr and r15 pc

g
respectively to differentiate them from other registers. The functions of these

in
registers are given below.

er
Stack pointer (r13 sp) : Register r13 is the stack pointer. It stores the top of
the stack in the current processor mode.

e
in
Link register (r14 Ir) : Register r14 is the link register. The processor stores
the return address in this register when a subroutine is called.

ng
Program counter (r15 pc) : Register r15 is the program counter and stores the
fE
address of the next instruction to be fetched from the memory by the
procesSor.
O
• It is used in most instructions as a pointer to the instruction which is two
instructions after the instruction being executed.
e

• All ARM instructions are four bytes long (one 32-bit word) and are always
g

aligned on a word boundary. This means that the bottóm two bits of the PC
le

are always zero, and therefore the PC contains only 30 non-constant bits.
ol

• It can often be used in place of one of the general-purpose registers ro to


C

r14, and is therefore considered one of the general-purpose registers.


However, there are also many instruction-specific restrictions or special
u

cases about its use. Usually, the instruction is unpredictable if r15 is used in
ad

a manner that breaks these restrictions.


iln

- r7
The Unbanked Registers r0
means that each of them refers to
Registers r0 to r7 are unbanked registers. This
m

processor modes.
the same 32-bit physical register in all
Ta

no special uses implied by the


They are completely general-purpose registers, with
a general-purpose
architecture, and can be used wherever an instruction allows
register to be specified.
The -
Banked Registers, r8 r14
Kegisters r8 to r14 are banked registers.
on the current processor
The physical register referred to by each of them depends
mode. Where a particular physical register is intended,
without depending on the
name (as described below) is used.
Current processor mode, a more specitic

PUBLICATIONS® an up-thrust for knowledge


TECHNICAL
<br>

Page 207 of 446

Embedded Systems and loT Design 5-20 ARM Processor

Almost all instructions allow the banked registers to be used wherever a


general-purpose register is allowed.
Out of 37 registers, 20 registers which are shöwn shaded in Fig. 5.3.2 are the
banked registers. Fig. 5.3.2 also shows which banked registers are used in which
mode. Banked registers of a particular mode are denoted by, r number_mode.

g
For example, supervisor, mode has banked registers r13_svc, rl4_SvC
and spsr_sve.

in
On the other hand, abort mode has banked registers r13-abt, r14-abt
and spsr-abt.

er
Registers r8 to r12 have two banked physical registers
each. The first group of
physical registers are referred to as r8_usr to r12_usr

e
and the second group as
r8_fiq to r12_fiq. The r8_usr to rl2_usr group is

in
used in all processor modes other
than FIQ mode, and the other is used in FIQ
mode.

ng
Registers r13 and r14 have six banked
physical registers each. One is used in User
and System modes, while each of the remaining
exception modes.
fE five is used in one of the five

The registers r0 to r13 are orthogonal.


O
This means, any instruction you can
apply to r0, you can equally well
apply to any of the r1 to r13 which
not the case with r14 registers. This is
and r15 registers.
g e

5.3.4 ARM CPSR


le

The current program status


ol

register (cpsr) is accessible


contains condition code
flags, interrupt disable in all processor modes. It
and other status and control bits, the current processor
C

information. mode,
Each exception mode also
has a saved program status
u

to preserve the value


of the cpsr when the associated register (spsr), that is used
ad

exception occurs.
Note User mode and system
mnode do not
exception modes. All have an SPSR, because
iln

UNPREDICTABLE instructions they are not


when executed in Userwhich read or write the SPSR are
mode or System mode.
m

• Fig. 5.3.3 shows


the format of the cpsr
and spsr.
Ta

Fields Flags Status


Extension
Control
Bits 31 28 27

2cv UNDEFINED
8 7 6 5 4

Condition
FT Mode
Functions
flags
Interrupt Processor
masks mode

Fig. 5.3.3 Format Thumb


of cpsr and spsr state
TECHNICAL PUBLICATIONS
an up-thrust for
knowledge
<br>

Page 208 of 446

Embedded Systems and loT Design


5-21 ARM ProOcessor

Control flags (Bits 0-7)


The control bits change when an exception arises and can be altered by
software
only when the processor is in a privileged mode.
Bits 0-4(Mode Select Bits) : Processor modes
These bits determine the processor mode.as shown in Table 5.3.1.

g
in
Processor mode Mode Select Bits [4 : 0]

er
Abort 1.0 111

e
Fast interrupt request 10001

in
Interrupt request 10010

ng
Supervisor 1001 1

System fE1111 1

Undefined 11011
O
User 10000
wwwwww..w
e

Table 5.3.1 Processor mode


g

Bit 5 (Thumb State Bit) :


le

• This bit gives the state of the core. The.state of the core determines which
ol

instruction set is being executed.


There are three instruction sets, ARM, Thumb and Jazelle. One of the three
C

instruction set is active when the processor is in ARM state, Thumb state and
u

Jazelle state respectively.


ad

:
Bits and 7 (Interrupt Masks)
on the ARM processor core:
There are two interrupts available
iln

Interrupt Request (IRO) and


m

Fast Interrupt Request (FIQ).


Ta

is controlled by bits 6 and 7 of


These are maskable interrupts, and their masking
7(1) controls IRQ.
CPSR. Bit 6(F) controls FIQ, and bit
request is masked, and
When a bit is set to binary 1, the corresponding interrupt
available.
when a bit is 0, the interrupt is
Condition code flags (Bit 28 - 31) :
most instructions to determine whether
These flags in the cpsr can be tested by
the instruction is to be executed.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 209 of 446

Embedded Systems and loT Design 5-22 ARM Processor

Bit 28 (Overflow flag, V)


• It is set in one of two ways :

For an addition or subtraction, V is set to 1 if signed overflow occurred.


regarding the operands and result as two's complement signed integers.
V.
"For non-addition/subtractions, is normally left unchanged.

g
Bit 29 (Carry flag, C)

in
• It is set in one of four ways :

er
For an addition, including the comparison instruction CMN, C is set to 1 if

e
the addition produced a carry (that is, an unsigned overflow),
and to 0

in
otherwise.
For a subtraction, including the comparison

ng
instruction CMP, C is set to 0 if
the subtraction produced a borrow (that
is, an unsigned underflow), and to 1
otherwise.
For non-addition/subtractions
fE
that incorporate a shift operation, C is set to
the
O
last bit shifted out of the value by
the shifter.
For other noi-addition/subtractions,
e

C is normally left unchanged.


Bit 30 (Zero flag, Z)
g

It is set to 1 if the result


le

of the instruction is zero (which


result from a comparison), and to often indicates an equal
ol

0 otherwise.
Bit 31 (Negative flag, N)
C

It is set to bit 31 of the


result of the instruction.
two's complement signed integer, If this result is regarded as a
u

then N = 1 if the result is


it is positive or zero. negative and N=0if
ad

5.3.5 Memory Organization


iln

• ARM7 processors
have a 32-bit address space,
m

4,294,967,296
(2) different memory locations. allowing them to address up to
means each
This
Ta

byte in memory. address refers to a


ARM7 uses byte
addressing, where each
memory. In address points to a
this scheme, the word 0 single byte of
2 is at location 8 and so on. is at location 0, word 1 is at location Wwora
4,
The Program Counter
(PC) in the ARM7 processor
absence of a branch is incremented
instruction. This is because by 4
each instruction is typically in
the
(32 bits) long in ARM
assermbly and 4 byte
the PC points to the next
instruction.

TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>

Page 210 of 446

Embedded Systems and loT Design 5-23 ARM Processor

ARM7 processors can be configured to operate in either little-endian or big-endian


mode. These two modes determine how multi-byte data (e.g., 16-bit or 32-bit
values) is stored in memory.
Little-Endian Mode: In little-endian mode, the lowest-order byte (the least
significant byte) of a multi-byte value is stored in the lowest memory address. The

g
following bytes are stored in increasing memory addresses. This is the default

in
mode for ARM processors.

er
Big-Endian Mode : In big-endian mode, the highest-order byte (the most

e
significant byte) of a multi-byte value is stored in the lowest memory address. The

in
following bytes are stored in increasing memory addresses.

ng
address

Ox103 78 Ox103 12
Ox102 56 Increasing
fE
Ox102 34
Ox101 34 Ox101 56
O
Ox100 12 Ox10078
Big endian Little endian
e

Fig. 5.3.1 Word, 0x12345678 stored in memory in big-endian and little-endian modes
g
le

The ARM memory map


ol

Fig. 5.3.2 shows the ARM memory organization. It shows the small portion of the
memory each byte location has a unique number with 'little-endian'
C

where
assignment. (When the lower byte addresses are used for less significant bytes of
u

the word, addressing is called little-endian).


ad

Bit 31 Bit 0
iln

Half word 23 22 21 20
m

19 18 17 16
Ta

15 14 13 12 Word

11 10 9 8

7 6 5 Half word

1
3 2

Byte 3 Byte 2 Byte


1
Byte 0

memory organization
Fig. 5.3.2 ARM memory with a "litle-endian'

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 21 I of 446

Embedded Systems and loT Design 5-24 ARM Processor

5.3.6. Basic ARM Addressing Modes


Some of the simple ARM addressing modes are:
1. Register
2. Immediate

g
3. Register indirect (indexed addressing mode)

in
Register addressing mode

er
The register addressing mode uses of registers to hold the data to be manipulated.

e
Example :

in
MOVR3,R2 ; copy the contents of R2 into R3

ng
Immediate addressing mode
In the immediate addressing mode, the source operand is a constant,
immediately after the opcode. fE and it comes

Example:
O
MOV R1,#0x35 ; load Ox35 into R1.

Register Indirect Addressing Mode (Indexed


e

addressing mode)
In the register indirect addressing
g

mode, the address of the memory location


where the operand resides is held
by a register.
le

Example :
ol

STR R1, [R2] ; store value of R1


into the memory.location pointed by R2.
C

Review:Questions
u
ad

1. List the features of ARM processors.


2. Explain ARM core
data flow model with a neat diagram.
iln

3. Draw and explain the


ARM programmer's model.
4. List the special purpose
registers of ARM processor.
m

5. Explain different processor modes of


ARM processor.
Ta

6. Explain the programmer's


model of ARM processor
with complete register sets
7. Explain registers used under available.
various modes.
8. Explain the various fields
in the Current Program Status Register
(CPSR).
9. What is Big-Endian and Little-Endian ?
10. Writea note on ARM memory
organization.
11. Explain some basic addressing modes
of ARM.

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 212 of 446

Embedded Systemns and loT Design 5-25 ARM Processor

5.4 Instruction Set


5.4.1 Load and Store Instructions
ARM uses a load-store architecture for memory access which means that only
load/store (LDR and STR) instructions can access memory.

g
In ARM processors, data must be moved from memory into registers before being

in
operated on. This means that incrementing a 32-bit value at a particular memory

er
address on ARM would require three types of instructions (load, increment, and
store) to first load the value at a particular address into a register, increment it

e
within the register, and store it back to the memory from the register.

in
This means that the instruction set will only process (add, subtract, and so on)

ng
values which are in registers.

5.4.1.1 Basic Forms of LDRISTR Instructions fE


LDR Rd, [RX] instruction
O
This instruction loads Rd with the contents of four consecutive memory locations
whose starting location is pointed at by Rx register. The contents of Rx is
an
e

address of memory between Ox00000000 to OxFFFFFFFF.


g

Example : Assume that R1 = 0x2000 0100 and locations Ox2000 0100 through
le

Ox2000 0103 contents 0x10, Ox25, 0x12, OxBO, respectively.


ol

LDR R2, [R1]


C

as
After execution of the above instruction, register R2 is loaded with OxB0122510,
u

shown in Fig. 5.4.1.


ad

R2 OxBO Ox12 0x25 Ox10


iln
m

Memory
Ta

Ox2000 0104
Ox2000 0103OxBO
Ox2000 0102 Ox12
Ox2000 0101 Ox25
Ox2000 0100 Ox10

Fig. 5.4.1 Executing the LDR instruction

PUBLICATIONS® - an
TECHNICAL up-thrust for knowledge
<br>

Page 213 of 446

Embedded Systems and loT Design 5-26 ARM Processor

LDRB Rd, [Rx] instruction


This instruction loads Rd with one byte from an address pointed to by Rx into the
lower byte of Rd. The unused portion (the upper 24 bits) of the Rd register will be
all zeros.
Example Assume that R1 = 0x2000 0100 and locations 0x2000 0100 through
:
Ox2000 0103 contents Ox10, 0x25, Ox12, OxB0,

g
respectively.

in
LDRB R2, (R1]

er
After execution of the above instruction, register R2
is loaded with Ox00000010, as
shown in Fig. 5.4.2.

e
in
R2 Ox00 Ox00 Ox00 Ox10

ng
Memory
fE
Ox2000 0104
O
Ox2000 0103 OxBO
e

Ox2000 0102 Ox12


Ox2000 0101
g

Ox25
Ox2000 0100
le

Ox10
ol

Fig. 5.4.2 Executing


C

the LDRB instruction


ARM supports a
memory-mapped
I/O interface and usually,
u

8-bits. Thus, LDRB


for reading the contentsI/O registers are
instruction is useful
ad

and peripheral ports. of I/O registers


LDRH Rd, [Rx]
instruction
iln

This instruction
loads Rd
whose starting location with the contents of two consecutive memory
m

is pointed at by Rx locations
2 bytes) from a register. It copies
base address pointed half-word
Ta

Register. The to (16-bit or


unused portion (the upper by Rx into the lower 16-bits
zeros. 16 bits) of of Ra
the Rd register will
Example : Assume be all
= 0x2000
Ox2000 0103 contents that R1 0100 and locations
Ox10, Ox25, Ox12, 0x2000 0100 througt
OxB0, respectively.
LDRH R2, (R1]
After execution
of the above instruction,
shown in Fig. 5.4.3. register R2 is loaded
with Ox00002510, a5

TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>

Page 214 of 446

Embedded Systems and loT Design 5-27 ARM Processor

R2 Ox00 Ox00 0x25 Ox10

Memory

g
Ox2000 0104

in
Ox2000 0103 OxBO

Ox2000 0102 Ox12

er
Ox2000 0101 0x25

e
Ox2000 0100 Ox10

in
ng
Fig. 5.4.3 Executing the LDRH instruction
STR RX, [Rd] instruction
fE
This instruction stores the 32-bit (4 bytes) contents of Rx register in four
consecutive memory locations whose starting location is pointed at by Rd register.
O
Example : Assume that R3 = 0x20000100 and R4 = 0x1050AC20.
STR R4, [R3]
e

After execution of the above instruction, 4 bytes contents of R4 register are stored in
g

as shown in
four consecutive memory locations whose starting location is 0x2000 0100,
le

Fig. 5.4.4.
ol

OxAC Ox20
C

R4 Ox10 Ox50
u

Memory
ad
iln

Ox2000 0104
Ox10.
Ox2000 0103
m

Ox2000 0102 Ox50


Ta

Ox2000 0101 OxAC


Ox2000 0100 Ox20

Fig. 5.4.4 Executing the STR instruction


STRB RX, [Rd] instruction
This instruction stores the 8-bit (lower byte) contents of Rx register
in a memory
Rd register.
location whose location is pointed at by
= R4 = Ox1050AC20.
Example : Assume that R3 0x20000100 and
TECHNICAL
PUBLICATIONS - an up-thrust for knowledge
<br>

Page 215 of 446

Embedded Systems and loT Design 5-28 ARM Processor

STRB R4,.[R3]
a
After execution of the above instruction, the lower byte of R4 register is stored in
memory location whose location is Ox2000 0100, as shown in Fig. 5.4.5.
R4 Ox10 Ox50 OXÁC 0x20

g
Memory

in
er
Ox2000 0104

e
Ox2000 0103

in
Ox2000 0102
Ox2000 0101

ng
Ox2000 0100 Ox20

fE
Fig. 5.4.5 Executing the STRB instruction
The I/0 ports are generally 8-bit and take only one memory space location
O
(memory-mapped I/0). Thus, STRB instruction
CPUregister to I/O registers is useful for writing data from the
and peripheral ports.
g e

STRH RX, [Rd] instruction


This instruction stores the lower 16-bit (2
le

consecutive memnory locations bytes) contents of Rx register


whose starting location is pointed at in two
ol

Example : Assume that R3 = 0x20000100 by Rd register.


and R4 = Ox1050AC20.
C

STRH R4, (R3]


After execution of the above instruction,
u

are stored in two 2 bytes (half-word) contents


consecutive mnemory locations of R4 register
ad

as shown in Fig. 5.4.6. whose starting location is Ox2000 0100,


iln

R4 Ox10
Ox50 OXAC Ox20
m

Memory
Ta

Ox2000 0104
Ox2000 0103
0x2000 0102
Ox2000 0101 OXAC
Ox2000 0100 0x20

Fig. 5.4.6 Executing the STRH instruction


TECHNICAL PUBLICATIONS- an
up-thrust for knowlodge
<br>

Page 216 of 446

Embedded Systems and loT Design 5- 29 ARM Processor

We started with a basic form of LDR/STR instructions and now continue with
three basic offset forms with three different address modes for each offset form.
1. Offset form : Immediate value as the offset
Addressing mode : Offset
Addressing mode : Pre-indexed

g
Addressing mode : Post-indexed

in
2. Offset form : Register as the offset

er
Addressing mode : Offset
Addressing mode : Pre-indexed

e
in
Addressing mode : Post-indexed

ng
3. Offset form : Scaled register as the offset
Addressing mode: Offset
Addressing mode : Pre-indexed fE
Addressing mode : Post-indexed
O
5.4.1.2 Offset form: Immediate Value as the Offset
e

LDR Rd, [Rx, imm] instruction


g

This instruction uses an immediate (integer) as an offset. This value is added


or
le

subtracted from the base register (Rx) to access data at an offset known at compile
time. The value of the base register does not change.
ol

= 0x2000 0100 and locations 0x2000 0100 through


Example : Assume that R1
C

Ox2000 0106 contents 0x10, 0x25, 0x12, OxBO, Ox34, Ox58, OxA2, respectively.
u

LDR R2, [R1, #2]


as
ad

After execution of the above instruction, register R2 is loaded with Ox5834B012,


shown in Fig. 5.4.7. The value of R1 remains unchanged.
iln

R2 Ox58 Ox34 OxB0 Ox12


m

Memory
Ta

Ox2000 0106 OxA2

Ox2000 0105 Ox58


Ox2000 0104 Ox34
Ox2000 0103 OxB0
Ox12
Ox2000 0102:
Ox2000 0101 Ox25
Ox2000 0100 Ox10

Fig. 5.4.7 Executing the LDR instruction


with immediate offset

TECHNICAL PUBLICATIONS8 - an up-thrust for knowledge


<br>

Page 217 of 446

Embedded Systems and loT Design 5-30 ARM Processor

LDR Rd, Rx, imm]! instruction


This instruction uses the pre-indexed address mode. We can recognize this mode
by the exclamation mark (). The only difference is that the base register gets
updated before accessing data.
Example :.Assume that R1 = 0x2000 0100 and locations 0x2000 0100 through
Ox2000 0106 contents Ox10, Ox25, Ox12, 0xBO, Ox34, Ox58, 0xA2, respectively.

g
in
LDR R2, (R1, #2]i
After execution of the above instruction, R1 = 0x20000102 and register R2 is loaded

er
with Ox5834B012, as shown in Fig. 5.4.8(a).

e
in
LDR Rd, [RX], imm instruction
This instruction uses the post-indexed address mode. The only difference is that

ng
the base register gets updated after accessing data.
Example : Assume that R1 = 0x2000 0100 and locations 0x2000 0100 through
fE
Ox2000 0106 contents Ox10, Ox25, Ox12, 0xB0, Ox34, Ox58,
OxA2, respectively.
O
LDR R2, [R1], #2
After execution of the above instruction, register R2 is loaded
with 0xB0122510 and
e

R1 = 0x2000 0102, as shown in Fig. 5.4.8(b).


g
le
ol

R1 Ox02 Ox00 Ox01 Ox02


C

R2 Ox58 Ox34 OxBO Ox12


u
ad

Memory
Ox2000 0106 OXA2
iln

Ox2000 0105 Ox58


Ox2000 0104. Ox34
m

Ox2000 0103 OxBO


Ta

Ox2000 0102 0x12


Ox2000 0101 0x25
Ox2000 0100 Ox10

(a) Executing the LDR instruction


with immediate
offset in pre-indexed address mode

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 218 of 446

Embedded Systems and loT Design 5-31 ARM Processor

R2 OxBO Ox12 0x25 0x10

Memory
Ox2000 0106 OxA2
Ox2000 0105 Ox58
Ox2000 0104 Ox34

g
Ox2000 0103 OxB0

in
Ox2000 0102 Ox12

er
Ox2000 0101 Ox25
Ox2000 0100

e
Ox10

in
ng
R1 Ox02 Ox00 Ox01 0x02

fE
(b) Executing the LDR instruction with immediate
offset in post-indexed address mode
O
Fig. 5.4.8
STR Rx, [Rd, imm] instruction
e

• This instruction uses an immediate (integer) as an offset. This value is added or


g

subtracted from the base register (Rx) to access data at an offset known at compile
le

time. The value of the base register does not change.


ol

=
Example : Assume that R3 = 0x200000FC and R4 0x1050AC20.
C

STR R4, [R3, #4]


u

After execution of the above instruction, 4 bytes contents of R4 register are stored in
ad

four consecutive menmory locations whose starting location is R3 (0x200000FC) + offset


(Ox04)= 0x2000 0100, as shown in Fig. 5.4.9.
iln

R4 Ox10 Ox50OXAC 0x20


m

Memory
Ta

Ox2000 0104
Ox2000 0103 Ox10

Ox2000 0102 Ox50


Ox2000 0101 OXAC

Ox2000
01000x20
Fig. 5.4.9 Executing the STR instruction with immediate offset

TECHNICAL PUBLICA TIONs® - an up-thrust for knowledge


<br>

Page 219 of 446

5-32 ARM Processor


Embedded Systems and loT Design

STR RX, [Rd, imm]! instruction


• This instruction uses the pre-indexed address mode. We can recognize this mode
by the exclamation mark (). The only difference is that the base register gets
updated before accessing data.
= Ox1050AC20.
Example: Assume that R3 = Ox200000FF and R4

g
STR R4, [R3, #4]!

in
After execution of the above instruction, R3 = R3 (0x200000FF) + offset (0x04) =

er
Ox2000 0103. The 4 bytes contents of R4 register are stored in four consecutive memory
locations whose starting location is pointed at by the updated value of R3 (0x2000 0103),

e
as shown in Fig. 5.4.10(a).

in
R3 Ox02 Ox00 Ox01 Ox03

ng
R4 0x10 Ox50 OXAC Ox20
fE
Memory
O
Ox2000 0106 Ox10
Ox2000 0105 Ox50
e

Ox2000 0104 OxAC


g

Ox2000 0103 Ox20


le

Ox2000 0102
Ox2000 0101
ol

Ox2000 0100
Ox2000 00FF
C

(a) Executing the STR instruction


with
offset in pre-indexed address mode immediate
u
ad

R4 Ox10 Ox50 OXAC Ox20


iln

Memory
Ox2000 0106
m

Ox2000 0105
Ox2000 0104
Ta

Ox2000 0103
Ox2000 0102 Ox10
Ox2000 0101 Ox50
Ox2000 0100 OxAC
Ox2000 0OFF Ox20

R3 Ox02 Ox00 Ox01 Ox03


(b) Executing the STR instruction
with
offset in post-indexed address modeimmediate
Fig. 5.4.10
TECHNICAL PUBLICATIONS -
an up-thrust for knovledge
<br>

Page 220 of 446

Systems and IloT Design 5-33


Embedded ARM Processor

Rx, (Rd],imm instruction


STR
instruction uses the post-indexed address mode. The is that
This only difference
the base register
gets updated after accessing data.

• Example : Assume that R3 =


0x200000FF and R4 =
Ox1050AC20.

(R3], #4
TR R4,
execution of the above instruction, the 4 bytes contents of R4 register are stored'

g
After
consecutive memory locations whose starting location is pointed at by the value

in
in four
a (0x2000 00FF), as shown in Fig. 5.4.10(a). Then the value of R3 is updated as

er
=
P3= R3 (0x200000FF) + offset (0x04) Ox2000 0103.

e
:
Register as the Offset

in
541.3 Offset Form
an immediate number. This
form uses a register as an offset instead of

ng

This offset
offset form is handy when
we
want to access an array where the index is
computed at run-time. fE
Example :
Address mode
:
immediate offset
O
memory address in R1 with the offset
STR Store the value in R3 to the
R3, [R1, R2] ;

value in R2. Base register, R1 unmodified.


e

memory address in R1 with the offset value in


g

at a
LDR R3, [R1, R2]:Load value
le

R3. Base register, R1


unmodified.
to register
ol

Example :
Address mode : pre-indexed
memory address in R1 with the offset
C

in R3 to the
R3, [R1, R2]! Store value
:
OIK = + R2.
R1
u

value modified: R1
in R2.
registerBase R1 with the offset value
in
address in
ad

a memory
LDR R3, [R1, R2]!: Load value at R2.
= RI +
R2 modified: R1
to register R3. Base register
iln

Example post-indexed
:Address mode : memory address in R1. Then
modify base
m

R3 to the
STR R3,[R1J,
R2; Store value in
Ta

egister: R1 = R3. Then


R1 + R2. address in R1 to register
a memory
LDR R3, at
[R1), R2 : Load value
Tnodify
base register : R1 = R1 + R2.
Offset
5A14
Ofset Form : Scaled Register as the
LOR
Ra, Rc, <shifter>]
[Rb,
STR
Ra, (Rb, Rc, <shifter>]

knowledge
PUBLICATIONS - an up-thrust for
TECHNICAL
<br>

Page 22 l of 446

Embedded Systems and loT Design 5-34 ARM Processor

• In this case, Rb is the base register and Rc is an immediate offset (or a register
containing an immediate value) left/right shifted (<shifter>) to scale the immediate
offset. The barrel shifter is used to scale the offset.
:
Example Address mode :
immediate offset
• STR R3, [R1, R2, LSL#2] ; Store the value in R3 to
the memory address in R1 with
the offset value in R2 left-shifted by 2. Base register, R1 unmodified.

g
in
LDR R3, [R1, R2, LSL#2]; Load value at a memory
address in R1 with the offset

er
value in R2 left-shifted by 2 to register R3. Base register, R1
unmodified.

e
Example :
Address mode :
pre-indexed

in
•STR R3, (R1, R2, LSL#2]! ;
Store the value in R3 to the memory

ng
the offset value in R2 left-shifted by 2. Base address in R1 with
register modified : R1 = R1 + R2<<2.
LDR R3, [R1, R2, LSL#2 fE
]!; Load value at a memory address in R1
value in R2 left-shifted by 2 to
register R3. Base register modified : R1 = with the offset
R1+ R2<<2.
O
• Example : Address :
mode post-indexed
STR R3, [R1], R2, LSL#2 ;
e

Store value in R3 to
modify base register : R1 = R1 + the memory address
g

R2<<2. in R1. Then


le

LDR R3, [R1], R2, LSL#2 ;


Load value at a memory address
modify base register : R1 = R1 + R2<<2.
ol

in R1 to register R3. Then


C

ReviewO
Questions
u

1. Explain the basic form of load/store


ad

instructions.
2. Explain. the load/store
instructions with immediate
3. Explain the load/store value as the offset.
iln

instructions with the


4. Explain the load/store register as the offset.
instructions with scaled
register as the offset.
m

5.4.2 Arithmetic Instructions


Ta

ARM instruction set


supports ADD, ADC,
instructions for arithmetic SUB, SBC, MUL,
operations. UMULL, RSB and
By default, these RS
ARM instructions
. We override the
do not affect flags
after the execution.
default by having letter
ADCS, SUBS, SBCS, S in' the instruction.
MULS, UMULLS, RSBS For example : ADDS
ARM instructions
do affect flag bits
and RSCS instructions,
in the CSPR register after With letter 5
the execution.
TECHNICAL
PUBLICATIONS -
an up-thrust for
knowledge
<br>

Page 222 of 446

Embedded Systems and loT Design


5-35 ARM Processor

Table 5.4.1 lists the arithmetic instructions.

Instruction (Do not update Flags)


Instruction (Do update Flags)
ADD Add ADDS Add and set flags

g
ADC Add with carry ADCS Add with carry and set flags

in
SUB SUBS SUBS Subtract and set flags

er
SBC Subtract with carry SBCS Subtract with carry and set flags

e
MUL Multiply MULS

in
Multiply and set flags
UMULL Multiply long UMULLS Multiply Long and set flags

ng
*****

RSB Reverse subtract RSBS Reverse subtract and set flags


********
RSC Reverse subtract with carry RSCS
fE
Reverse subtract with carry. and set flags
Table 5.4.1 Arithmetic instructions
O
• It is important to note that there are no increment and decrement instructions
in
the ARM processor. Instead, we use ADD and SUB instructions to perform them,
e

respectively.
g
le

54.2.1 Addition of Unsigned Numbers


ol

ADD instruction
C

Syntax : ADD Rd, Rn, Op2 ; Rd = Rn + Op2


• This instruction adds two operands. The Op2 operand can be a register or
u

immediate value.
ad

Examples:
ADD R1, R2, #0x35 ;R1 = R2 + 35 (in hex)
iln

ADD R1, R2, ;R1 = R2 + R3


R3
m

ADDS instruction
Syntax : ADDS Rd, Rn, Op2 ; Rd = Rn +Op2 and update flags
Ta

This instruction adds two operands and update flags. The Op2 operand can be a
register or immediate value.
Examples :
ADDS R1, R2, #Ox35 : R1 = R2 + 35 (in hex) and update flags
ADDS R1,
R2, R3 :R1 = R2 + R3 and update flags
ADC instruction (add with carry)
= +
Syntax : ADC Rd, Rn, Op2 Rd Rn +.Op2 C
;

This instruction adds two operands with a carry flag. The Op2 operand can be a
register or immediate value.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 223 of 446

ARM Processor
Embedded Systems and loT Design 5-36

Examples:
ADC R1, R2, #0x35 ;R1 = R2 + 35 (in hex) + Carry
ADC R1, R2, R3 ; R1 = R2 + R3 + Carry

ADCS instruction
• Syntax : ADCS Rd, Rn, Op2; Rd = Rn + Op2 + C and update flags

g
This instruction adds two operands with a carry flag and update flags. The Op2

in
operand can be a register or immediate value.

er
Examples :
ADCS R1, R2, #0x35 ; R1 = R2 + 35 (in hex) + Carry

e
and update flags
ADCS R1, R2, R3 ;R1 = R2 + R3 +

in
Carry and update flags
Program 1: Add two 16-bit numbers

ng
AREA P 1, CODE, READONLY
ENTRY
MOV R1, =0x8000 ;R1 = 0x 8000
fE
MOV R2, =0x9000 ;R2 = 0x 9000
O
ADD R3, R1, R2
;R3 = R1 + R2 =0x 11000
END
e

Program 2 : Add two 32-bit


g

numbers
AREA P_2, CODE, READONLY
le

ENTRY
ol

MOV R4, #0 : for saving carry


LDR R1, =0x80000000 ;R1 = 0x80000000
C

LDR R2, =0x9000FFFF


;R2 = 0x9000FFFF
ADDS R3, R1, R2 :R3 = R1 +
u

R2 = 0x1000FFFF
ADC R4, R4, #0 =
:R4 1, increments and carry = 1
ad

R4 since carry
is 1,
END
iln

Program 3: Add three 32-bit numbers


AREA
m

P 3, CODE, READONLY
ENTRY
Ta

MOV R5, #0 ;for saving carry


LDR R1, =0x80000000
;R1 = Ox80000000
LDR R2, =0x900OFFFF
;R2 = 0x9000FFEF
LDR R3, =0x10000000 ;R3 = 0x10000000
ADDS R4, R1, R2 : R4 = R1 +
R2 = 0x100OFFFF
ADC R5, R5, #0 :R5 = 1, increments R5 and carry=1
ADDS R4, R4, R3 : R4= R4 + since carry is 1.
R3=0x1000FFFF +
ADC R5, R5, #0 ;R5 = 1, no Ox10000000 = Ox2000FFFF
change in R5 since carry 0.
END is

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 224 of 446

Embedded Systems and loT Design


5-37 ARM Processor
Program 4: Add 0x12345678FF and 0x55FFAAAA33
AREA P_4, CODE, READONLY
ENTRY
LDR R1, =0x345678FF ;R1 = Ox345678FF
LDR R2, =0xFFAAAA33 ;R2 = OxFFAAAA33
MOV R3, =0x12 :R3 = Ox12

g
MOVR4, =0x55 ;R4 = Ox55

in
ADDS R5, R1, R2 ;R5 = R1 + R2 =
Ox34012332 and carry = 1

er
ADC R6, R3, R4 ;R6 = R3 R4+
+ carry = 0x12 + Ox55 + 1 = Ox68
END

e
in
5.4.2.2 Subtraction of Unsigned Numbers

ng
SUB instruction
Syntax : SUB Rd, Rn, Op2 ; Rd = Rn -Op2 fE
This instruction subtracts Op2 from Rn and stores the result in Rd using the 2's
O
complement method. Op2 operand can be a register or immediate value. The CPU
in executes the SUB instruction for unsigned numbers as follows :
e

1. Take the 2's complement of the subtrahend (Op2 operand).


g

2. Add it to the minuend (Rn operand).


le

3. Place the result in destination Rd.


ol

• Examples :
- 35 (in hex)
C

SUB R1, R2, #0x35 ;R1 = R2


SUB R1, R2, R3 : R1 = R2- R3
u
ad

SUBS instruction
; -
= Rn Op2 and update flags
Syntax : SUBS Rd, Rn, Op2 Rd are
iln

instruction is similar to SUB instruction; however, after execution, flags


This
can be a register or immediate value.
updated. The Op2 operand
m

Examples :
Ta

SUBS R1, R2, #0x35 = R2 - 35 (in hex) and update flags


:R1
R1 = R2 - R3 and update
:
flags
SUBS R1, R2, R3

SBC instruction (subtract with borrow) - Op2-1+ C


: SBC Rd, Rn, Op2 ; Rd = Rn
Syntax 0. Thus subtract
with
subtraction is represented by C=
• In ARM. borrow after Rn - Op2
-1
+ C.
The Op2 operand
implemented as Rd=
borrow instruction is
immediate value.
can be a register or
: Carry
Examples 35 (in hex)-1+
SBC R1, R2, #0x35 :R1 = R2-- + Carry
SBC R1, R2, R3 :R1 = R2 R3-1

PUBLICATIONws® - an up-thrust for knowledge


TECHNICAL
<br>

Page 225 of 446

Embedded Systems and loT Design 5-38 ARM Processor

SBCS instruction
Syntax : SBCS Rd, Rn, Op2;Rd = Rn - Op2
-1 +C and update flags
This instruction is similar to SBC instruction; however,
after execution, flags are
updated. The Op2 operand can be a register or immediate value.
• Examples :
SBCS R1, R2, #Ox35 ;R1 = R2 –
35 (in hex) -1 + Carry and update flags

g
SBCS R1, R2, R3 = -
;R1 R2 R3 -1 + Carry and update flags

in
Program 5: Subtract two 16-bit numbers

er
AREA P_5, CODE, READONLY
ENTRY

e
MOV R1, =0x8000 ;R1 = 0x8000

in
MOV R2, =0x5000 ; R2 = Ox5000

ng
SUB R3, R1, R2 ;R3 = R1 - R2 = 0x3000
END

Ox8000
fE
00008000
Ox5000 +
O
FFFFBO00 2's complement of Ox5000
Ox3000 Ox1 00003000 C=1, result is positive
g e

Program 6: Subtract 0x129000FFFF from 0x3480000000


le

AREA P
6, CODE, READONLY
ENTRY
ol

LDR R1, =0x80000000 ;R1 = Ox80000000


C

LDR R2, =Ox900OFFFF ;R2 = Ox9000FFFF


MOV R3, =0x34 ;R3 = Ox34
u

MOV R4, =0x12 ;R4 = Ox12


ad

SUBS R5, R1, R2 :R5 = R1 - R2=0xEFFFO001


SBC R6, R3, R4 :R6 =
and carry = 0
R3- R4 cary =
iln

END
-1+ 0x34 - Ox12 - 1 +0 = 0x21
m

Ox80000000 Ox80000000
Ta

Ox9000FFFF + Ox6FFF0001 2's complement of Ox9000FFFF


OxEFFF0001 OxEFFF0001 C=0, result is negative
RSB Instruction (reverse subtract)
Syntax : RSB Rd, Rn, Op2 ; Rd = Op2 - Rn
RSB and SUB instructions are
essentially
the same, except that the source
are reversed. The operands
Opz operand can be a register or
immediate value.

TECHNICAL PUBLICATIONs -
an up-thrust for knowledge
<br>

Page 226 of 446

Embedded Systems and loT Desian


5-39 ARM Processor

Examples :
RSB R1, R2, #0x35 :R1 = 35 (in hex) - R2
R2, R3 ;R1 =
RSB R1, R3- R2
RSBS Instruction
Syntax : RSBS Rd, Rn, Op2 ; Rd = Op2 - Rn
.

g
RSB and RSBS instructions are
essentially the same, except that, latter instruction

in
updates flags. The Op2 operand can be a register or immediate value.

er
Examples :
RSBS R1, R2, #0x35 :R1 = 35 (in hex)– R2 and update flags

e
RSBS R1, R2, R3 ;R1 = R3– R2 and update flags

in
RSC Instruction (reverse subtract with carry)

ng
• Syntax : RSC Rd, Rn, Op2 ; Rd = Op2 - Rn - 1+ C
fE
• RSB and RSC instructions are essentially the same, except that, latter instruction
subtracts with carry. The Op2 operand can be a register or immediate value.
O
Examples :
RSC R1, R2,
#0x35 ; R1 = 35 (in hex) – R2-1 + Carry
e

RSC R1,
R2, R3 ; R1 = R3 – R2 -1 + Carry
g

RSCS Instruction (reverse subtract with carry)


le

Syntax : RSC Rd, Rn, Op2 ; Rd = Op2 - Rrn -1 + C


ol

• RSC and RSCS


instructions are essentially the same, except that, latter instruction
C

updates flags. The Op2 operand can be a register or immediate value.


Examples:
u

KI, R2,
#0x35: R1 = 35 (in hex) R2-1 t Carry and update flags
ad

RSCS R1, –
R2, R3 ;R1 = R3 R2 -1 + Carry and update flags
Program7: Create and R1 register
iln

RO
2's complement of
a
64-bit data in
Assume RO holds the lower 32-bit.
m

LDR RO,=0x55667788
;RO = Ox55667788
LDR R1,=0x11AABBCC
Ta

; R1 = Ox11AABBCC
RSB R3,RO,#0 = 0xAA998878 and C= 0
RSC
:R3 = 0- RO =0-Ox55667788
R4.R1,#0 : R4 = 0- R1-1+ C=0-0x11AABBCC- 1 +0 = OxEE554433
5.4.2.3
Multiplication Unsigned Numbers
ARM
supports two types unsigned multiplication :
of

: Normal multiply (result is less than


or equalt to 32 - bit)
OL
(result is greater than 32 - bit)
moL
:
Long multiply

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 227 of 446

Embedded Systems and loT Design 5-40 ARM Processor

MUL (Unsigned Multiply)


Syntax : MUL Rd, Rn, Op2; Rd = Rn x Op2
• This instruction multiplies two operands. Since the result should not exceed
32-bits, two operands should be 16-bit. If the MUL instruction is used for 32-bit
operands, the destination register will hold the lower word (32-bit) and the portion

g
beyond 32-bit is dropped. The Op2 operand must be in register.

in
:
Examples
;R1 = R2 X R3

er
MUL R1, R2, R3
LDR R1,=0x10000000 : R1 = 0x10000000

e
LDR R2,=0x20000000;R2 = Ox20000000

in
MUL R3,R2,R1 ;R3 = 0x00000000
Actual result of multiplication is 0x200000000000000.

ng
However, only lower 32-bit is
stored in the R3; the portion beyond 32-bit is dropped.
UMUL (Unsigned Multiply Long) fE
Syntax : UMUL RdLo, RdHi, Rn, Op2 ; RdHi:RdLo =
Rn x Op2
This instruction multiplies two 32-bit operands.
O
The Op2 operand must be in
register.
Examples :
e

LDR R1,=0x10000000 ;R1 = 0x10000000


g

LDR R2, =0x20000000;R2 = Ox20000000


le

UMUL R3, R4, R2, R1 : R3 = Ox00000000


and R4 = 0x2000000
ol

LDR R1,=0xFFFFFFFF ;R1 = OxFFFFFFFF


C

LDR R2, =0xFFFFFFFF ;R2 = OxFFFFFFFF


UMUL R3, R4, R2, R1 ; R3 = 0x00000001
u

and R4 = 0x FFFFFFFE
ad

5.4.2.4 Multiply and Accumulate Instructions


In some applicatiorns, such as Digital
iln

Signal Processing (DSP), we


two registers and add the need to multiply
result with another register.
The ARM supports single
m

instruction to do both jobs.


MLA (Mutiply and Accumulate)
Ta

:
Syntax MLA Rd, Rm, Rs, Rn ;Rd = Rm x Rs +
Rn
This instruction multiplies two
operarnds
to the third operand. All operand must and adds the result of the multiplication
be in register.
Example:
MOVR1, #0x20 ;R1 = Ox20
MOV R2, #0x40 ;R2 = Ox40
MOVR3, #0x50 ;R3 = Ox50
MLA R4, R1, R2, R3 R4 = R1 x R2 + R3 = (0x20) X (0x40) + (0x50)= 0x850

TECHNICAL PUBLICATIONS
- an
up-thrust for knowledge
<br>

Page 228 of 446

Embedded Systems and loT Design 5-41 ARM Processor

• It is important to note that if MLA instruction produces a result greater than


32-bit, the destination register will hold the lower word (32-bit) and the portion
beyond 32-bit is dropped.
UMLAL (Unsigned Multiply and Accumulate Long)
Syntax UMLAL RdLO, RdHi, Rn, Op2 ; RdHi:RdLo = Rn x Op2 + RdHi:RdLo
:

g
This instruction multiplies two 32-bit operands and adds the result of the

in
multiplication to the contents of 64-bit (RdHi:RdLo) destination register. All

er
operand must be in register.

e
Example :

in
LDR R1, =#0x20001000 ; R1 = Ox20001000
;R2 = 0x40005500

ng
LDR R2, =#0x40005500
LDR R3, =#0x00000050 :
R3 = 0x00000050
LDR R4, =#0x0000C000 ; R4 = Ox0000CO00
UMLAL R3, R4, R2, R1 ;R4:R3 = R1 x R2 +(R4: R3)
fE
;= (0x20001000) x (0x40005500) + (0x 0000C00000000050)
O
;= 0x800CEA005500050
; R4 = Ox800CEA0 and R3 = Ox05500050
e

5.4.2.5 Division of Unsigned Numbers


g
le

Some ARM families do not support instruction for the division of unsigned
to perform the
numbers. In such cases, we can use repetitive SUB instruction
ol

division.
C

UDIV (Unsigned Divide)


= Rn + Rm
u

• Syntax : UDIV Rd, Rn, Rm; Rd


of the value in Rn by the
ad

This instruction performs an unsigned integer division


is not divisible by the value in
value in Rm. For instruction, if the value in Rn
iln

zero.
Rm, the result is rounded towards
m

Example: = R8 / R1.
UDIV R8, R8, R1 Unsigned divide, R8
Ta

Review Questions
supported by ARM processor.
1. Explain any four arithmetic instructions
2. Compare ADD, ADC, ADDS,
and ADCS instructions.
3. Compare SUB, SUBS,
RSB, and RSC instructions.
4. Explain unsigned multiplication instructions
supported by ARM processor.

- an up-thrust for knowledge


TECHNICAL PUBLICATIONs
<br>

Page 229 of 446

Embedded Systems and loT Design 5-42 ARM Processor

5.4.3 Logic Instructions


ARM processor supports logic instructions such as AND, ORR,
and EOR. These
instructions perform bitwise AND, OR, and Exclusive OR operations on
the values
two operands.
• Like arithmetic instruction, we must use
the

g
S in the instruction syntax if we want
to update the flags after the execution of the instruction.

in
• Table 5.4.2 lists the logic
instructions.

er
Instruction (Do not update Flags)

e
Instruction (Do update Flags)

in
AND ANDing
ANDS Anding and set flags

ng
ORR ORRing
ORS Oring and set flags
EOR Exclusive-ORing
BIC Bit Clearing
EORS

BICS
fE Exclusive Oring and set flags
Bit clearing and set
flags
O
Table 5.4.2 Logic instructions
AND instruction
Syntax : AND Rd, Rn,
e

Op2 ; Rd = Rn ANDed
Op2
g

This instruction performs a


bitwise logical AND
le

places the result operation on the operands


in the destination. The and
immediate value. AND Op2 operand can
be a register or
ol

instruction is usually
operand. used to mask certain
bits of the
C

Examples:
AND R1, R2, #0x65 ;R1 = R2 ANDed 65 (in hex)
u

AND R1, R2, R3


ad

;R1 = R2 ANDed R3 0011 1001


MOV R1, #0x39 AND 0 Ox39
0001111 OxOF
AND R2, R1, #0x0F
iln

;R2= R1
ANDed with 0x0F = 0000 1001
0x09 Ox09
ANDS instruction
m

Syntax : ADDS Rd,


Rn, Op2 ;Rd = Rn +
AND Op2 and update flags.
Ta

and ANDS instructions are


instruction updates flags. essentially the same,
except that, latter
ORR instruction
Syntax : ORR Rd, Rn, Op2 ; Rd =
Rn ORed Op2.
This instruction performs
a bitwise logical
places the result in the destination. OR operation on
the operands and
The Op2 operand
immediate value. can be a register or

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 230 of 446

Embedded Systems and loT Design 5-43 ARM Processor

Examples:
ORR R1, R2, #Ox65 ; R1= R2 ORed 65 (in hex) 0011 10011 Ox39
OR 00O0111 Ox0F
ORR R1, R2, R3 ;R1 = R2 ORed R3
MOV R1, #0x39 00111111 0x3F
ORR R2, R1, #0x0F ;R2= R1 ORed with 0x0F = 0x3F
instruction

g
ORS
Syntax : ORS Rd, Rn, Op2 ; Rd = Rn ORed Op2 and update flags.

in
ORR and ORS instructions are essentially the same, except that, latter instruction

er
updates flags.

e
EOR instruction

in
Syntax : EOR Rd, Rn, Op2 ; Rd = Rn EX-ORed Op2.

ng
This instruction performs a bitwise logical OR operation on the operands and
places the result in the destination. The Op2 operand can be a register or
fE
immediate value.
O
:
Examples
EOR R1, R2, #0x65 : R1= R2 EX-ORed 65 (in hex) 00111001 Ox39
;R1 = R2 EX-ORed R3
EOR 0
0001111 OxOF
e

EOR R1, R2, R3


g

MOVR1, #0x39 00110110 0x36


:R2= R1 EX-ORed with OxOF= 0x36
le

EOR R2, R1, #0x0F


ol

EORS instruction
Syntax :
Rd = Rn EX-ORed Op2 and update flags.
EORS Rd, Rn, Op2 ;
C

• EOR and EORS instructions are essentially the same, except that, latter instruction
u

updates flags.
ad

BIC (bit clear)


; = Rrn bit-cleared Op2.
Syntax : BIC Rd, Rn, Op2 Rd
iln

This instruction clears certain bits of Rn specified by the Op2 and place the result
in Rd. The instruction clears HIGH bits in Op2, and other bits (LOW bits) remain
m

unchanged.
Ta

Example: 00111001 Ox39


MOVR1, #0x39 BIC 000011 11 OxOF

EOR R2, R1, #0xOF


: R2= R1 bit-cleared with 0xOF = 0x30 00110000 Ox30
BICS instruction
; = Rn bit-cleared Op2
Syntax : BICS Rd, Rn, Op2 Rd
and update flags.
BIC and BICS instructions are essentially the same, except that, latter instruction
updates flags.
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 23 l of 446

Embedded Systems and loT Design 5-44 ARM Processor

MVN (Move Negatlve)


Syntax : MVN Rd, Opl ;move negative of Op1 to Rd.
This instruction generates one's complement of an operand (Op1) and places the
result in Rd. The Opl operand can be a register or immediate value.
Examples:

g
MVN R2, #0 ;R2 = 0xFFFFFFFF

in
LDR R1,=0xAAAA5555 ;R1 = 0xAAAA5555
;R2 = Ox5555AAAA

er
MVN R2, R1

e
Review Questions

in
1. Perform the folloving operations on operands 0x11114FCA :

ng
and Ox2222C237
a) AND b) OR c) XOR
2. What is the result of XORing an operand with itself
3. Write an instruction that sets bit 2 of R1.
fE?

4. Write an instruction that clears bit 5 of R3.


O
5. Write an instruction that masks lower four bits
of R4.
e

5.4.4 Rotate and Shift Instructions


g
le

Data processing instructions are processed


ol

within the Arithmetic Logic Unit (ALU). A Rr


Rm
pre-processing
Pre-processing

unique and powerful feature of the ARM


C

processor is the ability to shift the 32-bit


Barrel shifter
binary pattern in one of the source
u

registers left or right by a specific number


ad

No | Result N
of positions before it enters the ALU.
iln

• This shift increases the power


and Arithmetic Logic Unit
flexibility of many data processing
m

operations. The shifting of the source


registers left or right is achieved using
Ta

Rd
barrel shifter as shown in Fig. 5.4.11. Fig. 5.4.11 ALU with
barrel shifter
There are data processing instructions
that do not use the barrel shift, for example,
the MUL (multiply), CLZ (Count
Leading Zeros), and QADD (signed
32-bit add) instructions. saturated
Pre-processing or shift occurs
within the cycle time of the instruction.
particularly useful for loading constants This is
multiplies or division by a power into a register and achieving fast
of 2.

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 232 of 446

Embedded Systems and loT Design ARM Processor


5-45

Mnemonic Description Shift Result Shift amount y


LSL Logical Shift Left x LSLy or Re
x <<y #0-31
LSR Logical Shift Right x LSR y (unsigned) x >> y
....
#0-32 or R
ASR Arithmetic Right Shift x ASR y (signed) x >> y #0-32 or R

g
ROR Rotate Right X ROR y (unsigned) x >> y) | (x<< (32 or
#0-31 R

in
y)
Rotate Right x (c flag << 31) (unsigned) x >>

er
RRX RRX 1) none
Extended

e
Note :x represents the register being shifted and y represents the shift amount.

in
:
Table 5.4.3 Barrel shifter operations

ng
LSL : Logical Shift Left
fE
O
e

Carry
g

flag
le

Fig. 5.4.12' LSL #3


ol

:
LSR Logical Shift Right
C
u

Carry
00 0
ad

flag
iln
m

Fig. 5.4.13 LSR #3


Ta

ASR : Arithmetic Shift Right


Carry
flag

31

Fig. 5.4.14 ASR #3

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 233 of 446

Embedded Systems and loT Design 5-46 ARM Processor

ROR : A Rotate Right

Carry
flag

g
in
er
Fig. 5.4.15 ROR #3
RRX

e
A Rotate Right with Extend (RRX) moves the

in
bits of the register Rm to the right
by one bit, and it copies the carry flag into bit[31]

ng
of the result. It is the rotate
right operation with carry.
fE Carry
flag
31/3o|
O
10
g e

Fig. 5.4.16 RRX


le

Example: Assume C = 0
ol

LDR R1,=0x00000026 :R1 = 0000 0000 0000 0000


0000 0000 0010 0111
C

MOVS R1, R1, RRX :R1 = 0000 0000 0000 0000 0000
MOVS R1, R1, RRX : R1 = 1000 0000 0001 0011
0000 0000 0000 0000 C=1
u

MOVS R1, R1, RRX 0000 0000 1001


:R1 = 1100 0000 0000 0000 C=1
00000000 0000 0100
ad

MOVS R1, R1, RRX :R1 = 1110 0000 0000 0000


0000 0000 0000 0010 C=1
Rotate left C=0
iln

There is no rotate left


instruction in ARM. We can
operation by rotating right perform the rotate-left
m

32-n bits. Using this


proper carry if actual method does not give us the
instruction of ROL was available.
Ta

Example: Performing rotate-left


operation by 1 bit using
LDR R1,=0x00000026 :R1 = 0000 0000 ROR instruction.
MOVS R1,R1, ROR 0000 0000 0000 0000 0010 0110
#31 ;R1 = 0000 0000 0000 0000 0000 0000 010o 1100
Example1 MOV r6,
C=0
r5, LSL
#2:This instruction multiplies register
shifting its contents towards r5 by four (by
left by two bit positions)
register r6. and then places the result into

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 234 of 446

Embedded Systems and loT Design


5-47 ARM Processor

Example 2 MOV rl, r1, LSR #2 This instruction divides R1 by four by shifting
its
Contents towards 0O Dit poSitions (unsionpd)

Example 3
MOV T2, r2, ASR #2 : This instruction divides R2 by four by shifting its
contents towards
right by two bit positions (signed).

g
Example 4
MOV t3, r3, ROR #16: This instruction swaps the top and botton halves

in
C
of
R3.

er
Example 5
ADD 4, r4, r4, LSL #4: This instruction multiplies R4 by 17. (N=N+N"16)

e
in
Example 6 RSB r5, r5, r5, LSL #5: This instruction multiplies R5by 31. (N = N'32- N)

ng
Review Questions fE
1. Explain barrel shifter with a neat sketch.
O
2. Explain 5 diferent shift operations that can be used with barrel shifter.
e

3. Describe barrel shifter with its instructions of operation.


g

5.4.5 Looping, Branch Instructions and Conditional Execution


le
ol

Repeating a sequence of instructions or an operation a certain number of times is


called a loop. The loop is one of the most widely used programming techniques.
C

Loop is implemented using branch instruction.


u

Branches allow us to jump to another code segment. This is useful when we need
ad

to skip (or repeat) blocks of codes or jump to a specific function.


a
All ARM processors support a branch instruction that allows conditional branch
iln

forwards or backward up to 32 MB. As the PC is one of the general-purpose


a to R15.
registers (R15), a branch or jump can also be generated by writing value
m

• The Branch with Link (BL) instruction preserves the address of the instruction
Ta

after the branch (the return address) in the LR (R14). This allows performing
subroutine calls.
:

There are three types of branching instructions


Branch (B) : Simple jump.
to function. Used for
Branch link (BL) : Saves (PC+4) in LR and jumps
subroutine calls.
: to
Branch exchange (BX) and Branch link exchange (BLX) BX/BLX is used
ARM to Thumb.
exchange the instruction set from
TECHNICAL PUBLICATIONS- an up-thrust for knowledoe
<br>

Page 235 of 446

ARM Processor
Embedded Systems and loT Design 5-48

We start with a simple Branch or Branch with Link instruction


B
{condition) <address>
BL(condition) <address>
Fig. 5.4.17 shows the instruction format for branch and branch
link instructions.
0

g
31 28 27 25 24 23
24-bit signed word offset

in
Cond 101L

er
Fig. 5.4.17 Instruction format for branch and branch link instructions

e
Bits [31:28] :
These bits specify the conditions under which the instruction is

in
executed.

ng
Bits (27:25] : Identify this as a B or BL instruction - They have values 101.
Bit [24] : The L-bit = 0 for branch instruction (B) and L-bit 1 for branch with link
(BL) instruction
fE
:
Bits (23:0] 24-bit signed offset specifies the destination of the branch in 2's
O
complement form.
The word offset is shifted left by 2-bits to form a byte offset.
g e

This offset is added to the PC by the processor.


le

The range of a branch is approx +/- 32 Mbytes : 225*4 = 32M


ol

Table 5.4.4 shows the conditions under which the branch instructions are executed.
C

Opcode Mnemonic Interpretation Status flag state for


[31:28] extension
u

execution
ad

0000 EQ Equal/equals zero Z set


NE
iln

0001 Not equal Z clear


0010 CS/HS Carry set/unsigned higher or
m

C
set
same
Ta

0011 CC/LO Carry clear/unsigned lower C clear


0100 MI Minus/negative N set
0101 PL Plus/positive or zero N clear
0110 VS
Overflow V set
0111 VC
No overflow V clear

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 236 of 446

Embedded Systems and loT Design 5-49 ARM Processor

1000 HI Unsigned higher C set and Z clear


1001 LS Unsigned lower or same C clear and Z set.
1010 GE Signed greater than or equal
N equals V
1011 LT Signed less than N is not equal to V

g
1100 GT

in
Signed greater than Z clear and N equals V

er
1101 LE Signed less than or equal Z set or N is not equal to V

e
1110 AL Always any

in
1111 NV Never (do not use!) none

ng
Table 5.4.4 Conditions for branch instructions
• Examples : fE
B label ;Branch unconditionally to label
O
BCC label ¡Branch to label if carry flag is clear
BEQ label ;Branch to label if zero flag is set
e

Example 5.4.1 Write a program to add 24 to R1 register 100 tinmes, then place the sum in
g

R3. Also draw flowchart.


le

Solution:
ol

Initialize counter = 100


AREA PROG4 1 1, CODE, READONLY
C

ENTRY
Sum=0
LDR RO,=100
:
RO = 100, initialize counter
u

;with decimal value 100


Sum = Sum +
24
ad

MOV R1, #0 ;R1 (sum) = 0


ADD R1, R1, #24 R1= R1 + 24
AGAIN : Decrement counter
iln

-
SUBS RO, RO, #1
:
RO= and set the
RO 1
Decrement counter
: flags.
m

Is counter
BNE AGAIN ;Repeat until value in No zero?
counter (RO) = 0
Ta

;
Yes
; (i.e., Z= 1)
; Store the sum in R3
MOV R3, R1 Save result
HERE ;
HERE
B
Stay here
END Fig. 5.4.18

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 237 of 446

Embedded Systems and loT Design 5- 50 ARM Processor

Example 5.4:2: Write a program to place value OxAA55 into 100 bytes of
RAM locations from
address 0x3000000.
Solution:
AREA PROG4 1
2, CODE, READONLY
ENTRY

g
RAM L0C EQU 0x30000000 ; change the address for your ARM

in
LDR R1, =RAM LOC ;R1 = RAM Address

er
LDR RO, =0xAA55AA55 ; RO = 0xAA55AA55 (4 bytes)
value to be loaded
;
in one go.

e
MOV R2, #25 ;Initialize counter =
25 decimal

in
:(25 x 4bytes = 100
bytes)

ng
AGAIN STR RO,[R1] ;
Send it to RAM
ADD R1, R1, #4 ;R1 = R1 + 4 to increment memory
SUBS R2, R2, #1 pointer
BNE AGAIN
; R2 = fE
R2- 1 for decrement counter
;Repeat until value in counter (R2) = 0 (i.e., =
HERE B HERE ;Stay here
Z 1)
O
END

5.4.5.1
e

Use of Comparison Instruction


g

The CMP instruction comnpares


two operands and changes
le

the result of the comparison. the flags according to


is discarded; however, Op2 is subtracted from Rn - Op2),
flags are set accordingly. (Rn and the result
ol

unchanged. Theoperands themselves remain


C

Syntax : CMP Rn,Op2 ;compare


Rn with Op2 and set
If Rn > Op2:C= the flags
and = 0
u

1 Z

If Rn = Op2 : C= 1 and Z
ad

=1
If Rrn <
Op2 : C= 0 and Z = 0
iln

Example.5.43 Write a program to divide. 32-bit


number by 16-bit
Kalso. number. Draw flowchart
m

Solution :
Ta

AREA PROG4_1_3, CODE, READONLY


ENTRY
LDR RO, Number1 ;Load Dividend
LDR R1, Number2 ;Load Divisor
MOV R3, #0 ;
Clear register for quotient
LOOP CMP R0, R1 ;
Is the dividend less than
BLT Done
ithe divisor ?
;If so, finished
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 238 of 446

Embedded Systems and loT Design 5-51 ARM Processor

SUB R0, RO, R1 ;


Dividend = Dividend - Start
Divisor
ADD R3, R3, #1 Add one to quotient Get the dividend
B LOOP Repeat
Done STR RO, Remain ;Storethe remainder Get the divisor
STR R3, Quotient ;
and the quotient

g
HERE B HERE ;Stay here Quotient = 0

in
AREA Data1, DATA

er
Number1 DCD &1234ABCD A 32-bit binary number
Number2 DCD &2152 ; 16-bit
number

e
Yes ls
ALIGN dividend

in
divísor
AREA Data2, DATA

ng
Quotient DCD 0 ;Storage for result
No
Remain DCD 0 ;Storage for remainder
ALIGN fE Division = Dividend-Divisor
END
O
=

5.4.5.2 Use of TST (Test) Instruction Quotient Quotient +.1


e

The TST instruction checks the register contents


g

to see if any bit is set to HIGH. After the


le

operands are ANDed together, the flags are Remainder = Dividend


updated. However, the operands themselves
ol

remain unchanged. After the TST instruction, if


C

one Store the quotient and remainder


the result is zero, then the Z flag is set, and
can use BEQ (brarnch equal) to make the
u

End
decision.
ad

; Rn AND with Op2 Fig. 5.4.19


Syntax : TST Rn, Op2
iln

and flag bits are updated


Example 5.4.4 Write a program to check pin 3 of the inpiut port assigned with address
m

0x30000000, If Pin3 is high store OxFF in R4; otherwise, store Ox00 in R4.
Ta

Solution :
AREA PROG4 1 4, CODE, READONLY
ENTRY
INPORT EQU 0x50000000
;RO=0x080 (00001000 in binary)
MOV RO, #2 00001000
LDR R1,=INPORT :R1 = port address
;Get a byte from PORT and place it in R2
LDRB R2,[R1]
;Is bit 3 LOW?
TST R2,RO
;Check for Z flag, if Z= 0 (pin3 = HIGH) go to NEXT
BNE NEXT

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 239 of 446

Embedded Systems and loT Design 5-52 ARM Processor

MOV R4, #00 ; if = 1, R4 = 00


Z
B LAST Skip next instruction
=
; R4 0xFF
NEXT MOVR4, #0xFF
; Stay here
LAST B LAST

5:4.5.3 Use of TEQ (Test Equal) Instruction

g
The TEQ instruction checks to see if the contents of the two registers are equal.

in
The source operarnds are Ex-ORed together, and the flag bits are set according to

er
the result. After the TEQ instruction, if the result is 0, then the Z flag is set, and
one can use BEQ (branch zero) to make the decision. Recall that if we

e
Exclusive-OR a value with itself, the result is zero. The operands themselves

in
remain unchanged.

ng
Syntax : TEQ Rn, Op2 ; Rn EX-ORed with Op2 and flag bits are set.
Example5.4:5 Write a program to check the contents of the input port assigned with address
fE
Ox50000000. The program should continuously monitor the port contents
until they are
equal to 60 in decimal. Once port contents are 60, make R3 = 0.
O
Solution :
e

AREA PROG4 15, CODE, READONLY


ENTRY
g

INPORT EQU0x30000000
le

MOV RO, #60 ;RO = 60


ol

LDR R1,=INPORT ; R1 = port


address
AGAIN LDRB R2,[R1] ;Get a byte
C

from PORT and place it in R2


TEQ R2, RO ;Is it 60?
u

BNE AGAIN :Check for Z flag, if Z= 0 keep checking


;If = 1, R3 = 00
ad

MOV R3, #00 Z

LAST B LAST ;Stay here


iln

5.4.5.4 Short Branches and Calculating Short Branch Address


As mentioned earlier, for B
m

and BL branch instructions (conditional and


unconditional) are short jumps, meaning
the target's address must be within 32M
Ta

bytes of the program counter (PC). That means


entire address space of 4G bytes (0x00000000 to the short jumps cannot cover the
OxFFFFFFFF).
As shown in Fig. 5.4.20, the offset
is 24-bit, and it is automatically
by the ARM CPU. That gives us a multiplied by 4
26-bit offset. This signed
value of the program counter. If offset is relative to the
If the relative offset is negative,the relative offset is positive, the jump is forward.
can cover memory space then the jump is backwards.
of -32 Mbytes to +32 Mbytes The relative offset
the program counter. from the current location o

TECHNICAL PUBLICATIONs
- an
up-thrust for knowledge
<br>

Page 240 of 446

Embedded Systems and


loTDesian ARM Processor
5-53

24-bits

31 28 27 26 24 23
Cond 1.01 L 24-bit signed word offset

26-bits 32-bits
the next instruction to be fetched

g
Offset Address of
0|o

in
Sign or
direction bit

e er
in
Program counter

ng
fE
To word aligned program memory

Fig. 5.4.20 Address generation in case of short branch instructions


O
54.5.5 Branching Beyond 32 M Byte Limit
we use BX (branch and
To branch beyond the address space of 32 M bytes,
e

uses register Rn to hold the target


exchange) instruction. The "BX Rrn" instruction
g

address.
le

are 32-bit registers, the "BX


Since Rn can be any of the RO-R14 registers and they
4G bytes address space of the ARM.
ol

Rn" instruction can jump anywhere in the


is copied into the
C

In this instruction, the target address stored in the register


CPU starts to fetch instructions from
the taroet
program counter (R15), and the
u

program counter.
address pointed to by the
ad

Review Questions
iln

processors.
types of branch instructions stupported by ARM
I. Explain various
m

functionality.
List any six conditional
branch instructions with their
?
range for short branch instructions
Ta

O. What is the address 2

address calculated in case short branch instructions


of

How is the branch target

b45.6 Subroutine Instructions a


a sequential group of instructions stored in-the memory at
A
subroutine is
tasks that need to be
performed frequently. Whenever
specific address to, perform program control is transferred
it is necessary to accomplish
that particular task, A
subroutine. subroutine is executed, and then
from the main program to the program.
back to the main
Program control is transferred

PUBLICATIONS® an up-thrust for knowledge


TECHNICAL
<br>

Page 241 of 446

ARM Processor
Embedded Systems and loT Design 5-54

(BL), to transfer
The ARM processors provide special instruction, Branch with Link
control to subroutines and restore program control to the main program.
to
• Like Branch instruction, Branch with Link (BL) instruction also uses 24-bits offet
generate the address of the target subroutine. See Fig. 5.4.21.

g
Program counter (R15)
Step
1

in
Link regtster (R14)

er
24-bits

e
in
o1
Step 2
Cond 1 24-5t signed word offset

ng
26 bits 32 bits

Offset jolol Address of the net instruction to be fetched

Sign or
directon bt
fE
O
e

Program counter
g

Fig. 5.4.21 Exocution of BL


Instructlon
le

• BL instruction saves the address of the next


instruction to be fetched in the Link
ol

Register (LR) before placing the starting address of


the subroutine in the program
counter.
C

When the subroutine completes its task, the processor


copies the value stored in
the link register to the program counter, which
u

returns the control to the next


instruction from which the subroutine was called.
ad

Example 5.4.6 Write a subroutine,


SUM, that adds the values of two
iln

arguments and returns


a result in R0.
Solution:
m

AREA PROG4 2 1, CODE,READONLY


Ta

ENTRY
MOV RO, #10 ;Load number1
MOV R1, #3 ;Load number2
BL SUM
;Call subroutine
AGAIN B AGAIN :Stay here
SUM ADD RO, RO, R1
:Subroutine
BX LR code
Return from subroutine
END ;Mark end
of fle

TECHNICAL
PUBLICATIONS
on up-thrust
for knowledge
<br>

Page 242 of 446

Embedded Systems and loT Design


5-55 ARM Processor
Example 5.4.7Write a program to toggle all the bits aaddress 0x30000000 by continuously
of

sending the values 0x55 and 0xAA. Put a time delay between each issuing
of data to
address location.
Solution:
program
:-Main
AREA PROG4_2_2, CODE, READONLY
ENTRY

g
RAM LOCEQU 0x30000000 ; Initialize memory pointer

in
LDR R1,=RAM ADDR ; R1 = RAM address

er
AGAIN MOV RO Ox55 ;RO = Ox55
STRB RO, (R1] ;Send it to RAM

e
in
BL DELAY ;Call DELAY subroutine
:(R14 = PC of next instruction)

ng
MOV RO, #0xAA ; RO = OxAA
STRB RO, [R1] ; Send fE
it to RAM
BL DELAY ;Call DELAY subroutine
B AGAIN ;Repeat
O
iDELAY Subroutine
DELAY :R2 =5000, Initialize counter for delay
e

LDR R2,=5000
SUBS R2, R2, #1 ;
Decrement counter
g

L1
:If counter not zero, repeat
le

BNE L1
BX LR :If counter = zero, retum to main program
ol

nd DELAY subroutine
of
; END directive
C

END
Example 5,4.8 Write
aprogramn to store a value Ox5A in 200 consecutive iocations of a
u

memory block starting from 0x30000000 and then copy the block to a
new area of memory.
ad

Solution:
iln

;
Main Program
AREA PROG4 2 3, CODE, READONLY
m

ENTRY
;Asign memory pointer to the source block
BLOCK1 ADDR EQU 0x30000000
Ta

BLOCK2 ADDR EQU 0x40000000


¡Asign memory pointer to the destination
block source
block
BL SAVE :Call subroutine to load values in
: Call subroutine to transfer values to destination block
BL COPY
HERE B HERE
;Stay here
iSave Values Subroutine source block
ADDR Imitialize memory pointer to the
SAVE LDR R1,= BLOCK1 : Initialize counter 50 (200/4)
MOV RO, #50 ;
R2 = Ox5A5A5A5A
LDR R2,=0x5A5A5A5A
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 243 of 446

Embedded Systems and loT Design 5- 56 ARM Processor

LOOP STR R2, [R1] ;Store values to 4 memory location simultaniously


ADD R1, R1 ,#4 ;R1= R1 + 4 to increment memory pointer by 4
-
SUBS R0, RO, #1 ;RO = RO 1 for decrement counter
BNE LOOP ;If count not zero, repeat
BX LR ;Return tomain program

g
; Block Copy Subroutine

in
COPY LDR R1,= BLOCK1 ADDR ; Initialize memory pointer to the source block
LDR R2,= BLOCK2 ADDR ; Initialize memory pointer to the destination block

er
MOV R0, #10 ;Initialize counter 50 (200/4)

e
REP1 LDR R3, (R1] ;Read 4 bytes of
data from the source memory block

in
STR R3, (R2] ; Save 4 bytes of data in the destination memory block
ADD R1,R1,#4 ;R1 = R1 + 4, increment pointer for RAM1

ng
ADD R2,R2,#4 R2 = R2 + 4, increment pointer for RAM2
SUBS R0,RO,#1 :R0 = RO - 1, decrement counter
BNE REP1 ;If count not zero, repeat

END
BX LR ;Retum fE
to main program
;END of program
O
Review:Quèstions
e

1. What is subroutine ?
g

2. How subroutine implemented in ARM ? Explain with


le

the help of an example.


3. Explain the diference between B and BL instructions.
ol

5.5 Implementation of C Language Statements


using ARM Assembly
C

Example 5.5.1 Write ARM instructions to implement statementyp + O:


O) -R;
u

Solution: The code for the given statement is as follows:


ad

ADR r4,P ; Get address for P


LDR r0,r4] ;Load value of P
iln

ADR r4,a ;
Get address for 0
LDR r1,[r4] ;Load value of a
m

ADD r3,r0,r1 ;Set partial


result for Y in r3 = P+O
Ta

ADR r4,R ;Get


address for R
LDR r2,[r4] ;Load value
of R
SUB r3,r3,r2 ;Complete the computation : (P + a) –R
ADR r4,Y ;
Get address for Y
STR r3,(r4] ;Store the result of (P t a)- R at location Y

Example 5.5.2 Write ARM instructions to


implement if statement
Solution:Let us implement the following if statement as an
example :
if (P < O)

TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
<br>

Page 244 of 446

Ernbedded Systems and loT Design


5-57 ARM Processor
3;
R=
S= 8;
}

else Z = 5;
. Two code blocks are used in the implementation :

.T Block : for the true case and

g
. F_Block : for the false case.

in
: Compute and Test the Condition

er
ADR r4,P ;Get address for P

e
LDR ro,[r4] ;Load value of P

in
ADR r4,a ;Get address for a
;Load value of a

ng
LDR r1,(r4]
CMP ro, r1
BGE F Block
; Compare P < Q
;if P ,
>= take branch fE
;T Block Code
O
MOV rO,#3 ; Load value for R
ADR r4,R ;
Get address for R
e

;
STR r0,(r4] Store value of R
g

MOV rO,#8
;
Load value for s
le

ADR r4,S :Get address for


ol

STR r0,(r4] ;
Store value of S
;Branch after the false block
B Skip
C

;F_Block Code
u

F
Block MOV r0,#5
:
Load value for Z
ad

ADR r4,2
;
Get address for Z
;Store value ofZ
STR r0,[r4]
iln

Skip :code after the if statement


Example 5.5.3 Write ARM instructions to implement
C switch statement.
m

:
has the following form
Solution:The switch statement in
C
Ta

switch (test)
{

case 0:
.. break;
...
case 1: break;

so on, the above expression might be coded


By first testing test_A, then test_B and can be implemented more effectively by
to look like an if statement. However, it
base-plus-offset addressing.
creating a branch table and using
-
TECHNICAL PUBLICATIONS an up-thrust.for knowledge
<br>

Page 245 of 446

Embedded Systems and loT Design 5-58 ARM Processor

Here, the branch table (S_Table) holds the addresses for the blocks of code that
implement the various cases.
ADR r2,test ;Get address for test

LDR r0,r2] :Load value for test as an offset

ADR r1,s_Table ; Load address for switch table

g
LDR r15,(r1,r0,LSL #2]: LDR instruction shifts the value of r0 left two bits to turn the

in
:offset into a word address. It adds the left-shifted value of the offset

er
:(held in r0) to the address of the table's base held in r1, and sets the
;PC (r15) to the new address computed by the instruction.

e
in
S
Table DCD case0

ng
DCD case1

case0 :
Code for case 0
fE
O
B Skip ;Branch after the Switch code
e

case1 :Code for case 1


g
le

B Skip ;Branch after the Switch code


A separate block of code in memory is used to
ol

implement each case. The branch


table starts at the S_table location.
The branch table stores the addresses
C

starting points of the Case blocks because, in of the


a 32-bit address of the this code, the DCD instruction loads
starting points of the blocks that
u

into menmory. correspond to the cases


ad

. BSkip instruction implements the break statement


of C code.
Example 5.5.4 Write ARM
iln

instructions to implement the


followingC code for adding
numnbers in the array.
m

int sum_code(int *num)


Ta

unsigned int i;
int sum = 0;
for (i = 0;
i<
64; i++)
sum += num[i]:

returmn sum;

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 246 of 446

Embedded Systems and loT Design 5- 59 ARM Processor

solution: Let us see the ARM code.


MOV R2, RO ; R2 = base address of num array
MOV RO, #0 ;
sum= 0
MOV R1,#0 ;i=0, initialize loop counter = 0
LOOP: LDR R3,(R2,FR1,LSL #2]: R3 = num[i], content of location R2+(R1x4) is loaded to R3
ADD R1,R1,#1 ;R1 = R1 + 1 i.e., i = + 1
i

g
CMP R1,#0x40 ; compare i, 64

in
ADD RO,R3,RO ; sum += R3
BCC LOOP ;if (i < 64), repeat

er
MOVPC,R14 ; return sum

e
in
ng
fE
O
g e
le
ol
C
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS
- an up-thrust for knowledae
<br>

Page 247 of 446

UNIT II

6 Central Processing Unit

g
in
e er
in
Syllabus
CPU- Programming Input and Output - Supervisor Mode - Exceptions and Trap.

ng
Contents fE
6.1 Introduction
6.2 Programming Input and Output
O
.6.3 Supervisor Mode, Exceptions and Traps
g e
le
ol
C
u
ad
iln
m
Ta

(6 - 1)
<br>

Page 248 of 446

Embedded Systems and loT Design 6-2 Central Processing Unit

6.1 Introduction
• In computer systems, interfacing refers to how different hardware or software
components communicate and interact. This can involve sending and receiving
data, control signals and more. Effective interfacing is crucial for the proper
functioning of a system.

g
This chapter will discuss input and output mechanisms, particularly interrupts and

in
introduce similar mechanisms for handling internal events. These internal

er
event-handling mechanisms are often used for managing processes and system
events within a computer system, distinct from external interrupts that harndle

e
hardware-related events.

in
ng
6.2 Programming Input and Output
Fig. 6.2.1 shows the structure of a typical I/0 (Input/Output) device
fE and its
relationship with the CPU. It involves the use of registers as the interface.
O
e

Status
g

register
le

CPU
ol

/O
Device
machanism
C
u

Data
register
ad
iln

Fig. 6.2.1 Strucutre of a typical


/O device
m

The interface between the CPU and the device


primarily relies on registers. These
Ta

registers communicate between the CPU


and the device's internal components.
There are two types of registers :

Data registers : Data registers store values that


the device interprets as data.
They can, for example, hold data that is read from or
written to a disk drive.
Status registers : .
Status registers provide information about the device's
ongoing or completed operations. They provide information such as whether
the current transaction (e.g.,data transfer) has completed.

TECHNICAL PUBLICATIONS- an up-thrust


for knowledge
<br>

Page 249 of 446

Embedded Systems and loT Design


6-3 Central Processing Unit

Registers can have different properties. Some may be read-only, which means the
CPUcan only retrieve information from them. An example a status
is register that
indicates when the device has completed a task. Others may be both readable and
writable, allowing the CPUto retrieve and update information in those registers.

6.2.1 Input and Output Primitives

g
Most of the processors support isolated I/O systems. It partitions memory from

in
I/0 via software by having instructions that specifically access (address) memory

er
and others that specifically access I/O. When the processor decodes these
instructions, an appropriate control signal is generated to activate either memory

e
or operation. I/O devices can be interfaced to a computer system I/O in two

in
I/0
ways, which are called interfacing techniques -

ng
IOmapped I/O: If we do not want to reduce the memory address space, we
allot different I/O address spaces for memory and I/O, called the I/O mapped
fE
IVO technique, as shown in Fig. 6.2.2.
O
e

Mermory Total
g

Address Address
Space Space
le

Address
Space
ol

(a) Memory space (b) VO space


C

Fig. 6.2.2 Address space


u

memory address space is


Memory mapped I/0 n this technique, the total
:
ad

as shown in
partitioned and part of this space is allotted to I/0 addressing,
Fig. 6.2.3.
iln
m
Ta

Memory
Address Total
Space
Address
Space

Address Space

Fig. 6.2.,3 Address space

PUBLICATIONS® - an
TECHNICAL up-thrust for knowledge
<br>

Page 250 of 446

Embedded Systems and loT Design 6-4 Central Processing Unit

Comparison between memory mapped /0 and /O mapped /O


Sr. Memory mapped I/O ta I/O mapped I/O
No.
1 Memory and I/0 share the entire address Processor provides separate address range
range of processor. for menory andI/0 devices.

g
2 Usually, processor provides more address Usually, processor provides less address

in
lines for accessing memory. Therefore lines for accessing I/0. Therefore, less
more decoding is required control signals. decoding is required.

er
3.
Memory control signals are used to control I/O control signals are used to control

e
read and write I/0 operations. read and write I/0 operations.

in
ARM supports a memory-mapped I/O interface and usually,
I/O registers are

ng
8-bits. Thus, LDRB instruction is useful for reading
the contents of I/0 registers
and peripheral ports.
• The
fE
I/O ports are generally 8-bit and take only one memory space location
(memory-mapped I/0). Thus, STRB instruction helps write
O
data from the CPU
register to I/0 registers and peripheral ports.
Let us see the typical code to read and
e

write the device register.


We can use the EQU pseudo-op to
g

define a symbolic name for the memory


le

location of our I/O device.


I0_D1 EQU Ox5000 ;Assigns a symbolic name for the memory
ol

;
location
of I/0 device
C

LDR r1,# 10 D1 ;Get


the device address
LDRB r0,[r1] :Read the data from I0 D1 (1/0 Device1)
u

LDR r0,#5 ; Load


the value to write
ad

STRB r0,[r1] ;Write 8-bit value to the device


Accessing WO devices using C language
iln

In C, when we declare and use a


variable, the compiler hides
memory address. However, the variable's
m

for I/0 devices


memory-mapped hardware, we can Or when working with
utilize pointers to access and
Ta

specific memory addresses. manipulate


Functions named peek() and poke() were
commonly used to read from
to arbitrary memory locations, and write
such as 1/0 device registers or
hardware. The peek() gets the byte memory-mapped
located at the specified memory
the poke() sets the memory byte at the specified address. address and

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 25 of 4461l

Embedded Systerms and loT Design 6-5 Central Processing Unit

The peek() can be written in C as :

int peek(char *M_Address)


{
return * M_Address; /* Returns the byte stored at specified
memory address */

With this peak), we can read the device status register as :

g
#define Status_ Address 0x1000 / Define device status register address */

in
er
D_Status = peek(Status_Address); /* Read device status register */
• The poke ) can be written as :

e
void poke(char *Data_ Address, char New Data)

in
{

ng
("Data_Address) = New Data; Write to device data register */

fE
• We can use the following code to write to the status register :
/* Write 5 to device status register */
poke(Status_Address, 5);
O
6.2.2 Busy-wait /O (Programed WO)
e

Busy-wait I/0 or Programmed I/0 is basic data transfer method where the CPU
a
g

actively controls data transfer to and from peripheral devices by sending


le

status
commands, managing data registers and continuously checking the device's
ol

until the operation is complete.


are generally
It is simple but inefficient. Devices like storage drives or peripherals
C

an
slower than the CPU. They might require many CPU cycles to complete
u

waste of CPU cycles.


operation, resulting in a significant
ad

Example 6.2.1 Write a C code to send a


sequence of characters to the output device using
iln

busy-wait I/0.
Solution:
m

:
The device has two registers
data to the device.
Ta

Data register Used for writing


:

is busy writing (status 1) or has


Status register: Indícates if the device
0).
completed the write operation (status to
To start writing, we must set the
output status register to 1 and wait for it
return to 0.
symbolic names for the register addresses :
Let us define
Output device data register "/
#define Out Data Ox2000
#define Out Status 0x2001 * Output device status register */
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 252 of 446

Embedded Systems and loT Design 6-6 Central Processing Unt

char * str = "Welcome" / Sequence of characters stored in a standard


C string "/
char *current ptr; / Pointer to current position in string."/
current ptr = str; / Point to start of string /
while (*current ptr l= \0) / until null character, i.e. end of the string "/
poke(Out Data,"current ptr): / send character to device /

g
poke(Out_Status, 1); Set the output status register to 1 /
keep checking status if status is l= 0/

in
while (peek(Out_Status) != 0): /*
current ptr++; /* Increment character pointer /

er
The outer while loop sends the characters one at a time until it reaches the end of

e
the string. The inner while loop checks the device status.

in
Example 6:2.2 Write a C code to copy characters

ng
from input to output using busy-wait I/0.
Solution:

A character should be read from the


fE
Consider the following points before starting to
write the code.
input device and written to the output
O
device repeatedly.
The input device sets its status register to 1 a new character
read; we must set the status register back to 0 when
e

has been
so that the device is after the character has been read
g

ready to read another character.


le

When performing a write operation, we


and ensure it equals 1 before sending must check the output status
register
ol

the next character.


#define In Data Ox1000
C

#define In Status Ox1001


#define Out Data Ox2001
u

#define Out Status Ox2002


ad

while (TRUE)
/ Perform operation forever
while (peek(In_Status) == 0);
/ Wait until input device /
iln

is ready with
=
ch (char) peek(In Data); character */
Read
m

poke(In_Status,0);:
the character /
/ Set the status register
poke(Out_Data,ch); back to 0 /
Ta

1 Write a character
in output data
register /
poke(Out_Status,1);
Set the output status
while (peek(Out _Status) I= 0): register 1
/ wait for write operation to to /
complete "l

6.2.3 Interrupts
Busy-wait I/0 is highly inefficient
because the CPU continuously
status while waiting for checks device
I/O transactions to finish. However, in many
scenarios,
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 253 of 446

Embedded Systems and loT Design 6-7 Central Processing Unit

the CPU could perform other tasks in parallel with I/O operations, such as
computations or managing other devices. To enable this parallelism, the interrupt
mechanism is introduced.
• The interrupt mechanism allows devices to signal the CPU and trigger the
execution of specific code.

g
When an interrupt occurs, the Program Counter (PC) is updated to point to an

in
interrupt handler routine, often called a Device Driver or Interrupt Service

er
Routine.
This routine handles the device's needs, like writing data or reading newly

e
available data.

in
The interrupt mechanism also saves the PC's value at the interruption, ensuring

ng
that the CPU can later return to the interrupted program. Interrupts thus facilitate
the smooth transition of control in the CPU between various contexts, such as
fE
foreground computations and multiple I/0 devices. This mechanism significantly
improves system efficiency by allowing the CPUto multitask effectively.
O
g e

Status
le

Interrupt request register


CPU
ol

Interrupt acknowledge
C

Data / address Device


PC machanism
u
ad

Data
register
iln

IIO Device
m

Flg. 6.2.4 Interrupt mechanism


Ta

As shown in Fig, 6.2.4, the I/O device asserts the interrupt request signal (IRO)
when it requires attention or service from the CPU. On receiving IRO signal. the
CPU asserts the interrupt acknowledge signal ((ACK) when it is ready to handle
the I/0 device's request.
• This acknowledgment indicates that the CPU has recognized the device's interrupt
request and is prepared to switch its execution context to service the device.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 254 of 446

ibedded Systems and loT Design 6-8 Central Processing Unit

omparison between programmed /O and interrupt driven /O


• Table 6.2.1 compares programmed I/O and interrupt-driven I/0.
Sr. Programmed I/O Interrupt driven I/O
No.
External asynchronous inpüt is used to tell

g
1 In programmed I/O, processor has to check
the processor that I/0 device needs
its
each 1/O device in sequence and in effect

in
'ask' each one if it needs communication with service and hence processor does not have to
check whether I/0 device needs it service or

er
the processor. This checking is achieved by
continuous polling cyde and hence processor not.
can not execute other instructions in

e
sequence.

in
2 During polling processor is busy and In intérrupt driven I/0, the processor is

ng
therefore, have serious and decremerntal effect allowed to execute its instructions in
on system throughput. sequence and only stop to service I/0 device
when it is told to do so by the device itself.
fE
This increases system throughput.
O
3. Itis implemented without interrupt hardware It is implemented using interrupt hardware
support. support.
e

4. It does not depend on interrupt status. Interrupt must be enabled to process interrupt
g

driven I/O.
le

5. It does not need initialization of stack. It needs initialization of stack.


ol

*******

6. System throughput decreases as number of System throughput does not depend on


I/0 devices connected in the system number of I/0 devices connected in the
C

increases. system.
u

Table 6.2.1 Comparison between programmed I/o and interrupt


driven /O
ad

Example 6:2:3 Write a C code to copy characters from input to output


with basic interrupts.
iln

Solution:
When an input interrupt occurs, it signifies that the input device is
ready with a
m

character and activates the input interrupt handler. Input


interrupt handler reads
the character and stores it in global variable ch. It also assigns a
Ta

TRUE value to
the global variable ch _ready, indicating the character is ready to output to another
device.
When an output interrupt occurs, it activates the output interrupt handler. Output
interrupt handler assigns a TRUE value to the global variable ch sent, indicating
that the character write operation is completed.
In the main program, there's a continuous process for sending characters to the
output device. The conditions for sending characters are as follows :
Character availability : The main program checks if the input device has
already read a character, indicating that theres data available for transmission.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 255 of 446

Embedded Systems and loT Desian Central Processing Unit


6-9

Write operation completion : It also verifies whether the previous write


operation to the. output device has been completed.
void input_handler) /* Called when In Status changes to 1*/
/* Read a character and put in global variable ch*/
ch = peek(In Data); /* Read the character */
ch_ready = TRUE; /* Indicates character is ready to output

g
in
to another device */
poke(n Status,0); /" Set the status register back to 0 */

e er
void output handler()

in
* Called when Out Status changes to 0*/

ng
ch sent = TRUE; /* Indicates character write operation completed */
}

main()
fE
O
while (TRUE) /* Read then write forever */
{ if (ch ready) * Check if character is ready to write */
e

if(ch_sent) * Checkif previous write operation completed "/


g

{ poke(Out Data, ch): /* Put character in device */


le

poke(Out_Status,1);: /* Set status to initiate write */


ol

ch ready = FALSE; * Reset character ready flag */


C
u
ad

request
• The CPU implements interrupts by continuously monitoring the interrupt
each instruction.
iln

line at the start of the execution of


CPU doesn't proceed to fetch the next
If an interrupt request is detected, the
m

• to
Counter (PC). Instead, it redirects the PC
instruction pointed to by the Program
of. the interrupt
Ta

a predetermined memory location, typically the beginning


handling routine. as a pointer in
address of the interrupt handler is often stored

The starting CPUdefines a memorv
memory. This approach allows flexibility because the
Consequently, the interrupt handler
location that holds the address of the handler.
can anywhere in memory, making it adaptable and more efficient
routine reside
sources and their respective handlers.
tor managing various interrupt
at every instruction they execute. This
CPUs continuously check for interrupts requests
to service from devices.
allows them to respond quickly

TECHNICAL PUBLICATIONS
- an up-thrust for knowledage
<br>

Page 256 of 446

Embedded Systems and loT Design 6-10 Central Processingg Unt

• It is crucial that interrupt handling is to return to the foreground program


(the program running before the interrupt) without disrupting its operation. This
is similar to how subroutines must return control to the calling program after
execution.
• Both subroutines and interrupt handlers typically use a stack to
remember the
return address. When a subroutine or interrupt is called, the address of the next

g
instruction to execute in the calling program is pushed onto the stack. This

in
ensures that after the subroutine or
interrupt harndling is complete, the CPU can

er
pop the return address from the
stack and continue executing the calling program.

e
6.2:4 Priorities and Vectors

in
6.2.4.1 Interrupt Priorities

ng
• The majority of systems
contain multiple I/O devices; hence, some mechanism
allowing multiple devices to interrupt for

• For the implementation


fE
must exist.
of an interrupt system that accommodates
multiple
O
handling routines and device addresses, I/0
devices with flexibility in interrupt
key approaches are commonly two
used :
e

Interrupt priorities : This mechanism


enables the CPU to differentiate
g

various interrupts based on between


their importance. Not all
interrupts are of equal
le

significance and assigning


priorities allows the system
interrupts over others. to precede specific
ol

Interrupt vectors : Interrupt vectors


C

respective interrupt handlers. allow interrupting devices


to specify their
vector, which contains Each device is associated with a unique
u

the address of its interrupt


occurs, the uses handler routine. an
CPU When
ad

the vector to locate interrupt


This flexibility allows and execute the appropriate
different devices to handler.
locations, making the system more have distinct handling
routines and
iln

• Prioritized interrupts adaptable.


enable the CPUto manage
priority levels. Fig. 6.2.5 multiple devices
m

shows the prioritized by assigring


Fig. 6.2.5, interrupts
from various devices are
interrupt system. As shown in
Ta

signals : INT 0, INT 1, INT 2 connected to the


usually given higher priority. and so on. Lower-numbered interrupt request
So, in this case, interrupt lines are
multiple devices request INT0 has the highest priority.
interrupts simultaneously, When
and handles the request from the CPU first acknowledges
the highest-priority device.

TECHNICAL PUBLICATIONS®
- an up-thrust for
knowledge
<br>

Page 257 of 446

Embedded Systems and loT Design


6-11 Central Processing Unit
Interrupt acknowledge
INTA

CPU Device 0 Device 1


Device N

INTO

g
INT 1

in
er
INT N

e
in
Fig. 6.2.5 Prioritized interrupt sytem

ng
Fig. 6.2.6 shows another way of handling multiple interrupts.
Here, interrupt
requests from various devices are routed through the OR gate to a single interrupt
signal.
fE
O
Interrupt acknowiedge
INTA
e

N
Device
g

Device 0 1.
Device
CPU
le
ol

INT
C

Fig. 6.2.6 Sharing interrupt signal using polling


u

are grouped, this handler doesn't


Since the interrupt requests for various devices
ad

inherently know which specific device triggered the interrupt. The handler checks
the status or conditions of the connected devices through polling to determine
iln

which one initiated the interrupt.


m

are
• Let us assume we have devices (A, B and C) and their corresponding priorities
sequence diagram in Fig. 6.2.7 shows which
Ta

(A': 1, B: 2, C: 3). The UML


as a function of time for a series of interrupt
interrupt handler is executed
requests. (See Fig. 6.2.7 on next page)
UML sequence diagram is as given beloww -
The sequence of events shown in the
t = 1: Device C generates an interrupt. Since
it is the only active interrupt
starts executing.
request at t = 1, the C interrupt handler
t = 2 : Device A generates an interrupt.
Because A has a higher priority
preempts the execution of the C interrupt
(priority 1) than C, the A interrupt
interrupt handler.
handler and starts executing the A

TECHNICAL
PUBLICATIONS - an up-thrust for knowledge
<br>

Page 258 of 446

Embedded Systems and loT Design 6- 12 Central Processing Unit

Time Interrupt Background


requests task B

g
A

in
e er
in
ng
6 fE
O
8
e
g

9
le
ol

|10 B
C

Fig.6.2.7 UMLsequence diagram showing execution of


interrupt handlers
t= :
u

3 Device B generates an interrupt. However, interrupt A


has a higher
ad

priority than B; its interrupt handler continues to execute until


it completes its
task.
iln

t= 4: Once the A interrupt handler completes its task, it may


check for any
pending interrupts with equal or lower priority. In this case, finds
it
m

the higher
priority pending interrupt as B and starts executing the B
handler. The B
interrupt handler continues to execute until it completes its task.
Ta

t=6 : Once the interrupt


B
handler completes its task, the system goes back
execute the C interrupt handler, to
which has been pending since the beginning.
t = 8: After completion of
execution of the C
interrupt handler, the system
does the execution of the background
task until the subsequent interrupt
request OCcurs.

TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>

Page 259 of 446

Embedded Systems and loT Desian


6-13 Central Processing Unit

6.2.4.2 Interrupt Vectors


An interrupt vector is a numerical identifier associated with a specific type of
interrupt or device. It serves as a unique identifier for different interrupt sources
or devices.
When a device sends an interrupt request, it waits for the CPUto acknowledge it.

g
Once accepted, the device sends its interrupt vector number over the interrupt

in
vector lines to the CPU.

er
As shown in Fig. 6.2.8, the CPUmaintains an Interrupt Vector Table (IVT) in

e
memory. This table contains entries for each possible interrupt vector number.

in
Each interrupt vector entry in the table points to the memory address of the

ng
corresponding interrupt handler.

Interrupt fE 1
VT
Vector 0 Handler
request head
I/O Vector 1 Handler3
O
CPU Interrupt
device
acknowledge 2
Vector3Handler
g e

Interrupt vector
le

Vector N
ol

Interrupt Vector Table (VR)


C

Fig. 6.2.8 Interrupt vectors


u

a it uses the interrupt


When the CPU receives an interrupt vector from device,
ad

handler associated with


vector table to read the memory address of the interrupt
iln

that vector.
by jumping to the memory
The CPU then transfers control to the interrupt handler
m

vector table.
address provided by the interrupt
a crucial mechanism in computer
systems for efficiently
Ta

Interrupt vectors are


requests from various devices. They enable the CPU to quickly
handling interrupt vector
execute the appropriate interrupt handler using the interrupt
identify and
table. to consider -
has two crucial aspects
The interrupt vector mechanism : store and transmit their interrupt
Device-initiated vector numbers Devices
CPU. Thus, it is possible to assign' a new handler to it by
vector numbers to the a device sends without changing the
vector number that
simply changing the through programmable switch
settings.
system software. This can be done
<br>

Page 260 of 446

Embedded Systems and loT Design 6- 14 Central Processing Unit

No fixed relationships : The interrupt vector mechanism doesn't enforce fixed


pairings between vector numbers and handlers. Instead, it uses an
interrupt
vector table, enabling arbitrary relationships, which offers .

flexibility in
connecting hardware devices and software routines.

Steps involved in handling interrupts using IVT

g
CPU check : The CPUchecks for pending interrupts before
each instruction and

in
responds to the highest-priority one.

er
Device interaction : Once the CPU accepts
the interrupt request, it sends the
corresponding acknowledgment. After receiving acceptance,
the device sends an

e
interrupt vector to the CPU.

in
• Vector lookup: The
CPUuses the vector to find the handler's address
in an IVI,

ng
saving its state.

Software handling: Software (device driver or


and restores the saved state.
fE
ISR) performs device-specific
tasks
Return to normal : The CPUexecutes an
O
interrupt return instruction to resume
interrupted program. the
e

6.2.5 Interrupts in ARM


g
le

ARM processor supports two types


of interrupts :
External (Hardware) and
Software.
ol

• Hardware interrupt : This type


of interrupt causes an
C

external peripheral. These are IRQ exception raised by an


and FIQ.
Software interrupt : This type a
u

is specific instruction
SWI instruction. that causes an exception
ad

Both types suspend the


normal flow of a program.
iln

Software interrupts :
These are typically
system routines. For reserved to call privileged
example - an SWI instruction. operating
m

program running user It can be used to


in mode to a privileged mode. change a
Ta

Interrupt Requests (IRQ) :


These are generally
interrupts. The IRQ exception assigned for general-purpose
time than the FIQ exception. has a lower priority and higher interrupt response
Fast Interrupt Requests
source that (FIQ) : These are
requires a fast response typically reserved for a
time - for example, single interrupt
specifically used to move memory direct memory access
blocks.
The ARM7 processor follows
specific steps when
when leaving an interrupt handler. responding to an interrupt
and
TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>

Page 261l of 446

Emboddod Systems and loTT Design 6- 15 Central Processing Unt

When responding to an interrupt :


Save PC : The ARM7 saves the current value of PC for later use.
Copy CPSR to SPSR : Copies the current program status into a Saved Program
Status Register (SPSR).
Disable interrupts : IRQ or both IRQ and FIQ interrupts are disabled in the
CPSR to stop subsequent interupts.
Sets the PC with the memory address of the interrupt

g
:
Set PC to vector

in
handler routine.

er
When leaving the interrupt handler :
Restore PC: Retrieves the saved PC value to resume the interupted program.

e
. Restore CPSR : Restores the program status from the SPSR.

in
Clears interrupt disable flags to enable subsequent interrupts.
:

ng
Clear flags
an external interrupt request
Interrupt latency : It is the interval of time from
signal being raised to the first fetch of
an instruction of a Specific Interrupt Service
fE
Routine (ISR).
O
to respond to an interrupt is
• In ARM processor system, the worst-case latency
27 clock cycles
e

Two cycles for external request synchronization.


g

current instruction.
Up to 20 cycles to complete the
le

Three cycles for data abort and


ol

handling state.
Twocycles to enter the interrupt
C
u

Review Questions
ad

a typical I/O (nput/Output) device.


1. Drav and explain the structure of
iln

?
2. What is I/O mapped /O technique
3.. Explain memory mapped /0 technique.
m

techniques.
and memory mapped l/O
mapped
.Give comparison between I/O example.
transfer method with a programming
Ta

3. Explain the busy-wait I/O data


mechanism.
0. Write a note on the interrupt
programmed T/O and interrupt-driven /0.
Give a comparison between
basic interrupts.
C code to copy characters from input to output with
O. Writea
9. Writea note on interrupt priorities. sequence diagram.
mechanism using the UML
Explain the interrupt priority
011.
. Write a note on interrupt
State the stens inpolved in
Explain the various internupts
vectors.
handling interrupts using IVT.
supported by the ARM
processor.

PUBLICATIONS - an up-thrust for knowledge


TECHNICAL
<br>

Page 262 of 446

Embedded Systems and loT Design 6- 16 Central Processing Unit

6.3 Supervisor Mode, Exceptions and Traps

6.3.1 Supervisor Mode


Complex systems often consist of multiple programs that run under the control of
an operating system and need to communicate with each other. It may be helpful

g
to include hardware checks to ensure that these programs do not interfere with

in
each other, especially by accidentally overwriting or accessing each other's

er
memory.
We can use software debugging to identify and fix these program issues; however,

e
it may not catch all problems and some issues may still persist in a running

in
system. Hardware checks provide extra safety.

ng
Supervisor mode, often referred to as privileged mode or kernel mode, is
-

introduced in ARM processors and in many other CPU architectures to provide a


fE
higher level of control and privilege to the operating system or
trusted system
software. In supervisor mode, programs have higher privileges
than regular user
O
mode programs.
For examnple, in memory management systems that facilitate
e

the dynamic alteration


of memory location addresses, the control over
g

the Memory Management Unit


(MMU) is restricted to supervisor mode.
le

This precautionary measure prevents


potential issues from programming errors that
might unintentionally modify the
ol

memory managerment registers.


C

ARM architecture provides a supervisor


mode. The ARM7 enters this mode after
reset. However, we can activate
supervisor mode using the ARM instruction
u

known as SWI when ARM is in user mode.


ad

• Like any
other ARM instruction, SWI can be
executed, it initiates the executed conditionally. When SWI is
transition of the CPU into
iln

simultaneously sets the Program supervisor mode and


Counter (PC) to Ox08. The SWI
24-bit immediate value as instruction takes a
its argument, subsequently transmitted
m

mode code. This argument serves as a to the supervisor


means for the program
to request various
Ta

services from the supervisor mode.


When the processor switches to
supervisor mode, the bottom
Program Status Register (CPSR) are 5 bits of the Currernt
set to 1. This is to
now operating in supervisor indicate that the CPU is
mode.
Before executing a SWI
instruction or any other
switch, the processor typically saves instruction that causes a mode
the old CPSR into a special
Saved Program Status Register register called the
(SPSR). Each processor
the supervisor mode SPsR is called SPSR svc. mode has its own SPSR;

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 263 of 446

Embedded Systems and loT Design 6- 17 Central Processing Unit

6.3.2 Exceptions
Interrupts and exceptions are both mechanisms used in computer systems to
handle changes in the flow of control of a program, but they serve different
purposes and are triggered in different ways.
Interrupts are signals external hardware devices send to the CPU to request

g
attention. They are asynchronous events that can occur at any time. They are used

in
to handle events external to the normal program execution, such as hardware

er
errors, keyboard input or incoming data from a network.
Exceptions, on the other hand, are events that are generated internally by the PU

e
or program itself during its execution. Exceptions are synchronous events and are

in
often caused by conditions like division by zero, invalid memory access or other

ng
exceptional situations that occur while the program is running.
When an exception occurs, the CPU interrupts the normal flow of program
fE
execution and transfers control to an exception handler specified in the program or
error
the operating system. The purpose of exceptions is to allow for graceful
O
handling and recovery within the program.
an instruction, such as :
Exception occurs as a direct result of executing
e

Software Interrupt Instruction (SWI).


g
le

Undefined or illegal instruction.


an instruction.
ol

Memory error during fetching


memory.
Memory fault during data read/write from
C

Arithmetic error (e.g. divide by zero).


u

prioritization and vectoring.


• Like interrupts, exceptions in general, require both
ad

necessary because a single operation can lead to the


In exception, prioritization is
essential to determine which excenion
generation of multiple exceptions and it's
iln

should be handled first.


user to specify the handler for the exception
m

• Like interrupts, vectoring allows the


Ta

condition.

6.3.3 Traps
or the
A trap exception is a specific type of exception
that occurs when a program
a
operating system intentionally generates an exception condition using software
interrupt. to a
are used to change the normal flow of program execution
Trap exceptions
predefined exception handler associated with or that specific trap. This controlled
system-level operations.
diversion allows for the execution of privileged
-
TECHNICAL PUBLICATIONS an up-thrust for knowladge
<br>

Page 264 of 446

Embedded Systems and loT Design Central Processing


6-18 Unit

the primary uses of trap exception is facilitate the transition


to
One of from user
a
mode to supervisor mode, The entry into supervisor mode is critical operation
from a security perspective.

Review Questions

g
1. What is superoisor mode ?

in
2. Write a note on exceptions and traps.

e er
in
ng
fE
O
g e
le
ol
C
u
ad
iln
m
Ta

TECHNICAL PUBLICATIONS
- an up-thrust
for knowledge
<br>

Page 265 of 446

UNIT II

Program Design
7 and Analysis

g
in
e er
in
Syllabus
Models for programs - Assembly,

ng
Linking and Loading - Compilation Techniques - Program Level
Performance Analysis.

Contents
fE
O
7.1 Models for Programs
7.2 Assembly, Linking and Loading May-18, Dec.-21, Marks 8
e

Marks 8
7.3 Compilation Techniques. May-17, 21, Dec.-17, 21
g

7.4 Program Level Performance Analysis.May-17, Marks 8


le
ol
C
u
ad
iln
m
Ta

(7-1)
<br>

Page 266 of 446

Embedded Systems and loT Design 7-2 Program Design and Analysis

7.1 Models for Programs


can be
Writing code in various languages, such as assembly, C, etc., is specific and
complex to analyze. To simplify this, developers create models for programs that
are more general than source code. These models make program analysis and
manipulation easier, making optimization and code generation more efficient.
• Here, we discuss the Control/Data Flow Graph (CDFG) as a fundamental model

g
for programs. It can also be used to represent hardware behavior.

in
This graph has constructs that model both data operations (e-g., arithmetic

er
calculations) and control operations (e.g., conditionals). The strength of CDFG lies

e
in its ability to combine both control and data elements seamlessly. To
comprehend CDFG, we begin with pure data descriptions and then gradually

in
introduce control-related components into the model. This integration of data and

ng
control aspects makes CDFG a powerful tool for program and hardware modeling.

7.1.1 Data Flow Graph fE


• A data flow graph focuses on the flow of data within a program and it does not
O
represent the program's control flow, which may involve conditionals and loops.
• In high-level languages, a sequence of statements with a single entry and exit
e

point without control statements is called a basic block.


g

Fig. 7.1.1 shows a simple basic block in C. In this basic block, the variable x has
le

been assigned twice on the left side of an assignment.


ol

W = p+ q;
C

X = r- S;
u

W =p-I;
ad

y = X + s;
Z = y + t;
iln

Fig. 7.1.1 Basic block in C


• The variable can appear only once on
m

the left side in the single-assignment form.


Because of this, in this case, to distinguish
between multiple w assignments, we
Ta

assign separate names like w1 and w2 to indicate separate uses w.


of
w1 = P+ 4
X = r- s;
w2 = p-I;
y = X + S;

Z = y + t;
Fig. 7.1.2 Basic block in single assignment form

TECHNICAL PUBLICATIONs an up-thrust for knowledge


<br>

Page 267 of 446

Desian
Embedded Systems and loT 7-3 Program Design and Analysis

The single-assignment form is useful since it identifies an individual position in


the code where each designated location is computed. As an introduction to the
data flow graph, we use round nodes to represent operators and square nodes to
represent values.
The value nodes can be either inputs
to the basic block, such as p and q or E

g
variables allocated within the block,

in
such as w1 and y.

er
Fig. 7.1.3 shows the data flow graph
for a single assignment form. In

e
single-assignment form, the data flow
W. W

in
graph representing variable

ng
assignments is acyclic. This means that
the graph doesn't contain any cycles
or loops. Each variable is defined at fE
most once and the data flow goes
O
from the definition point to its uses
without any loops. Keeping the data Fig. 7.1.3 Data flow graph for basic block
e

flow graph acyclic is important for


g

various types of analyses performed


le

on the program.
ol

Typically, the data flow graph is


drawn as depicted in Fig. 7.1.4. In this
C

graph, variables are associated with W W2


as
u

the edges rather than represented


individual nodes. Due to this, it is
ad

more
possible to represent variable by
are
iln

than one edge. Here, the edges


a
directed and all of the edges for
m

variable come from a single source.


We chose this form since it is simple
Ta

Fig. 7.1.4 Standard data flow graph for


and compact. basic block
2
Control/Data Flow Graphs
constructs to describe control in the
A Control/Data Flow Graph (CDFG) adds
data flow graph.

TECHNICAL PUBLICATIONS an up-thrust for knowledae


<br>

Page 268 of 446

Embedded Systems and loT Design 7-4 Program Design and Analysis

In a basic CDFG, there are two types of nodes :


Decision nodes : Decision nodes are used in CDFGs to represent control flow
decisions, such as conditional branches and loops. These nodes typically have
two or more outgoing edges, each corresponding to a possible control flow
path depending on the outcome of the decision. A single type of decision node
can be used to represent all types of control
in a sequential program.

g
in
Data flow nodes : Data flow nodes in a CDFG encapsulate a complete
data
flow graph for a basic code block.

er
Fig. 7.1.5 displays C code containing control constructs
and the CDFG created

e
from it. A CDFG uses rectangular nodes to represent
basic blocks of code.
Diamond-shaped nodes represent conditionals

in
with labels indicating the conditions
(e.g., "True" and "False"). Edges
between nodes - are labeled with the possible

ng
outcomes of the conditions. This
graph shows how a program's control
branches based on conditions, facilitating flow
analysis and optimization.
fE
for (i = 0; i < N; i++)
{
i=0
O
basic block1():
e

C code
g
le

basic_block1(0:
ol

=i+1;
C

CDFG
u

while (p < )
ad

p= func1 (p, q); IT


q=
iln

func2 (p, g): p= func1(p, q):


q= func2(P, q):
m

C code
CDFG
Ta

Fig. 7.1.5

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 269 of 446

Embedded Systems and loT Desian


7-5 Program Design and Analysis
Example 7.1.1 Construct CDEG
for the switch statement in C

Solution:
Switch (choice)

case 1 :
basic_block_10:
choice
break;

g
case 2 : basic block_2():

in
break; 3
2

er
case 3 : basic block 30:
break;

e
basic_block_1(); basic_block_2( ): basic block_3();

in
C Code

ng
fE
O
CDFG

Fig. 7.1.6
g e

Review Questions
le

1. Outline the significance of CDFG.


ol

2. Construct a data flow graph and Control/ Data Flow Graph (CDFG) with an example.
C

:
3. Design a data flow graph for the block shoun below
r= a+b-c;
u

ar ;
ad

S=
t= b- d;
iln

r= d+e; necessary diagrams.


2. lustrate the Code/Data Flow Graph for a while loop with
m

72 Assembly, Linking and Loading AU May-18, Dec.-21


Ta

linking, which convert instructions


The final compilation steps are assembly and
memory. The program is loaded into
into an image of the program's bits in
can be executed.
emory during loading so that it
Fig. 7.2.1 shows program generation
from compilation through loading.
compilers do- not directly generate
Compiler : Ás shown in Fig. 7.2.1, most
an intermediate representation of the
machine code. Instead, they produce
assembly language. This choice allows
Programn in the form of human-readable

TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
<br>

Page 270 of 446

Embedded Systems and loT Design 7-6 Program Design and Analysis

High-level language program


(C program)

Compiler.

g
in
er
Assembly language program

e
in
Assembler

ng
Object code fE
O
Linker Object: library routine
g e
le

Executable binary/ machine language program


ol
C

Loader
u

Execution
ad

Main memory
iln

Fig. 7.2.1 Program generation


from compilation through loading
compiler writers to focus on the high-level
m

aspects of compilation without


with low-level details like instruction dealing
formats and memory,addresses.
Ta

Assembler : The assembler translates


symbolic assembly.language statements
bit-level representations of instructions into
known as object code. It handles
instruction formats and partially translates
not determine the final addresses labels into addresses. However, may
of instructions and data, especially
it
program comprises multiple files. when a
Linker : Linking is the step that follows assembly.
It involves combining multiple
object files generated fromn different source files
and resolving references between
them. The linker determines the final addresses of instructions
and data,
producing an executable binary file.
TECHNICAL PUBLICATIONS - an up-thrust
for knowledge
<br>

Page 27 l of 446

Embedded Systems and loT Design 7-7 Program Design and Analysis

Loader : The program responsible for bringing the executable program into
memory for execution is called a loader. It ensures the program is correctly placed
in memory and ready to execute.
Concept of absolute addresses and relative addresses in assembly language
programming
• In the simplest form of assembly language programming, the programmer

g
specifies the program's starting address. All addresses within the program are then

in
expressed as. absolute addresses, meaning they directly represent memory

er
locations.
• Using absolute addresses requires the programmer to determine and specity the

e
starting addresses for all modules before assembly. This can be cumbersome,

in
especially when dealing with multi-component programs.

ng
overcome the limitations
Many assemblers support the use of relative addresses to
of absolute addresses. With relative addresses, the programmer does not specity
fE
the starting address of the module at the beginning of the code. Here, addresses
within the module are computed relative to the start of that module. This provides
O
flexibility because the actual starting address can be determined during the linking
e

phase.
into absolute
g

The linker is responsible for translating these relative addresses


le

addresses.
ol

7.21 Assembler
C

mnemonics into binary


The assembler's main tasks include translating assembly
converting symbolic labels into
u

opcodes, formatting instructions correctly and


by assemblers,
actual memory addresses. Labels are crucial abstraction provided
ad

a
specific memory
allowing programmers to write code without worrying about
iln

locations. :

assembly language typically involves a two-pass


Label processing in
m

pass, the assembler scans the entire assembly


First Pass : During the first
each label.
source code and determines the memory addresses associated with
Ta

in the second pass


Second Pass The assembler assembles the instructions
:

pass. It substitutes the memory


using the label values computed during the first
to create machine-readable code.
addresses for the labels in the instructions
first pass and contains the names of all
A Symbol table is created during the
It is formed by scanning from the
symbols/labels along with their addresses.
source code.
first to the last instruction in the
memory is kept in a Program Location
During scanning, the current location in
memory locations to labels. Note that PLC is
Counter (PLC). It is used to assign
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
<br>

Page 272 of 446

Embedded Systems and loT Design 7-8 Program Design and Analysis

different from Program Counter (PC). Program Counter is the instruction pointer
that keeps track of the memory address of the next instruction to be executed.
During the first pass of assembly, the Program Location Counter (PLC) is
initialized to the program's starting address. The assembler examines each line of
code, incrementing the PLC by the appropriate instruction size (e.g., four bytes for

g
ARM instructions) after each line. If a line begins with a label, the assembler adds

in
an entry to the symbol table containing the label's name and current PLC value.

er
This value represents the memory address where the label is defined.
Once the first pass is complete, the assembler resets to the beginning of the

e
in
assenbly file for the second pass. In the second pass, when the assembler
encounters a label name in the code, it looks up the label in the symbol table and

ng
substitutes its value (memory address) into the appropriate position within the
instruction. fE
The ORG (origin) statement is a common pseudo-op
in assembly language
programming. It specifies the starting location or memory address for the
O
assembly program. For example, in ARM assembly,
e

ORG 100
The statement specifies that the starting
g

address of the assembly program is 100.


le

Exainple 7.21 Generate a symbol


table for the following ARM assembly code :
ol

ORG 100
label1 SUB r3,A
C

LDR r0,[r3]
label2 ADR r3,B
u

LDR r1,(r4]
ad

label3 ADR r0,r0,r1


iln

Solution :
. The ORG tells us to
set the PLC value to 100. Because
the ORG statement is a
m

pseudo-op that generates no memory


values, the PLC value remains at 100
second statement. The second statement for the
Ta

are four bytes long, is instruction and since ARM instructions


the PLC is incremented by value 4.
Here, the second instruction
begins with a label; hence, a new
symbol table. The new entry includes entry is made in the
the label name and its value.
• For every subsequent
instruction, the PLCvalue is
entry is added to the symbol incremented by 4 and a new
table if the instruction begins
. We continue this process as we scan
with a label.
the program until we reach the end, at which
the state of the PLC and symbol table are as
shown below.

TECHNICAL PUBLICATIONs
- an
up-thrust for knowledge
<br>

Page 273 of 446

Embedded Systems and loT Design 7-9 Program Design and Analysis

No. Statements PLCValue


1 ORG 100 100
Label name Value
label1 SUB r3,A 100
labell 100
LDR r0,[r3] 104
label2 108

g
label2 ADR r3,B 108

in
label3 116
LDR r1,(r4] 112

er
6 label3 ADR r0,r0,r1 116

e
in
Example 7:2.2 Show the contents of the assembler's symbol table at the end of code generation
for each line of the following program :

ng
ORG 200
p1 ADR r4,a
LDR ro,[r4]
fE
O
ADR r4,e
LDR r1, (r4]
e

ADD r0,r0,r1
g
le

CMP rO,r1
BNE p1
ol

p2 ADR r4,e
FAUDec21; Marks 8
C

Solution:
u

No. Statements PLC Value


ad

ORG 200
200 Label name Value
iln

200
2 p1 ADR r4,a pl 200
m

204
3 LDR ro, [r4] p2 228
Ta

208
ADR r4,e
212
5 LDR r1, {r4]
216
ADD rO,r0,r1
220
CMP rO,r1
8 224
BNE p1
9 228
p2 ADR r4,e

knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>

Page 274 of 446

Embedded Systems and loT Design 7-10 Program Design and Analysis

The assembler translates assembly mnemonics into their corresponding binary


opcodes. Each instruction is mapped to its machine code representation.
Operand values, such as register numbers or memory addresses, are also
translated into their binary representations as needed.

g
• The assembler generates the final object code, which consists of binary instructions

in
and data.
Throughout the process, the assembler performs error checking. It identifies and

er
reports syntax errors, semantic errors, or other issues in the source code.

e
• Error messages and diagnostic information are typically

in
provided to help the
programmer correct mistakes.

ng
7.2.2 Linking

Breaking down a large assembly language program


fE into smaller, manageable
modules, often called modular programming,
is a common practice to enhance
O
code organization and readability. Each
or function, making the module typically focuses on a specific task
overall program more maintainable
e

This modular approach encourages and easier to debug.


code reuse, as modules can
g

various projects. be utilized in


le

In many cases, assembly language programs


rely on preassembled library routines
ol

that provide essential functionality,


such as input/output
operations or
C

mathematical calculations.
After the assembly process, you
have multiple object files,
u

and data from different modules or each containing code


libraries.
ad

• The linker
combines these object files
references between different into a single, executable programn.
modules and ensures It resolves
iln

references and other symbols are that function calls, variable


correctly linked to their
The linker assigns memory definitions.
m

addresses to functions
locations in the final executable. and variables, determining
It calculates memory offsets their
Ta

accordingly. and adjusts references


7.2.3 Loading
When a program is to be
executed, the loader initiates
Some labels will be defined the loading process.
and used in the same
in asingle file
but used elsewhere. The location file, while others will be defined
in the file a
point, and the location in the file where label is defined
is known as an entry
Lknown as an
external reference. The loader's where the label is used is
waforences based on available main job is to resolve external
entry points using the
symbol table.
TECHNICAL PUBLICATIONS®
- an
up-thrust for knowledge
<br>

Page 275 of 446

Embedded Systems and loT Design


7-11 Program Design and Analysis

The loader allocates memnory in the computer's RAM to hold the program's code,
data and any additional resources it may require.
• The loader reads the executable file and copies the contents of the executable file
into the allocated memory space.
The loader adjusts memory addresses within the loaded code and data to reflect

g
the actual locations in RAM where they have been loaded.

in
Some executables may contain relative memory addresses or references that must

er
be adjusted to the correct absolute addresses in RAM. The loader relocates,
modifying instructions and data as necessary to reflect the memory layout.

e
in
Review Questions

ng
1. Bring out the difference between program counter and program location counter.
fE
2. Outline the role of assemblers and linkers in the compilation process.
AUDeç-21:
AU:May-18,
Marks

Marks. 8
2
O
3. Explain the label processing in assembly language with the help of a suitable example.
4. What does a linker do ?
e

5. Explain the function of the loader.


g
le

73 Compilation Techniques EAU; May-17) 21Dec.17,21:


ol

various over
In embedded computing systems, you often need fine-grained control
aspects, such as handling interrupts, memory allocation and instruction
C

you more control over


sequencing. Understanding how a compiler works gives
u

these aspects.
ad

Understanding the compilation process helps meet your performance goals by


you want or by
writing high-level code that gets compiled into the instructions
iln

to integrate it into vour


identifying whern to write assembly code and how
high-level language program.
m

optimization.
Compilation is not just about translation; it also involves
Ta

programs into lower-level


The translation process converts high-level language
instructions.
sequences. This
The optimization techniques improve the instruction source
optimization process is more effective tharn indeperndently translating
program to ensure that decisions that
code statements. It considers the entire
to more
benefit one part of the code do not inadvertently harm others, leading
efficient and reliable program execution.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 276 of 446

Embedded Systems and loT Design 7-12 Program Design and Analysis

shows the compilation process. Compilation starts with high-level code


Fig. 7.3.1
like C and typically generates assembly code rather than direct object code
generation, as that duplicates the assembler's function.
High level
language code

g
in
Parsing and Symbol table generation

e er
Semantic analysis

in
ng
Machine independent optimizations
fE
Instruction level optimization
O
e

Code generation
g
le

Assembly code
ol

Fig. 7.3.1 Compilation process


C

Steps in the Compilation Process


1. Parsing : In this initial step,
u

the compiler breaks the code into individual


statements and expressions.
ad

2. Symbol table generation : During


parsing, the compiler identifies and records all
named objects, such as variables, functions
iln

and data types, in a symbol table. This


table is used for reference throughout
compilation to ensure proper variable usage
m

and scope.
3. Semantic analysis
Ta

:
This phase focuses on checking
correctness. It involves type the code for semantic
checking, scope analysis and
validations to ensure the program other high-level
adheres to the language's rules
Any semantic errors are and constraints.
reported at this stage.
4. Machine-independent optimization :
It tries to make the intermediate
efficient by trarnsforming a
section of code that doesn't code more
components like CPU registers or involve hardware
any absolute memory
optimizes code by eliminating location. Generally, 1
redundancies, reducing the
eliminating useless code or number of code lines
reducing the frequency of
repeated code. Thus, it can
TECHNICAL
PUBLICATIONs- an
up-thrust for knowledge
<br>

Page 277 of 446

Embedded Systems and loT Desian 7-13 Program Design and Analysis

be used on any processor, irrespective of machine specifications. They may incdude


-
techniques like
Constant folding It evaluates constant expressions at compile-time rather
than runtime to reduce the computational work performed during program
execution.

g
:
Example Before optimization : int x = 5+7+ c;

in
After optimization: int x = 12 + c;

er
Common subexpression elimination : It identifies and eliminates redundant

e
calculations.

in
Example : Before optimization : tl=x*z; t2=a+b; t3=p%t2; t4=x*z; t5za-Z;

ng
After optimization : tl=x*z; t2=a+b; t3=p%t2; t5=a-z;
Constant Propagation : If any variable is assigned a constant value and used in
fE
further computations, constant propagation suggests using the constant value
directly for further computations.
O
Before optimization x = 12.4, y= x/2.3
:
Example:
After optimization : y= 12.4/2.3
g e

Copy Propagation It is an extension of constant propagation.


:
le

= * x = a; d = x *b+ 4;
Example: Before optimization : c a b;
ol

After optimization :c= a* b;


x = a; d =
a* b+ 4;
C

a to another
After a is assigned to x, use to replace until is assigned again
a x
compile time as it
variable, value, or expression. It helps in reducing the
u

reduces copying.
ad

removes code that is guaranteed to


Dead code elimination It identifies and
:

output.
iln

have no impact on the program's


x = a; d =x*b+4:
Before optimization : =a*b;
c
Example:
m

d =
a
After optimization :c = a * b; *b+4:
Ta

assignment statements into dead code.


Copy propagation often leads to making never
since it is used after its last definition.
A variable x is said to be dead
a call is replaced by the function's body.
Function Inlining Here, function
:

the parameters, storing the return


address.
This saves a lot of time copying all
etc.
or more loops are combined in a single loop. It helps in
Loop Jamming: Two
reducing the compile time.
5. Instruction-Level Optimization
: These optimizations are specific to the target :

more efficient machine code. Examples include


architecture and aim to produce
PUBLICATIONs - an up-thrust for knowledge
TECHNICAL
<br>

Page 278 of 446

Embedded Systems and loT Design 7-14 Program Design and Analysis

Loop unrolling : It is a technique where the compiler replaces loop constructs


with multiple copies of the loop body to reduce loop control overhead.
Example: Before optimization :
i= 0; while( I < 30) { xi]=0; i++;}// Loop runs for 30 times
After optimization :

g
i= 0; while( I < 30) { x[i]=0; i++;

in
x\i]=0; i++;

er
x{i]=0; it+;
I/Loop runs for 10 times

e
Register allocation : It aims to minimize memory accesses and maximize the
use of CPUregisters to reduce memory latency and improve

in
execution speed
and instruction scheduling.

ng
6. Code generation : In the final stage, the compiler translates
the high-level code into
assembly code suitable for the embedded systerm's processor.
fE
7:3.1. Statement Translation
O
This section focuses on translating a high-level
language program with little or no
e

optimization. Let's start with how to translate an


expression.
g

• First, let's think


about how to translate an expression.
In a typical application, a
le

major portion of the code is made up


of logical and mathematical expressions.
Understanding how to compile a single
ol

a useful starting point for learning expression, as shown in Example


7.3.1, is
about the entire compilation process.
C

Example7:3.1 Compile the arithmetic


expression: Y = P*Q + 4 * (R - S)
for ARM
u

processor.
ad

Solution: Fig. 7.3.2 shows the data P


flow diagram R
for the given
iln

expression. Every node in the data


flow graph corresponds to
an
m

operation. As shown in Fig. 7.3.2,


operands are the inputs assigned to
Ta

respective nodes. The temporary


variables tl, t2 and t3 are
used to
store intermediate values.
We simply produce an
instruction at each node
since
every node in the data flow
graph corresponds to a specific
instruction in the ARM Fig. 7.3.2 Data flow
diagram for given expression
TECHNICAL PUBLICATIONS®
- an
up-thrust for knowledge
<br>

Page 279 of 446

Embedded Systems and loT Design 7-15 Program Design and Analysis

instruction set. We use a sequence of registers, such as r1, r2, r3 and so on,
supported by ARM processor to store operands, their addresses and temporary
yariables during code generation. For simplicity, here, we use arbitrary register
assignment.
. ARM
Code for the given expression is as follows :

;operator 1 (*)

g
ADR r7,P ;Get address for P

in
MOV r1,[r7] ;Load a value of P

er
ADR r7,a ;Get address for a

MOV r2,[r7] ;Load a value ofQ

e
MUL r3,r1,r2 ;Store t1 = P* Q
into r3

in
ioperator 2 (-)

ng
ADR r7,R ;Get address for R
MOV r4,[r7] ;Load a value of R
ADR r7,s ;Get address for S fE
MOV r5,(r7] ;
Load a value of S
O
SUB T6,r4,r5 ;
Store t2 = R -S into r6
operator 3 (*)
e

MUL I7,r6,#4 ;Store t3 = R -S *4 into r7


g

ioperator (+)4
le

-
ADD r8,7,r3
:
t4 = P*a+4*
Store (R S) into r8
;Get address for Y
ol

ADR r7,Y
STR r8,[r7]. ;Store Y
C

• In the above code, the values of r2 are no longer needed following


rl and
of r4 and r5 are not needed.
operation 1. Similarly, after operation 2, the values
u

the code.
These registers can be reused to optimize
ad

:
is as follows
Optimized ARM Code for the given expression
iln

;operator 1 (*)
ADR I3,P
;Get the address for P
m

;Load a value of P
MOV r1,[r3]
;Get the address for Q
Ta

ADR r3,a
;Load a value of a
MOV r2,[r3] r3
;Store t1 = P *Q into
MUL r3,r1,r2
ioperator 2 (-)
ADR r4,R
:Get the address for R
:Load a value of R
MOV r1,[r4]
; Get the address for S
ADR r4,s
;Load a value of S
MOV r2,[r4)
;Store t2 =R-S into r4
SUB r4,1,r2
ioperator 3 (*) r1
:Store t3 = R-S*4 into
MUL r4,r4,#4
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
<br>

Page 280 of 446

Embedded Systems and loT Design 7-16 Program Design and Analysis

ioperator 4
(+)
ADD r1,r4,r3 ; Store t4 = P* Q+4* (R - S) into r1
ADR r2,Y ;Get thé address for Y
Y
STR r1,[r2] ;Store
Now, we will see how to. translate control structures. Control structure involves
the execution of an expression and based on the result, it controls the flow of the

g
program execution. The code generation techniques in the previous example may

in
be applied for expressions, leaving us with the task of producing code for the flow

er
of control itself.

e
A simple example of changing the control flow in C is shown in Fig. 7.3.3, where
the condition determines whether the true or false branch of the if statement is

in
executed.

ng
Example 7.3,2 Generate assembly code for the following C code.
if (P + Q> 0) fE
Z= 3;
else
O
Z= 6;
e

Solution: Fig. 7.3.3 shows the control/data flow


g

graph for the given code.


le

To generate the control flow code, we have to


P+Q>0 T
assign a label to the first instruction at the end
ol

of a directed edge and create a branch for


C

each edge that does not go to the next F Z=3


instruction in the sequence. The exact
u

procedure to be used at the branch points


ad

depends on the target architecture. Some


processors evaluate expressions
and generate
iln

Fig. 7.3.3
condition codes that we can test in subsequent
branches and on others, we can directly use
test-and-branch instructions. ARM
m

allows us to test condition codes.


Ta

ARM code for the givenC statement is as


follows.
ADR r3,P ;Get
the address for P
MOV r1,[r3] ;Load a value
of P
ADR r3,a ;Get the
address for Q
MOV r2,[r3] ;Load a value of Q
ADD r3,r1,r2 ;Store P+Q into r3
BLE B_ False
;If condition is false branch to B_ false
:True case
LDR r1,#3 ;Load constant

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 28l of 446

Embedded SystemS and loT Desian 7-17 Program Design and Analysis

ADR r2,Z ;Get the address for Z


STR r1, [r2] ;store value into Z
B Last ;Done with
the true case
;false case
B False LDR r1,#6 :Load constant
ADR r2,2 ;Get the address for Z
STR r1,[r2] ;Store value into Z

g
Last

in
Example. 7.3.3 Generate assembiy code for the following C code.

er
i= 0;y =0;

e
while (i < n)

in
y=y+ 2;

ng
i=i+;
fE
Solution :
Fig. 7.3.4 shows the control/data flow graph for the given code.
O
i=0: Loop initiation code
e

y=0;
g
le
ol

F Loop test
<i<n
C

Loop
T
exit
u

y=y+2; Loop body


ad
iln

Loop variable update


ii+1;
m
Ta

Fig. 7.3.4

statement is as follows.
ARM Code for the given C
:Initialize iteration counter =0
LDR r1,#0
MOV I2,r1 ;r2 = 0 n

ADR r4,n :Get the address for


:Read the value of n
MOVI3, [r4]
Loop CMP r1, r3 : Compare i and n
:Ifi >=nexit the
loop
BCS L Exit

PUBLICATIONS - an up-thrust for knowledge


TECHNICAL
<br>

Page 282 of 446

Embedded Systems and loT Design 7-18 Program Design and Analysis

ADD r2,r2,#2 iy=y+2


ADD r1,r1,#1 ;Incremnent iteration counter
B Loop
ADR r1,y ;Get the address for y
STR r2, Ir1] ;store value into y
L_ Exit

g
in
7.3.2 Procedures

er
Code generation for procedures involves generating the necessary instructions to
set up and manage procedure calls, pass parameters, execute the procedure code,

e
and handle the return. The specifics of code generation depend on the CPUS

in
architecture and the calling conventions used.

ng
The basic subroutine calling procedure for ARM processor is explained in
section 5.4.5. However, modern programming languages require more than the
fE
basic CPUsubroutine call mechanism to support procedures effectively.
where the linkage mechanism comes into play. 1t allows programs
This is
to pass
parameters to procedures and receive return values. Additionally,
O
it provides help
in restoring the values of registers that are updated in the procedure.
e

In most cases, procedure stacks are designed to expand in a


downward direction,
g

starting from higher memory addresses. Within this structure, a


stack pointer (sp)
le

signifies the current frame's endpoint, whereas a


frame pointer (fp) marks the end
of the previous frame. (The frame pointer, or
ol

fp, is essential only when a


procedure can dynamically expand its stack frame
while running.) The procedure
C

can access elements


within the frame by addressing them relative to
pointer (sp). When a new procedure is the stack
called, both the stack pointer (sp) and
u

frame pointer (fp) are modified to accommodate


another frame on the stack.
ad

The ARM Procedure Call


Standard (APCS) is a typical
mechanism example. While stack procedure linkage
frames reside in the main memory,
iln

understanding the role of registers is


essential in understanding this mechanism.
is as given below - It
m

r0 to r3: These registers pass parameters


into the procedure. Additionally, ro
Ta

stores the return value.


If more than four parameters are
placed on the stack frame. needed, they are
r4 to 7: These registers hold register
variables.
11: It functions as the frame pointer
13 : It serves as the stack pointer.
.
10: It keeps the limiting address on stack
size, crucial for checking the
overflows. stack

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 283 of 446

Embedded Systems and loT Design 7-19 Program Design and Analysis

7.3.3 Data Structures


. Adata structure is a way of organizing and storing data in a computer so that it
can be accessed and modified efficiently. It defines a particular organization for
data and operations that can be performed on that data.
The compler translates the data structure references into memory addresses
during code generation. This translation requires address computation.

g
Some of these computations cn be resolved at compile time. For example, if

in
you're accessing global constant, the compiler can determine its memory address.
a
during compilation. However, some calculations must be done at run time.

er
Since the array index (the position of the elemnent you want to access) can vary

e
dynamically during program execution, the memory address of an array element

in
often needs to be calculated at runtime.

ng
a a[0j
OneDimensional Array
• Let us consider a one-dimensional array : a[i]. a[1]
Fig. 7.3.5 shows the layout of the array in memory. fE a[2]
The first element of the array is accessed using a[0],
O
the second elemnent with a[1], the third with a[2],
and so on.
e

C++, Fig. 7.3.5 Layout of a


many programming languages like C and one-dimensional array in
g

In
access elements in an array.
you can use pointers to memory
le

to the first
If you have a pointer arr_ptr that points
ol

can access the element at index i using pointer


element of the array a, then you
C

arithmetic as *(arr_ptr + i).


a[0, 0]
u

Two Dimensional Array


Let us consider a two-dimensional
array: afi, j]. a[0, 1]
ad


Fig. 7.3.6 shows the layout of
the two-dimensional
row-major order.
array in memory in the form of
iln

most common way to


In row-major order, the a[1, 0]
arrays in memory, the inner
m

Store two-dimensional a[1,


case, j in ai, j) varies most
1]
variable (in this
Ta

as a contiguous
quickly. Each row is stored
that row
memory block and the elements within
sequentially. Conversely, Fortran uses a[2, 0)
are stored
outer variable
column-major order, where the a(2, 1]
(1
in this case) varies most quickly.
access ai, j]
convert a two-dimensional array
lo array access in roW-major
nto one-dimensional
formula a[i * M +j, where Fig. 7.3.6 Memory layout for
Order, you can use the two-dimensional array

PUBLICATIONS - an up-thrust for knowledge


TECHNICAL
<br>

Page 284 of 446

Embedded Systems and loT Design 7-20 Program Design and Analysis

M is the number of columns in the two-dimensional array.


i represents the row number and it is multiplied by the number of columns M
to skip to the correct row
in memory.
j represents the column number within that row, which is added to
reach the
desired element.
Structure

g
• A C struct is easier to address.

in
Fig. 7.3.7 shows a structure imnplemented as a
contiguous memory block.

er
struct

e
{ S_ptr

in
int field1; field1 4 bytes
char field2 ;

ng
field2
;
st
struct st
s, s ptr = &s; fE Fig. 7.3.7
• In C and many other programming
languages, fields within a structure can
O
accessed using constant offsets be
from the base address of the structure.
example, assuming that field1 In this
is four bytes long, adding
e

(s_ptr) effectively points to 4 to the base address


the beginning of field2,
g

*(s_ptr + 4). ie.,


le

This offset calculation is


usually
used during execution to fetch done at compile time and
the indirection () is
ol

the memory location


address. This allows for efficient access pointed to by the calculated
to the fields within
C

the structure.
Review Questions
u

1. With a neat
ad

flowchart, explain the steps


involved in compiling a program.

2. Explain in detail AU May-21,


iln

about the compilation process Dec.-21 Marks 7


3. Explain the
in high-level languages.
principle of various compilation AU: May-17, Marks 8
m

techniques.
4. State the basic
principle of the compilation
technique.
AU: Dec.-17, Marks. 8
5. Name any two techniques
Ta

used to optimize the


6. For the given execution time of the program.
conditional code snippet, generate
if (a + b > 0) the code

X= 5;
else
x=7;
7. Discuss the procedure
and data structure with respect
8. Demonstrate to compilers.
the dead code elimination to
optimize the- program
9. Generate the statement
translation into ARM with a code snippet.
instruction for the expression
ab+ 5(c-d).
TECHNICAL PUBLICATIONs -
an up-thrust for knowledge
<br>

Page 285 of 446

Embedded Systems and loT Desian


7-21 Program Design and Analysis

7.4 Program Level Performance Analysis


AUMay-17
Analyzing program execution time in embedded systems
is crucial for ensuring
the system meets its real-time requirements
and performs efficiently. It involves
measuring and estimating how long it takes for a program or
specific parts of it to
execute. This analysis is essential
for optimizing code to meet timing constraints
and manage resource consumption, including power

g
consumption.
Assessing CPU performance differs from evaluating program

in
performance. The
CPUclock speed is not a reliable indicator
of how a program will perform.

er
. It is also essential to note that a CPU's ability to execute
specific program

e
segments quickly does not guarantee that it will run the entire program at
the rate

in
we desire.

ng
Various factors, including microarchitecture, memory management,
parallelism,
and software design, collectively influence the actual performance of a program on
a given CPU. fE
Determining Program Execution Time is a Challenging Task
O
Because of the following reasons, determining the execution time of programs can
e

be challenging in practice.
Input Data Values : Program execution time can vary based on the input data
g
le

values because they determine the execution paths, loop iterations and branch
complexities within the program. Different inputs can lead to significantly
ol

different execution patterns.


C

Cache Behavior : The performance of a program is heavily influenced by the


behavior of the CPU's cache. The efficiency of caching is influenced by the
u

specific data values used by the program. Cache hits and misses'
can have a
ad

substantial impact on execution time.


can
iln

Instruction-Level Variability Even at the instruction level, execution times


:

vary. Floating-point operations are particularly sensitive to data values, but


m

Additionally. the
integer operations can also exhibit data-dependent variations.
execution time of an instruction in a pipeline is influenced not only by the
Ta

the pipeline.
instruction itself but also by the surrounding instructions in
Various
Ways to Measure Program Performance :

the following methods


rOgram performance can be measured using
simulators for
Microprocessor Simulators : Some CPU manutacturers provide
run on workstations or PCs, take nrocs
their processors. These simulators
prOgram execution. Thev can
executables and input data as input and simulate
also measure execution time.

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 286 of 446

Embedded Systems and loT Design 7- 22 Program Design and Analysis

of specific code sections


Timer on the Microprocessor Bus The performance
:

can be measured using timers connected to the microprocessor bus. The code to
timer's
be measured starts and stops the timer at its beginning and end. The
precision limits the accuracy of this method.
Logic Analyzer A logic analyzer can be connected to the microprocessor bus
:

to measure code segments' start and stop times.

g
in
Various Performance Measures

er
There are three key types of performance measures for programs :
Average-Case Execution Time
:
This measures the typical execution time

e
expected for typical or representative data inputs.

in
.Worst-Case Execution Time : This represents the longest time the program can

ng
take to execute for any input sequence.
Best-Case Execution Time : This measures the shortest time a program can
fE
complete its execution for any input sequence.
O
7.4.1 Elements of Program Performance
e

Program execution time is given as


g

Execution time = Program path + Instruction timing


le

Program Path: It is the sequence of


instructions executed by the program
ol

either in its low-level representation (machine code) or


high-level
language.
C

Instruction Timing : It is determined based on


the sequence of instructions
traced by the program path. It considers
u

various factors, including data


dependencies between instructions, pipeline
ad

behavior and the impact of


caching.
The challenges in estimating program
iln

execution time from a high-level


program are : language
Indirect Correspondence : High-level
m

to machine instructions. language statements do not directly map


The translation involves multiple
Ta

difficult to predict how many steps, making it


instuctions will be executed precisely.
Memory and Variable
Estimations: Estimating the number
locations and variables can of memory
be complex. Results may be cached or
further complicating the prediction. recalculated,
Compiler Optimization : As
compilers optimize programs,
further complexity in estimating execution they introduce
time. Optimizations can
code is translated to machine
instructions, making it difficult change how
performance. to predict

TECHNICAL PUBLICATIONS® an up-thrust for knowledge


<br>

Page 287 of 446

Embedded Systems and loT Design


7- 23 Program Design and Analysis

However, examining high-level code can roughly estimate some program


performance aspects. For instance, ideritifying large, fixed-loop iterations or
significantly longer conditional branches can provide insights into time-consuming
segments of the program.
Achieving a precise estimate of program performance involves considering the
specific instructions being executed, as different instructions have varying

g
execution times. Performance estimation becomes even more complex when the

in
execution time of one instruction depends on the instructions exected before and

er
after it.

e
:
Example 7.4.1 ldentify data-dependent paths in the nested if statements given below

in
if (p) /* Test 1 */

ng
if () /* Test 2 */

e=a * b;
/* Assignment 1
/
fE
O
else
e

e= a
g

+
b; /* Assignment 2 /
le

f= a -b; /* Assignment 3 /
ol
C

else
u

if () /* Test 3 */
ad

g=c- d; /* Assignment 4 */
iln

}
m

a program with conditional tests and


Solution : To identify all the execution paths in
p, q and r, we can create a truth table-like structure
Ta

assignments controlled by variables as shown below.


possible combinations of values of these variables,
to account for all

conditions Execution path Distinct cases


Test
1
1 false, Test 3 false No Assignment
0 Test
Assignment 4 2
0 0 1 Test 1 false, Test 3 true
1
1 false, Test 3 false No Assignment
1 Test
Assignment 4 2
1 1 Test 1 false, Test 3 true

PUBLICATIONSe an up-thrust for knowledge


TECHNICAL
<br>

Page 288 of 446

Embedded Systems and loT Design 7-24 Program Design and Analysis

1 0 0 Test 1 true, Test 2 false Assignments 2, 3


1 1
Test 1 true, Test 2 false Assignments 2, 3 3

Assignments 1, 3 4
1 1 0 Test 1 true, Test 2
true
Assignments. 1, 3
1 1 1 Test 1 true, Test 2 true

g
When analyzing the program's execution paths, it's important to consider the

in
distinct cases that result from the conditional tests and assignments. In this

er
program, there are four distinct cases (execution paths) no assignment,
assignment 4, assignments 2 and 3 or assignments 1 and 3.

e
in
Example 74.2 Determine the path for a loop code given below.
for (i = 0, j = 0; i < N; i++)

ng
j=j+ 2;

Solution: Fig. 7.4.1 shows CDFG for the


given code. Looking at CDFG we can
fE =0: Loop initiation code
more easily determine how many times j=0;
O
various statements are executed. The
loop initiation block is executed once,
e

the test condition is executed N + 1


g

i<N Loop test


times and both the body and loop
le

variable update are executed N times. Loop


ol

exit T
After determining the program's
|i=j+2:
C

execution path, the next step is to Loop body


evaluate the execution time of the
u

instructions executed along that |i+ 1: Loop variable update


ad

path.
The most straightforward estimate
iln

assumes that every instruction


Fig. 7.4.1
takes the same number of clock
m

cycles. In this case, we only need to tally


the total count of instructions and then
multiply it by the per-instruction execution
Ta

time to calculate the program's overall


execution time. However, even when
disregarding cache-related effects, this
technique is simplistic for several
significant reasons :
Execution Time Variability : Not
all instructions take the same
Some instructions, like floating-point time to execute.
much slower than others. and certain load-store operations, can be
Dependency on Surrounding
Instructions : The execution
instruction can depend on the
instructions that come before or
time of an
after it. CPUs
TECHNICAL PUBLICATIONS
an up-thrust for
knowledge
<br>

Page 289 of 446

Embedded Systems and loT Design


7-25 Program Design and Analysis
use techniques like register bypassing to
optimize instruction sequences,
affecting execution times.
Operand-Dependent Time : Instruction
execution time may vary based On
operand values, especially in floating-point
and specialized instructions.
uandlingChallenges in Estimating Instruction Execution Time

g
The first two challenges are more
manageable compared to the third.

in
1. Using
Look-up Tables : We can effectively address the first wo
by creating a
look-up table that indexes instruction execution times

er
basci on opcode and
potentially other parameters like register usage.

e
2. Considering Nearby Instructions: To account for interdependencies

in
in
execution times, we can expand this table with additional columns to factor in

ng
the influence of nearby instructions. Since the size of the
CPU pipeline
generally limits these effects, we only need to analyze a relatively
fE small
window of instructions to accommodate such effects.
3. Operand Variations : Handling operand-dependent variations is challenging
O
and often requires actual program execution with diverse data values.
Fortunately, these effects are usually minor, especially for common operations
e

like additions and multiplications in floating-point programs.


g

Cache plays a crucial role in instruction execution time, offering much faster access
le

times than main memory. Main memory access can be 10-100 timnes slower than
ol

cache access, significantly affecting both instruction and data retrieval times.
C

Cache performance relies on the program's execution pattern since the cache
content depends on past memory accesses.
u
ad

(4.2 Measurement-Driven Performance Analysis


iln

Themost straightforward way to assess a program's execution time is by direct


limitations.
measurement. While this method is attractive, it has its
m

a program requires providing


Determining the worst-case execution path of
Ta

specific inputs.
guarantee worst-case execution is often
ldentifying the exact inputs that
infeasible.
vou
To accurately measure a program's
performance on a particular CPUtype,
or its simulator.
need access to that CPU measurement-based assessments are still the
Despite
the drawbacks mentioned, evaluating the execution time of embedded
most commonly used approach for
measurement provides practical insights into how
software. This is because direct
environment.
a program performs in a real-world
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 290 of 446

Embedded Systems and loT Design 7-26 Program Design and Analysis

Many performance measurement methods involve both tracking the program's


program
execution path and recording the time it takes to follow that path. As the
runs, it dynamically selects a path and we monitor the execution time along that
chosen path. This record of the program's execution path is called program trace
or simply a trace. Traces have additional utility beyond performance measurement;

g
they can be highly valuable for analyzing the program's cache behavior.

in
• We have seen that providing a set of inputs that causes the worst-case execution

er
time is a difficult task. Using benchmark data sets or providing data captured

e
from a running system, it is possible to generate typical input values.

in
When dealing with input data, complex systems can pose challenges for isolating

ng
components for independent testing. This often necessitates software scaffolding,
the integration of testing modules within the system's software helps us introduce
testing values and to observe testing outputs.fE
Measuring program performance can be done directly on hardware or through
O
simulation, each with its pros and cons.
Direct monitoring of the program counter is ideal but often not
feasible to
e

measure program performance. However, we can


modify the program to start and
g

stop timers, providing valuable execution time


data for different program
le

segments.
ol

Logic analyzers and oscilloscopes are


useful tools for monitoring signals that
indicate different program execution points.
C

programs that have exceptionally However, when dealing with


long execution times, this method becomes less
u

effective due to the limited memory


capacity of logic analyzers.
ad

Some CPUs, like Pentium processors, can


generate branch trace messages
automatically. These messages provide
information about branch source and
iln

destination addresses, allowing us to reconstruct


executed instructions within basic
blocks while conserving memory.
m

As an alternative to physically
measuring execution time, simulation
Ta

valuable method. A CPU


simulator is a software program provides a
memory image
and emulates the CPUs operations, that inputs a CPUs
images as output. producing modified memory
The cycle-accurate simulator
is crucial for performance
calculates the exact number analysis. It precisely
of clock cycles needed for execution.
slower than actual CPUs, optimizations Although it is
slower than the processor hardware. make them run only hundreds of times
A Cvcle-accurate simulator
includes a complete CPUmodel,
As a result, it can provide including the cache.
useful information regarding
why the software runs so
slowly.
TECHNICAL PUBLICATIONS® an up-thrust for knowledge
<br>

Page 291 of 446

7-27 Program Design and Analysis

Review Questions

What is
the program-level performance analysis of
embedded computing system
design
Marks 8
, Why is it difficult to determine program
AU.: May-17,
execution time ?
. Discuss various ways to measure program
performance.
4.
List the various performance measures.

g
5. Discuss the elements of program performance.

in
6. What are the sgnificant challenges in estimating instruction execution time and
how do we
Overcome them ?

er
7.
List the limitations of direct measurement techniques
for execution time.

e
8. What is program trace ?

in
9. What do you mean by software scaffolding ?

ng
10. What is cycle-accurate simulator ? Explain its use.

fE
O
g e
le
ol
C
u
ad
iln
m
Ta

- an up-thrust for knowledge


PUBLICA TIONs
TECHNICAL
<br>

Page 292 of 446

UNIT
II: EMBEDDED SYSTEMS
TWo MARKS QUESTIONS WITH ANSWERS

g
in
Q.1 What are embedded systems ?

er
Ans. : Embedded systems are specialized computer
systems designed to perform
dedicated functions or tasks within a larger system
and designing them requires a

e
structured approach,

in
Q:2 What is
design methodology?

ng
:
Ans. Design methodology refers to
the set of principles, guidelines, and
guiding the entire design process. best practices
It involves decisions about the choice
fE
componernts, software
development techniques, testing procedures of hardware
and more.
Q.3 What is the importance of design
O
methodology in embedded system
Ans. : Refer section 4.1. design ?
e

Q.4 Differentiate top-down and bottom-up


design.
g

Ans. : AUApril-14, CE
Refer section 4.1.
le

Q.5 List the goals of embedded system


design.
ol

Ans. :
Refer section 4.1.
C

Q.6 What are the recurring


tasks to be performed at each
system design process ? step in the embedded
u

Ans. : Refer section 4.1


ad

Q.7 List the nonfunctional requirements


of embedded systems.
iln

Ans. :
Refer section 4.1.1.
Q.8 What is a digital
command
m

control?
Ans. : Refer section 6.2.2.
Ta

Q.9 List the two fundamental types


of computer architecture.
Ans. : Von Neumann and
Harvard architecture are two
architecture. fundamental types of computer
Q,10 Give the comparison
between Harvard and Von-Neumann
:
Ans. Refer section 5.2.1.3. architectures.

a.11 What is CISC?


Ans. : Refer section 5.2.1.4.
(7- 28)
<br>

Page 293 of 446

Embedded Systems and loT Design


7-29 UNIT I
0.12 What is RISC ?
Ans. : Refer section 5.2.1.5.
Q.13 State the general purpose registers in
the ARM processor.
:
Ans. Registers ro0 to
rl2 are used as general-purpose registers in the ARM processor.
0.14 What are CPSR and SPSR ?

g
Ans. : CPSR (Current Program Status

in
Register) and SPSR (Saved Program Status
Register) are the special purpose registers.

er
0.15 State the function of the link
register.

e
Ans. : Register rl4 is the link register. When a subroutine is called, the processor stores

in
the return address in this register.

ng
0.16 What is the function of r15 register in the ARM processor?
fE
Ans. : Register r15 is the program counter and stores the address of the next
instruction to be fetched from the memory by the processor.
O
Q.17 What do you mean by unbanked registers ?
:
e

Ans. Refer section 5.3.3.4.


g

Q.18 What do you mean by banked registers ?


le

:
Ans. Refer section 5.3.3.4.
ol

Q.19 What is Little-Endian mode ?


C

:
Ans. Refer section 5.3.5.
u

Q.20 What is Big-Endian mode ?


ad

:
Ans. Refer section 5.3.5.
iln

Q21 What is WO mapped /O ?


:
Ans. Refer section 6.2.1.
m

Q.22 What is memory-mapped /O ?


Ta

Ans, :
Refer section 6.2.1.
VO mapped /O.
Q.23 Compare memory mapped /0 and
Ans. :
Refer section 6.2.1.
Q.24 what are peek and poke functions ?
:
Ans. Refer section 6.2.1.
Q25 What is interrupt service routine ?
Ans. :
Refer section 6.2.3.

TECHNICAL PUBLICATIONS an up-thrust for knowledae


<br>

Page 294 of 446

Q.26 What do you mean by interrupt priority and interrupt vector ?


:
Ans. Refer section 6.2.4
Q.27 State the interrupts supported by ARM processor.
Ans. : Refer section 6.2.5
Q.28 What is interrupt latency ?
Ans. : Refer section 6.2.5

g
in
Q.29 What is DFG and CDFG ?

er
Ans. : DFG stands for "Data Flow Graph," and CDFG
stands for "Control Data Flow
Graph." A Data Flow Graph is a graphical representation
that illustrates the flow of

e
data within a system or program. A Control Data Flow Graph is an
extension of the

in
Data Flow Graph that includes control flow information
in addition to data flow.

ng
Q.30 Define assembler.
AU May-19
Ans. : Assembler is a program
that translates the assembly language program
fE
machine code. into
Q.31 What is meant by linking ?
O
AU* May-19
Ans. : Linking is the step
that follows assembly. It involves combining
files gernerated from different source files multiple object
e

linker determines the final addresses of


and resolving references between them. The
g

instructions and data, producing an


binary file. executable
le

Q.32 What is meant by loader ?


ol

Ans. : A loader is a program that brings AUMay-19


the executable program into memory
C

execution. It ensures the program is for


correctly placed in memory and
ready to execute.
u

Q.33 Define embedded programming.


ad

Ans. : Embedded programming AU.May-19


is the process of creating software
designed to run on embedded systems. that is specifically
An embedded system is a computer system
with a dedicated function or purpose,
iln

often with constraints on size, power


consumption and processing capability.
m

Q.34 Name any two techniques


used to optimize the execution time of a program.
Ta

Ans. : Machine-independent
optimizations and instruction-level
techniques used to optimize the optimizations are two
execution time of a program.
Q.35 What is machine-independent
optimization ?
Ans. : Refer section 7.3.
Q.36 What is instruction-level optimization
?
: Refer section 7.3.
Ans.

TECHNICAL PUBLICATIONs
- an
up-thrust for knowledge
<br>

Page 295 of 446

Embedded Systems and loT Design


7-31 UNIT II

State the principle of basic compilation


Q.37 techniques.
Ans, : The principle of basic
compilation techniques involves the transformation of a
high-level programming language
(source code) into an equivalent lower-level
representation, typically machine code or
assembly language, using various
ootimization techriques to generate efficient code.
o38 List out the various compilation techniques.

g
Ans.: Various compilation techniques are Parsing, symbol table
generation, semantic

in
analysis, Machine-independent optimizations, instruction-level
optimizations, code

er
generation, etc.

What is program trace

e
0.39

in
Ans. :
Refer section 7.4.2.

ng
Q40 What is software scaffolding ?
Ans. :
Software scaffolding refers to a temporary and supportive structure of code that
fE
is put in place to facilitate software components' development, testing or debugging.
O
D00
g e
le
ol
C
u
ad
iln
m
Ta

- an up-thust for knowedoe


TECHNICAL PUBLICATIONS
<br>

Page 296 of 446

UNIT III

Processes
8

g
and Operating Systems

in
e er
in
Syllabus

ng
Structure ofa real - time system - Task Assignment and Scheduling Multiple Tasks and Multiple
-
Processes Multirate Systems Pre emptive real time Operating systems - Priority based
- -
scheduling - Interprocess Communication Mechanisms - Distributed Embedded Systems - MPSoCs
fE
and Shared Memory Multiprocessors - Design Example - Audio Player, Engine Control Unit and
Video Accelerator.
O
Contents
e

Structure of a Real - time System


g

8.1
le

8.2 Multiple Tasks and Multiple Processes


8.3 Preemptive Real-time Operating Systems
ol

Dec.-12, 14,16, May-13, Marks 16


8.4 Priority based Scheduling.
C

Marks
&.5 Interprocess Communication Mechanisms. Dec.-12,13, May-13, 16
May-13, Dec.-13,14,
*

Marks 16
u

8.6 Distributed Embedded Systems.


ad

8.7 MPSoCs and Shared Memory Multiprocessors


8.8 Design Example: Audio Player
iln

8.9 Engine Control Unit


..Dec.-16, Marks 8
m

8.10 Video Accelerator


Ta

-
(8 1)
<br>

Page 297 of 446

Embedded Systems and loT Design 8-2 Processes and Operating Systems
-
8.1 Structure of a Real time System
Time constraints are the key parameter in real time systems. It controls
autonomous system such as robots, satellites, air traffic control and hydroelectric
dams.
When user gives an input to the system, it must process within the time limit and

g
result is sent back. Real time system fails if it does not give results within the time

in
limits.

er
• A real-time system is any information processing system which has to respond to

e
externally generated input stimuli within a finite and specified period.

in
• A real time system is NOT a system that runs quickly. Real time system meets the
temporal constraints.

ng
Examples of temporal constraints are as follows:
a. Few milliseconds for radar systems. fE
b. One second for machine-man interfaces (in an aircraft):
O
C. Hours for some chemical reactions.

d. 24 hours for the weather forecast.


e

e. Several months or years for some space


g

crafts.
le

Real time systems are clock based or event based. Interactive is one more category
of real time system. Synchronization between the external processes and internal
ol

actions (tasks) carried out by the computer may be defined in terms


of the passage
C

of time or the actual time of day, in which case the system is


said to be
"Clock-based system" or it may be defined in terms of events and the systemn is
u

said to be "Event-based system".


ad

If the relationship between the actions in the computer and the system
more loosely defined, then the system is is much
said to be an "interactive system".
iln

Real time system is an example of a general purpose


operating system. This
system is used when the requirements are inelastic for
m

processors, so it is often used as a control


data flow or operations of
device in dedicated applications. Sensors
Ta

are used to bring the data in computer.


Computers analyze the data and possibly
regulate controls for the modification of seniors input.
Real-time systems are those systems in which the overall correctness
of the system
depends on both the furnctional correctness and the timing correctness.
Real time
systems also have a substantial knowledge of the system
it controls and the
applications running on it. These are deadline dependent.
• A RTS is any information processing system
that has to respond to 'externally
generated signal within a finite and specified period.

TECHNICAL PUBLICATIONs - an
up-thrust for knowledge
<br>

Page 298 of 446

Embedded Systems and loT Design


8-3 Processes and Operating Systerms
.A RTS is a computer system
where the correct functioning of the system
on the results produced depends
and the time at which they are produced.
A Real-Time Operating System (RTOS)
is an operating system intended to serve
real-time application process data as
it comes in, typically without buffering
delays.
In general, an operating system is
responsible for managing the hardware

g
resources of a computer
and hosting applications that run on the computer. An

in
RTOS performs these tasks, but is also
specially designed to run applications with

er
very precise timing and a
high degree of reliability. This can be especially
important in measurement and automnation systems where downtime is.costly or a

e
program delay could cause a safety hazard.

in

An RTOS can guarantee that a program will run with very consistent

ng
timing.
Real-time operating systems do this by providing programmers with a high degree
of control over low taskS are prioritized and typically also allow checking to
fE make
sure that important deadlines are met.
O
• A real-time kernel is software that manages the time and resources of a
microprocessor, microcontroller or Digital Signal Processor (DSP) and provides
e

indispensabl services to your applications.


g

RTOS kernel services :


le

Along with objects, most kernels provide services that help developers create
ol

applications for real-time embedded systems.


C

1. Timers
2. Device
I/0 supervisor
u

3. Dynamic memory allocation


ad

4. Intertask communication and synchronization


iln

5. Task management.
RTOS generally contains a real-time kernel and other higher-level services
such as
m

a user interface and other components.


file management, protocol stacks, graphical
devices.
Most additional services revolve around I/O
Ta

8.1.1 Characteristic of RTOS


features
RTOS are characterized by these main
1. Determinism
2. Responsiveness
3. User control
4. Reliability
5. Fail-soft operation.
TECHNCAL PUBLICATIONS- an up-thrust for knowledgs
<br>

Page 299 of 446

Embedded Systems and loT Design 8-4 Processes and Operating Systems

1. Determinism : Operations are performed at fixed, predetermined times or within


predetermined time intervals.
2. Responsiveness : How long, after acknowledgment, the operating system takes to
service the interrupt. It includes the time to begin execution, of the Interrupt
Service Routinte (1SR). If a context switch is necessary, the delay is longer than an
ISR executed within the context of the current process.

g
3. User control : User should be able to,

in
a) Specify paging or process swapping.

er
b) Decide which processes must reside in main memory.

e
c) Establish the rights of processes.

in
d) Fine-gained control over task priorities.

ng
e) Select algorithms for disks scheduling.
4. Reliability : fE
Real time system must be reliable. Reliability means
should not fail. The mean time between the failures should
that system
be very high.
O
5. Fail-soft operation It is ability of a system to
:
fail in such a way as to preserve as
much capability and data as possible.
g e

8.1.2 Classification of Real-time Systems


le

Real time systems are of clock based or event based.


Interactive is one more
ol

category of real time system.


C

Synchronization between the external processes


and internal actions (tasks) carried
out by the computer may be defined in terms of
the passage of time or the actual
u

time of day, in which case the system is said to be "Clock-based


ad

system" or it may
be defined in terms of events and the system is
said to be "Event-based system".
• If the relationship between
iln

the actions in the computer and the system is much


more loosely defined, then the system
is said to be "interactive system".
m

Task is a set of related jobs which jointly provide some


function. A job is a unit of
work that is scheduled and executed by a system.
Ta

Real time tasks get generated in response to some


events that may either be
external or internal to the system. When a
task get generated, it is said to have
arrived. Every real time system usually consists
of a number of real time tasks.
:
Job A job is a unit of work scheduled
and executed by the system.
A task T = U1,J2 s... . J is a set
of related jobs that together perform some
operation.

TECHNICAL PUBLICATIONS®
an up-thrust for knowledge
<br>

Page 300 of 446

Ermbedded Systems and loT Design 8-5 Processes and Operating Systems

. Jobs execute on a processor and may depernd on some resources. A scheduling


algorithm describes how jobs execute.
. Processors are active devices on which jobs ere scheduled. For example : Threads
scheduled on a CPU, data scheduled on a transmission link. A processor has a
speed attribute, that determines the rate of progress of jolbs executing on that
processor.

g
. A resource (R) is a passive entity on which jobs may depend. Resources have

in
different types or sizes, but have no speed attribute nd are not consumed by use.

er
Jobs compete for resources and can block if a resource is in use.

e
:
1. Clockbased tasks

in
• Clock based tasks are also called cyclic or periodic tasks.

ng
• Al jobs of a periodic task
t
have a regular inter arrival time T, we call T the
period of the periodic task t. fE
• If a job for a periodic task t; arrives at time t, then the next job of task t; must
O
arrive at t+I;.
a
Example of periodic task is task monitoring temperature of patient. It is time
e

driven method.
g

is the
• Each task is repeated at a regular interval and maximum execution time
le

same for each period.


ol

is usually the end.


Arrival time is uSually the start of the period and deadline
C

Periodic tasks are mutually independent.


tasks.
• Static scheduling is used for scheduling periodic
u
ad

Plant time constant Sampling time (T_)Interrupt


Fig. 8.1.1 Static scheduling flow
iln

specified time is dependent on the


• The completion of the operations within the
m

of the computer.
number of operations to be performed and the speed
Ta

a computer systen and


Synchronization is usually obtained by adding clock to the
of the computer at a
using a signal from this clock to interrupt the operation
predetermined fixed time interval.
2. Event based tasks :
tasks.
• Event based task is also called aperiodic
or time intervals but in
Actions are to be performed not at particular times
time
response to some event. The system must respond within given maximun
a

to a particular event.

TECHNICAL
PUBLICATIONS an up-thrust for knowiedge
<br>

Page 301l of 446

Embedded Systems and loT Design 8-6 Processes and Operating Systems

Events occur at non-deterministic intervals and event-based tasks are referred to as


"'a periodic" task.

Aperiodic tasks is a stream of jobs arriving at irregular intervals. Each task can
arrive at any time.
These tasks are event driven. Example of this type of task is task activated

g
upon
detecting change in patients condition.

in
• Two aperiodic tasks can arrive at
the same time.

er
Dynamic scheduling is used to schedule both periodic
and aperiodic tasks.

e
• The specification
of event based systems usually indicates

in
respond within specified maximum time to a
that the system must
particular event. These systems uses

ng
interrupts to indicate the real time system
that the action is required.
3. Interactive systems :
They represent the largest class of
fE
RTSs such as automatic
systems for hotels, airlines bank tellers, reservation
and car rental, etc.
O
The real-time requirement
is usualy expressed in terms
response time must not exceed". such as "the average
g e

The system responds at a


time determined by the
internal state of the computer
le

and without any reference to the environment.


The combination of clock
ol

based system and event


importance of average execution based system which gives
the
C

time of the task is called


This covers the systems interactive systems.
like automatic teller
machine, reservation system
u

hotels, airlines booking etc. for


ad

This system receives


the input from the
and executes within the average response plant or operator and
initiates the task
time.
iln

For example if you want


processes draw cash from ATM
the task of giving the money when you put your
m

on the network out. In this case the response card then it


traffic and time depends
other atmospheric changes. internal processing time and it does not
Ta

bother about
8.1.3 Hard Real Time Systems
.A hard real-time system is one
where the response
value. This time is normally time is
dictated by the environment. specified as an absolute
.A SUstem is called a hard real-time if
their deadlines or if messages tasks always must
finish execution before
always can be delivered
interval." within a specified time

TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>

Page 302 of 446

Embedded Systems and loT Design


8-7 Processes and Operating Systerms
Hard real-time is often associated with safety
critical applications. A failure
(e.g. missing a deadline) in a safety-critical
application can lead to loss of human
life or severe economical damage.
Missing a deadline may be catastrophic. Critical deadline
is called a hard
deadline.
. Hard real time means strict about adherence to each task deadline.
When an event

g
occurs, it should be serviced within
the predictable time at all times in a given

in
hard real time system.

er
• The preemption period for the hard real time
task in worst case should be less
a
than few seconds.

e
in
Automobile engine control system and anti lock brake are the examples of hard
real time systems.

ng
8.1.4 Soft Real Time System fE
A soft real-time system is one where the response time is normally specified as arn
O
average value. This time is normally dictated by the business or market.
A single computation arriving late is not significant to the operation of the system,
e

though many late arrivals might be.


g

Example : Airline reservation system - If a single computation is late, the system's


le

response time may lag. However, the only consequence would be a frustrated
ol

potential passenger.
C

Soft real time means that only the precedence and sequence for the task-operations
are defined, interrupt latencies and context switching latencies are small but there
u

can be few deviations between expected latencies of the tasks and observed time
ad

are accepted.
constraints and a few deadline misses
iln

8.1.5 Difference between Hard and Soft Real Time System


m

Soft Real Time System


Sr. No. Hard Real Time System
Ta

one where A soft real-time system is one where


Hard real-time system is the response time is normally
specified as an
the response time is specified as an average vaiue.
absolute value.
the This time is normally dictated by the
Thistime is normally dictated by business or market
environment.
millisecond. Time granularity is in second.
3
Time granularity is in
term data integrity. It support long term data integrity.
It support short

TECHNICAL PUBLICATIONS - an up-thrust for knowledae


<br>

Page 303 of 446

Embedded Systems and loT Design 8-8 Processes and Operating Systems

5. Safety is critical. Safety is non-critical.


6 Error detection is by system. Error detection is by user.
7 Ex: Automobile breaking system. Ex :
Airline reservation systemn.

8.2 Multiple Tasks and Multiple Processes

g
Tasks are units of sequential code implementing
the system actions and executed

in
concurrently by an OS.

er
Real time systems require that tasks
be performed within a particular
Task is related to the performance time frame.

e
of the real time systems.
A task, also called a thread, is a

in
simple program that thinks has
itself. The design process for a it the CPU all to

ng
real-time application involves splitting
be done into tasks responsible for a portion of the the work to
problem.
Each task is assigned a priority, fE
its own set of CPUregisters and its own
area. stack
O
In the specified time constraint, system
must produce its correct output. system
fail to meet the specified output, If
then the system is fail or quality decreases.
e

Real time systems are used for space


g

flights, air traffic control, high speed


telephone switching, electricity distribution, aircraft,
le

industrial processes etc.


Real timne systemn must be 100 %
fesponsive 100 % of the time. Response
ol

measured in fractions of second, but this time is


is an ideal not often achieved
C

field. in the
Real time database is updated
u

continuously. In aircraft example,


continuously changing so it is necessary to flight data is
ad

update. It includes speed, direction,


location, height etc.
iln

Real time tasks are of two types :


1.Periodic tasks : This types of tasks consists an
of infinite sequence of identical
m

activity, called instances, which are


invoked within regular time period.
Ta

2. Non periodic tasks are


invoked by the occurrence of an event.
• A task is a set of related jobs
which jointly provide some function.
of work that is scheduled A job is a unit
and executed by a system.
Terms used in the real time
task.
1. Release time or ready
time : It is a time when task is ready or
for execution. task is eligible
2. Deadline : Deadline is the maximum
time within which the task must
complete its execution with respect to event.

TECHNICAL PUBLICATIONSe -
an up-thrust for knowledge
<br>

Page 304 of 446

Embedded Systems and loT Desian 8-9 Processes and Operating Systems

3. Response time : It is a time duration from the occurrence of the event


generating the task to the time the task produces its results.
4. Completion time : The instant at
which a job completes execution.
5. Laxity : Laxity is defined as the amount of time
by which a task can miss its
deadline and still avoid severe consequences.

g
Real timne tasks get generated in response to some events that may either be

in
external or internal to the system. When task get generated, it is said to have
arrived. Every real time system usually consists of a number of real time tasks.

er
A process is a sequential program in execution. Terms like job and task are also

e
used to denote a process.

in
• A process is a dynamic entity that executes a program on a particular set of data.

ng
Multiple processes may be associated with one program.
Task is a single instance of an executable program.
fE
In a multiprogramming environment, usually more programs to be executed than
could possibly be run at one time. In CPU scheduling, it switches from one
O
process to another process. CPU resource management is commonly knowm as
e

scheduling
g

Objective of the multiprogramming is to increases the CPU utilization. CPU


le

scheduling isone kind of fundamental operating system functions.


ol


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
C

a
specific state for each process. A state diagram is composed of set of states and
u

transitions between states.


ad

Fig. 8.2.1 shows an on-the-fly compression box.


iln

Bit Co
Uncompressed Compressor npressed
m

Character queue data


data
Ta

Conpression
table

Fig. 8.2.1 On-the-fly


compression box

Input and output of the


compressor box 1s Serial ports. It takes uncompressed data
compressed data. Given data is compressed
and processes it. Output of the box is
table. Modem is used such type of box.
using a predefined compression

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 305 of 446

Embedded Systems and loT Design 8-10 Processes and Operating Systems

The program's need to receive and send data at different rates. It is an example of
rate control problems. It uses asynchronous input. We can provide a button for
compressed mode and uncompressed mode.
When the ser presses ncompressed mode, the input data is passed through
unchanged.
The button will be depressed at a much lower rate than characters

g
will be
received, since it is not physically possible for a person to

in
repeatedly depress a
button at even slow serial line rates.

er
Keeping up with the input and output data while
checking on the button can
introduce some very complex control code

e
into the program.

in
Sampling the button's state too slowly can cause
the machine to miss a button
depression entirely, but sampling it too

ng
can cause the machine to frequently'and duplicating a data value
incorrectly compress data. This
maintaining counter. problem is solved by
fE
82 Multirate Systems
O
More complicated control systems have multiple sensors
and actuators and must
e

support control loops of


different rates. Multirate
embedded computing systems
g

includes automobile engines,


printers and cell phones.
le

Tasks may be synchronous or


asyrnchronous. Synchronous
different rates. Processes run tasks may recur at
ol

at different rates based on


the tasks. computational needs of
C

Automotive engine control is an


example of multirate system.
u

engine control are Tasks in automotive


spark control, crankshaft
sensing, fuel/air mixture, oxygen
ad

sensor and Kalman filter.


• Fig. 8.2.2 shows automotive
engine control.
iln

e The spark plug must be fired at a


certain
point in the combustion cycle,
m

but to obtain
better performance, the phase
relationship Engine
Ta

between the piston's movement Controller


spark should change as a function and the
of engine
speed. Using a microcontroller senses
the engine crankshaft position that
allows the
spark timing to vary with engine
. Automobile engine controllers use
speed. Fig. 8.2.2 Engine
control
additional sensors, including
position and an oxygen sensor
used to control
the gas pedal
multimode control scheme. emissions. They also use a

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 306 of 446

Embedded Systems and loTDesign 8-11 Processes and Operating Systems

The larger number of sensors and modes increases the number of discrete tasks
that must be performed.

8.2.2 Process State and Scheduling


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

g
specific state for each process.

in
• Fig. 8.2.3 shows a process state diagram. A state diagram is composed of a set of

er
states and transitions between states.

e
in
Create New Build context Ready
request state

ng
Start Admit

complote
Dmplete allocateo

Preemption fE
ait CPU
O
e

Terminate End/
Exiting
g

Waiting Running
le

state Wait state


ol

Controlled by Controlled by
CPUscheduler job scheduler
C

Fig. 8.2.3 Process state diagram


u
ad

State diagram is used by


process manager to determine the type of service to
process states are as follows: New, ready, running.
provide to the process. The
iln

waiting and end.


)' system call. These
m

: Operating system creates new process by using fork(


•New resources are not allocated.
process are newly created process and
Ta

CPU. Process reaches to the head of the


Ready The process is competing for the
:

list (queue).
executed. Operating system allocates
Running:The process that is currently being process
resources to the for execution.
all the hardware and software
some event occurs such as the completion of
Waiting :A process is waiting until
an input-output operation.
releases it all resources.
• Exit/End : A process is completes its operations and
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 307 of 446

Embedded Systems and loT Design 8-12 Processes and Operating Systems

8.2.3 Scheduling Policies


The scheduling policy determines when it is time for process to be removed from
the CPU and which ready process should be allocated the CPU next. The
scheduling mechanism is composed of several different parts, depending on
exactly how it is implemented in any particular operating system.

g
CPU scheduling is divided into two types : Preemptive scheduling and

in
non-preemptive scheduling.

er
Preemptive scheduling : A scheduling method that interrupts the processing of a
process and transfers the CPU to another process is called a preemptive CPU

e
scheduling. The process switches from running state to the ready state and waiting

in
state to the ready state.

ng
:
Non-preemptive scheduling Nonpreemptive operation usually proceeds towards
completion uninterrupted. Once the system has assigned a processor to a process,
fE
the system cannot remove that processor from the process. The process switches
from running state to the waiting state and termination of process.
O
8.3 Preemptive Real-time Operating Systems
e


Real time operating system executes processes based upon timing constraints
g

provided by the system designer. The most reliable way to meet timing constraints
le

accurately is to build a preemptive OS and to use priorities to


control what
process runs at any given time.
ol
C

8.3.1 Preemption
• A computation or task is preemptable if can
u

it be interrupted when another more


critical task needs to be executed. Fig. 8.3.1 shows
ad

the effect of preemption.


IRQ
iln

preemption Compteted
Task 1
m

Task 2
Ta

Time

IRQ
no preemption Completed

Task 1 ----
-

Task 2

Time
Fig. 8.3.1 Effect of preemption
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
<br>

Page 308 of 446

Embedded Systems and loT Design 8- 13 Processes and Operating Systems


The "C" function call is an alternative way of preemption
for controlling execution.
The CPU is shared multiple processes. Kernel is
in built with operating system
and it check what process is running. Timer is used for activating
the kernel. The
kernel is activated periodically. The Kernel interacts with the machines hardware.
. It
is the Kernel's job to keep each process and user separate and to
regulate access
to system hardware, including CPU, memory, disk and other

g
I/0 devices.
Task are given a limited amount of time of processor time called a time slice or

in
time quantum. The length of the timer period is known as the time quantum

er
because it is the smallest increment in which we can control CPUactivity.

e
• If a task does not complete before its quantum expires,
the system preempts it and

in
gives the processor to the next waiting task. The system then places the preempted
task at the back of the ready queue. On the next timer interrupt, the kernel may

ng
pick the same process or another process to run.
fE
• A context switch is the switching of the CPU from one process or thread to
another. A context is the contents of a CPU's registers and program counter at any
O
point in time.
Switching the CPU to another process requires performing a state save of the
e

current process and a state restore of a different process. This task is known as
a
g

context switch.
le

The data structure that holds the state of the process is known as the process
ol

control block.
a
C

Context switches can occur only in Kernel mode (system mode). Kernel mode is
runs and which provides
privileged mode of the CPU in which only the Kernel
u

resources.
access to all memory locations and all other system
ad

8.3.2 Priorities
iln

process will run next ? This is possible by


• How does the kernel determine what
priority of each process.
m

assigning priority to each process and kernel check the


CPU is a resource that must be
The priority is a non-negative integer value.
Ta

Kernel that apPportions CPUtime between


shared by all process. The part of the
processes is called the scheduler.
process priority dynamically. While a process is
It allows the Kernel to vary the
not running, the Kernel periodically increases its
priority. Whern a process receives
its priority.
Some CPUtime, the Kernel reduces
Priority - driven scheduling :
to be done. The priority-driven
Never leave processor idle when there is work
algorithms.
algorithms are on-line scheduling
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 309 of 446

Embedded Systems and loT Design 8-14 Processes and Operating Systems

Scheduling decisions are made when particular events in the system occur, for
:
example
a. Job becomes available b. Processor becomes idle
Priority-driven algorithms are event-driven.
Another name for this approach are greedy scheduling, list scheduling and
work-conserving scheduling.

g
Most scheduling algorithms used in non real-time systems are priority-driven.

in
Operating systems use a priority driven scheduler to schedule tasks. Examples :

er
FIFO, LIFO, SETF, LETE, EDF.
• A priority-driven algorithm is greedy because it tries to make locally

e
optimal
decisions. Leaving a resource idle while some job is ready to use the resource

in
is
not locally optimal.

ng
Yet another name is list scheduling. This is because any
can be implemented priority-driven algorithm
by fE
i. Assigning priorities to jobs.
ii. Place ready jobs in one or more queues ordered
O
by their priorities.
iii. At any scheduling decision time, jobs
with the highest priorities are scheduled
e

and executed on the available processors.


g

Priority assignment can be done as follows :


1. Per task : Every job
le

in the same task has the same


Monotonic Algorithm (RM): the higher priority. e.g. Rate
the rate, the higher is the priority of
ol

task. the
C

2. Per job : Each job in a task can have a


First (EDF):The earlier the deadline, different priority. e.g. Earliest Deadline
the higher the priority of the job.
u

3. Per time tick : Job


priority will be reassigned after
ad

Time First (LST) : The lower each tick e.g. Least Slack
the slack time, the higher the
• Possible implementation priority of the job.
of preemptive priority-driven
iln

1. Assign priorities to scheduling :


jobs.
2. Scheduling decisions are
m

made when job becomes ready or processor


idle or priorities of jobs change. becomes
Ta

3. At each scheduling
decision time, choose
In non-preemptive case, ready task with highest priority.
scheduling decisions are
becornes idle. made only when processor
Non-preemptive priority based
execution : When the processor
task with the highest priority is idle, the ready
is chosen for execution; once
chosen, a task is run to
completion.
Preemptive priority based execution :
When the processor is idle, the
with the highest priority 1s chosen for ready task
execution; at any time, execution
of a task
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 310 of 446

loT Desian Processes and Operating Systems


Embedded Systems and 8- 15

can be preempted if a task of higher priority becomes ready. Thus, at all times the
processor is either idle or executing the ready task with the highest priority.
have the priorities
.Example : Consider a program with 3 tasks I, T, and T, that
as follows :
repetition periods and computation times defined

Task Priority Period Computation Time

g
in
1
2

er
2 16 4

31

e
in
Overrun here

ng
T
fE
O
g e
le
ol
C

T3

13 14 15 16 17
u

9 10 11 12
5 6 7 8
1. 2 3 4
preemption
ad

Fig. 8.3.2 Priorities without


iln
m
Ta

10 11 12 13 14 15 16 17 18 19 20 21
1 5 6 7
2 3 preemption
Fig. 8.3.3 Priorities with
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 311l of 446

Embedded Systems and loT Design 8- 16 Processes and Operating Systems

Advantages of Prlority-drlven Scheduling


1. Easy to implement.
2. Itdoes not require the information on the release times and execution times of the
jobs a priori.
3. The run-time overhead due to maintaining a
priority queue of ready jobs can be

g
made.

in
Disadvantages of Priority-driven Scheduling

er
1. The timing behavior of a priority-driven system
is nondeterministic.

e
2. It is difficult to validate that all jobs
scheduled in a priority-driven manner meet

in
their deadlines when the job parameters vary.

ng
8.3.3 Processes and Context
fE
A context switch can mean a register context
switch, a task context switch, a
thread context switch or a process context switch.
O
A register is a small amount of very fast memory
inside of a CPUthat is used to
speed the execution of computer programs
e

Lused
by providing access
quick to commonly
values.
g

• A program
counter is a specialized register
le

that indicates the position of the CPU


in its instruction sequence and which
holds either the address of the
ol

being executed or the address instruction


of the next instruction to be
the specific system. executed, depending on
C

• Context switching can


be described in more
u

as the Kernel
following activities with regard to processes detail performing the
on the CPU:
ad

1. Suspending
the progression of one process
context) for that process and storing the CPU's state (i.e.,
somewhere in memory. the
iln

2. Retrieving the context


of the next process from memory
CPUs registers arnd and restoring it in the
m

3. Returning to
the location indicated
Ta

by the program counter


process. in order to resume the
Context switches can occur
only in Kernel mode
privileged mode of the (system mode). Kernel
CPU in which only mode is a
access to all memory the Kernel runs and
locations and all other system which provides
resources.
Other programs, including
can run portions applications, initially operate
of the Kernel code via system in user mode, but they
can be used on calls. Software context
all CPUs and can switching
be used to save and reload
needs to be changed. only the state that

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 312 of 446

Embedded Systems and loT


Design
8-17 Processes and Operating Systems

To use the hardware context switch you need to tell the CPU where to save the
existing CPU state and where to load the new CPU state from. The CPU state is
always stored in a special data structure called a TSS (Task State Segment).
Context switch times are highly dependent on hardware support. Context
Switching represents a substantial cost to the system in terms of CPU time and it
can be the most costly operation on an operating system.

g
There are three situations where a context switch needs to occur. Théy are

in
multitasking, interrupt handling, user and Kernel mode switching.

er
B.3.4 Processes and Object-oriented Design

e
in
as active objects. The
Unified Modeling Language (UML) refers to processes

ng
an active
objects that have independent threads of control. The class that defines
object is known as an active class.
Fig. 8.3.4 shows an example of
fE
a UML active class. It has all the normal
a name, attributes and operations. It also
characteristics of a class, including
O
can be used to communicate with the process.
provides.a set of signals that
e

name
g

BlackboardController attributes
le

currentKnowledgeSource operations
ol

signals
C

Signals
blackboardlsSolved
u

hasAHint
ad

Fig. 8.3.4 UML active


class
control.
represents an independent flow of
iln

are just classes which


• Active classes classes.
share the same properties as all other
Active classes started: when
m

created, the associated flow of control is


is terminated.
When an active object flow of control is
Ta

destroyed, the associated


the active object is classes
-
are, <<process>> Specifies
stereotypes that apply to active
Two standard execute concurrently
with other processes.
can
a
heavyweight flow that lightweight flow that can execute concurrently with other
Specifies a
<<thread>>-
same process.
threads within the a process are peers of
one another.
in the context of
All the threads that live

PUBLICATIONS - an up-thrust for knowledoe


TECHNICAL
<br>

Page 313 of 446

Embedded Systems and loT


Design 8-18 Processes and Operating Systems

8.4 Priority based Scheduling |AU : Dec.-12, 14, 16, May-13

8.4.1 Earliest-Deadline-First Scheduling


Earliest Deadline First (EDF) is one of the best known algorithms for real time
processing. It is an optimal dynamic algorithm. In dynamic priority algorithms, the

g
priority of a task can change during its execution It produces a valid schedule

in
whenever one exists.

er
EDF is a preenptive scheduling algorithm that dispatches the process with the

e
earliest deadline. If an arriving process has an earlier deadline than the
running

in
process, the system preempts the running process and
dispatches the arriving
process.

ng
• A task with a shorter deadline has a higher
priority. It executes a job with the

EDF is optimal among all scheduling algorithms not


fE
earliest deadline. Tasks cannot be scheduled by rate
monotonic algorithm.
keeping the processor idle at
O
certain times. Upper bound of process utilization is 100 %.
Whenever a new task arrive, sort the ready queue so
e

that the task closest to the


end of its period assigned the highest priority. System
g

preempt the running task if


it is not placed in the first of the queue in the last sorting.
le

• If two tasks have the same absolute


deadlines, chose one of the two at random
ol

(ties can be broken arbitrarily). The


priority is dynamic since it changes
for
C

different jobs of the same task.


EDF can also be applied to aperiodic-task
u

sets. Its optimality guarantees


maximal lateness is minimized when EDF that the
ad

is applied.
Many real time systems do not provide
hardware preemption, so other algorithm
must be employed.
iln

In scheduling theory, a real-time system


conmprises a set of real-time
m

task consists of an infinite or finite stream tasks; each


a of jobs. The task set can be scheduled
by number of policies including
Ta

fixed priority or dynamic priority


algorithms.
The success of a real-time system
can be guaranteed to depends on whether all the jobs of
complete their executions before all the tasks
their deadlines. If they can,
then we say the task set is schedulable.
The schedulability condition is that
the total utilization of the task set must
than or equal to 1. be less
Implementation of earliest deadline first : Is
it really not feasible to implement
EDF scheduling.
TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
<br>

Page 314 of 446

Embedded Systems and loT Desian


8-19 Processes and Operating Systems

Task Arrival Duration Deadline


0 10 33

28

5 10 29

g
Task arrivals

in
e er
T

in
ng
--Earlier deadline
(preemption)

T2 fE
O
e

T3
g
le

Later deadline
(No preemption)
ol
C

4 6 10 12 14 16 18 20
Fig. 8.4.1
u

Problems for implementations :


ad

1. Absolute deadlines change for each new task instance, therefore the priority needs
queue.
to be updated every time the task moves back to the ready
iln

2. More important, absolute deadlines are always increasing, how can


we associate a
finite priority value to an
ever increasing deadline value.
m

3. Most important, absolute deadlines are impossible to compute a-priori.


Ta

EDF properties :
1. EDF is optimal with respect to feasibility (i.e.
schedulability).
lateness.
2. EDF is optimal with respect to minimizing the maximum
Advantages
1. It is optimal algorithm.
2. Periodic, aperiodic and sporadic tasks
are scheduled using EDF algorithm.
3. Gives best CPUutilization.

TEOHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 315 of 446

Embedded Systems and loT Design 8-20 Processes and Operating Systems

Disadvantages
1. Needs priority queue for storing deadlines.
2. Needs dynamic priorities.
3. Typically no OS support.
4. Behaves badly under overload.

g
5. Difficult to implement.

in
Example 8.4.1 Schedulability test for EDE.

er
Task Period CPU burst

e
in
9 6

ng
T; 15 5
Ta 5
fE
Test if the given task set is schedulable with EDF.
Solution:
O
CPU,Utilization (U) = C3
e

P
P,
g

8:4:2: Rate Monotonic Scheduling


le
ol

Rate Monotonic Priority Assignment


(RM) is a so called static priority round robin
scheduling algorithm.
C

In this algorithm, priority is increases


with the rate at which a process must
u

scheduled. The process of lowest period be


will get the highest priority.
ad

The priorities are assigned to tasks before


execution and do not change over
scheduling is preemptive, i.e., a task can time. RM
be preempted by atask with higher
iln

• In RM algorithms, the assigned priority.


priority is never modified during
system. RM assigns priorities runtime of the
m

simply in accordance with its


priority is as higher as shorter is periods, i.e. the
the period which means as
Ta

activation rate. So RM is a scheduling higher is the


algorithm for periodic task sets.
• If a lower priority process
is running and a higher
available to run, it will preempt priority process becomes
the lower priority process. Each
assigned a priority inversely based on its periodic task is
1. The shorter period :
the period, the higher the priority.
2. The longer the period, the
lower the priority.

TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 316 of 446

Embedded Systems and loT Design


8-21
. The algorithm was provern
Processes and Operating Systems
under the following assumptions :
1. Tasks are periodic.
2. Each task must
be completed before the next request occurs.
3. All tasks are independent.
4.Run time of each task request
is constant.
5. Any non-periodic

g
task in the system has no required
deadlines.

in
• RMS is optimal among
all fixed priority schduling algorithms
periodic tasks where the deadlines for scheduling

er
of the tasks equal their periods.
Rate monitoring example

e
in
Task (T) Period (P)

ng
CPU burst (C)
2
3
fE 1.01
O
1 1.01
Utilization =
P 3
e

= 0.5 + 0.3366 = 0.8366


g
le

U= 83.66 %
ol
C
u

T
ad
iln
m

Time
3 4 5 6
Fig. 8.4.2 (a)
Ta

T.
Missed deadline

0
Fig. 8.4.2 (b)
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 317 of 446

Embedded Systems and loT Design 8-22 Processes and Operating Systems

Advantages :

1. Simple to understand. 2. Easy to implement. 3. Stable algorithm.

Disadvantages :
1. Lower CPUutilization.

g
2. Only deal with independent tasks.

in
3. Non-precise schedulability analysis.

er
8.4.2.1 Comparison between RMS and EDF

e
in
Parameters RMS EDF

ng
Priorities Static Dynamic
Works with OS with fixed priorities
Uses full computational power of processor
fE Yes No
No Yes
O
Possible to exploit full computational power
of No Yes
Processor without provisioning for slack
g e

Example 8.4.2 Consider three tasks


T1, T2 and T3. All timing is in milliseconds.
le
ol

Task Phase Execution Relative Period


time
C

deadline
T1 20 10 20 20
u

T2 40 10 50
ad

50
T3 70 20 80 80
iln

Calculate the length of time by using table


driven scheduler.
Solution: The tasks in the schedule
m

will automatically repeat


The major cycle of a set of tasks is after every major cycle.
LCM of the periods even
when the tasks have
Ta

arbitrary phasing.
Major cycle = LCM (20, 50, 80) = 400 ms

8.4.3 Priority Inversion


Priority inversion occurs when a
low-priority job executes while some
higher-priority job waits. ready
• Fig. 8.4.3 shows priority inversion
method.

TECHNICAL PUBLICATIONs- an up-thrust


for knowledge
<br>

Page 318 of 446

Embedded Systems and loT Desian


8-23 Processes and Operating Systems
Consider three tasks T1, T2 and T3
with decreasing priorities. Task T1 and 13
share some data or resource that requires
exclusive access, while T2 does not
interact with either of the other two
tasks.
.
Task T3 starts at time to and locks semaphore s
at time t,. At time t2, T1 arrives
and preempts T3 inside its critical section. After a
while, T1 requests to use the
shared resource by attempting to lock s, but it gets blocked, as
T3 is currently

g
using it. Hence, at time t3 continues to execute inside its critical
section. Next,

in
when T2 arrives at time t4, it preempts T3, as it has a higher priority
not interact with either T1 or T3. and does

e er
T1 Blocked

in
Normal execution

ng
Critical T2
section
T3

t4 t t
fE
t Time
O
Fig. 8.4.3 Priority inversion method
e

The execution time of T2 increases the blocking time of T1, as it is no longer


g

dependent solely on the length of the critical section executed by T3.


le

• When tasks share resources, there may be priority inversions.


ol
C

Priority inversion
u

J.
ad

J,
iln

Ja

6 8 10 12 14 16 18
m

4
0 2

Fig. 8.4.4 Priority inversion example


Ta

some cases, the priority inversion


Priority inversion is not avoidable; However, in
could be too large.
:
Simple solutions
1. Make critical sections non-preemptable.

2. Execute critical sections at the highest priority of the


task that could use it.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 319 of 446

Embedded Systems and loT Design 8-24 Processes and Operating Systems

The solution of the problem is rather simple; while the low priority task blocks an
higher priority task, it inherits the priority of the higher priority task; in this way,
every medium priority task cannot make preemption.
Timing anomalies
As seen, contention for resources can cause timing anomalies due to priority

g
inversion and deadlock. Unless controlled, these anomalies can be arbitrary

in
duration, and can seriously disrupt system timing.

er
• It cannot eliminate these anomalies, but several protocols exist to control them :

e
1. Priority inheritance protocol.

in
2. Basic priority ceiling protocol.

ng
3. Stack-based priority ceiling protocol.

Wait for graph fE


Wait-for graph is used for representing dynamic-blocking relationship among jobs.
In the wait-for graph of a system, every job that requires some resource
O
is
represented by a vertex labeled by the name of the job.
e

At any time, the wait-for graph contains an (ownership) edge with label x
from a
g

resource vertex to a job vertex if x units


of the resource are allocated to the job at
le

the time.
ol

Wait-for-graph is used to model resource contention. Every


serial reusable resource
is modeled. Every job which requires a resource is modeled by vertex
C

with arrow
pointing towards the resource.
u

Every job holding a resource is represented


by a vertex pointing away from the
ad

resource and towards the job.


A cyclic path in a wait-for-graph indicates
Fig. 8.4.5 shows wait for graph. deadlock.
iln
m
Ta

Fig. 8.4.5 Wait for graph


. L has locked the single unit of resource R
and J, is waiting to lock it.
.A minimum of two system resources are required in a deadlock.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 320 of 446

Embedded Systems and loT Desian Processes and Operating Systems


8-25

Review Questions

1. Describe any tw0 scheduling policies used in multiprocess environment.

AU': Dec.-12; Marks 6


2. Explain the principle of priority based context suitching mechanism. Discuss about the varios

g
priority based scheduling algorithms. AU : May-13, Marks.16

in
3. Describe in detail about the scheduling policies with suitable examples.

er
AU.: Dec.-14, Marks 16
4. Explain in detail rate monotonic scheduling with an exanple. AU: Dec:-16, Marks 8

e
in
8.5 Interprocess Communication Mechanisms AU: Deç:12;13, May-13.

ng
Exchange of data between two or more separate, independent processes/threads is
possible using IPC. Operating systems provide facilities/resources for Inter-Process
fE
Communications (IPC), such as message queues, semaphores and shared memory.
A complex programming environment often uses multiple cooperating processes to
O
perform' related operations. These processes must communicate with each other
e

and share resources and information. The Kernel must provide mechanisms that
make this possible. These mechanisms are collectively referred to as interprocess
g
le

communication.
to provide
Distributed computing systems make use of these facilities/resources
ol

Application Programming Interface (API) which allows IPC to be programmed at


C

a higher level of abstraction. (e.g-, send and receive).


are as follows:
u

Five types of inter-process communication


1. Shared memory permits processes to communicate by simply reading and
ad

memory location.
writing to a specified
iln

memory, except that it is associated with


2. Mapped memory is similar to shared
a file in the file system.
m

one process to a related'process.


3. Pipes permit sequential communication from
Ta

processes can communicate


4. FIFOS are similar to pipes, except that unrelated
a name in the file system.
because the pipe is given
processes even on different
5. Sockets support communication between unrelated

computers.

knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>

Page 321 of 446

Embedded Systems and loT Design Processes and Operating Systems


8-26

Name Description Scope Use


File Data is written to and read from a typical Local Sharing large data
UNIX ile. sets.

Any numnber of processes can interoperate.

g
Pipe Data is transferred between two processes Local Simple data

in
using dedicated file descriptors. sharing, such as
Communication occurs only between a producer and

er
Consumer.
parent and child process.

e
Named Data is exchanged between processes via Local Producer and
pipe

in
dedicated file descriptors. consumer or
command-and-contr

ng
'Communication can occur between any two
ol, as demonstrated
peer processes on the same host. with MySQL server
fE and its
command-line
query utility.
Signal An interrupt alerts the application
O
to a Local
specific condition.
Cannot transfer
data in a signal, so
mostly useful for
e

process
g

Shared Information is shared by management.


reading and
le

memory Local Cooperative work


writing from a Common segment
of of any kind,
memory.
ol

especially if security
Socket is required.
After special setup, data
C

is transferred Local or
using common input/output operations. Network services
remote such as FTP, ssh,
u

and the Apache


Web Server.
ad

Table 8.5.1 Interprocess


communication in UNIX
Purposes of IPC
1. Data transfer :
iln

One process may


wish to send data to another process. User
processes User
processes
m

2. Sharing data : Multiple processes


may wish to operate on
shared
Ta

data, such that if a process Kernel


modifies the data, that change IPC on same
will be immediately visible to host
other processes sharing it. User
processes User
3. Event modification : processes
A process
may wish to notify another
process Or set of processes that Kemel Kernel
some event has occurred. IPC on different hosts
Fig. 8.5.1 IPC on different
hosts
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 322 of 446

Embedded | Systems and loT Design


8-27 Processes and Operating Systems
4. Resource sharing : The Kernel
allocatiorn; they are
provides default semantics for resource
not suitable for all application.
5. Process
control : A process such as a debugger may
control over the execution wish to assume complete
of another process.
TPC has two forms :
PC on same host and IPC on different hosts.
PC s used for two functions :

g
in
1) Synchronization : Used to coordinate access to resources among processes
to coordinate the execution of these processes.
and aiso

er
They are record loCking
Semaphores, mutexes and condition variables.

e
2) Message passing : Used when processes wish to exchange information. Message

in
pässing takes several forms such as: Pipes, FIFOs, Message queues arnd shared

ng
memory.

8.5.1 Features of Message Passing fE


1.Simplicity : Message passing system should be simple and easy to use. It should
O
be possible to communicate with old and new applications.
e

2. Uniform semantics : Message passing is used for two types of IPC.


g

a. Local communication : Communicating processes are on the same node.


le

b. Remote commnunication : Communicating processes are on the different nodes.


ol

3. Efficiency :
IPC become so expansive if message passing system is not effective.
Users try avoiding to IPC for their applications. Message passing system will
C

more message exchanges during


become more efficient if we try to avoid
u

:
communication process. For examples
ad

connection.
a. Avoiding the costs of establishing and terminating

b. Minimizing the costs of


maintaining the connections.
iln

c Piggybacking of acknowledgement.
catastrophic events such as
m

4. Reliability
:
Distributed systems are prone to different communication
failures. Loss of message because of
Ta

node crashes or physical link messages, we required acknowledgement and


link fails. To handle the loss
Duplicate message is, one of the major problems. This
retransmission policy.
or events of failures.
nappens because of timeouts
a feature related to IPC protocols for group
5. Correctness : Correctness is as follows :
correctness are
communication. Issues related to to
message sent to a group of receivers will be delivered
Atomicity : Every
either all of them
or none of them.
all receivers in an order acceptable to the
: Messages arrive to
i. Ordered delivery
application. PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 323 of 446

Embedded Systems and loT Design 8-28 Processes and Operating Systems

iii. Survivability : Messages will be correctly delivered despite partial failures of


processes, machine or communication links.
6. Security : Message passing system must provide a secure end to end
communication.

g
:
7. Portability Message passing systerm should itself be portable.

in
8.5.2 IPC Message Format

er
Message passing system requires the synchronization and communication between

e
the two processes. Message passing used as a method of communication in

in
microkernels. Message passing systems come in many forms. Messages sent by a

ng
process can be either fixed or variable size.
The actual function of message passing
is normally provided in the form of a pair of primitives.
a) Send (destination _name, message)
b) Receive (source_name, message)
fE
O
Send primitive is used for sending a message to
destination. Process sends
information in the form of a message to
another process designated by a
e

destination. A process receives information by


executing the receive primitive,
g

which indicates the source of the sending process


and the message.
le

Design characteristics of message system for IPC.


1. Synchronization between the process
ol

2. Addressing
C

3. Format of the message


u

4. Queueing discipline.
ad

Issues in IPC by Message Passing


Message is a block of information.
iln

A message is a meaningful formatted


block of information sent by the
process to the receiver process. sender
m

The message block consists of a fixed


length header followed by a variable size
Ta

collection of typed data objects.


. The header
block of a message may have the following
:
1. Address A set of characters elements :
that uniquely identify both the sender and receiver.
2. Sequence number : It is the message identifier to identify
duplicate and lost
messages in case of system failures.
a Structural information :
It has two parts. The type part
to that specifies whether the
data be sent to the receiver is included within the message or
the message only
contains a pointer to the data. 1he second part specifies length of the variable-size
message.
TECHNICAL PUBLICATIONS - an up-thrust for knowledge
<br>

Page 324 of 446

Embedded Systems and loT Design 8- 29 Processes and Operating Systems

Fig. 8.5.2 shows the typical message format.

Structural information Addresses


Actual data Sequence
or pointer Number of number Receiving Sending
to the data bytes/ Type or message ID process process
addressaddress

g
elements

in
HVariable - Fixed-length header

er
size collection
of typed data

e
Fig. 8.5.2 Message structure

in
Some important issues to be considered for the design of an IPC protocol based

ng
message passing system :
i. The sender's identity

ii. The receiver's identity


fE
ii. Number of receivers
O
iv. Guaranteed acceptance of sent messages by the receiver
e

v. Acknowledgement by the sender


g

vi. Handling system crashes or link failures


le

vii. Handling of buffers


ol

vii. Order of delivery of messages.


C

8.5.3 IPC Synchronization


u

can be
ad

Send operation can be synchronous or asynchronous. Receive operation


blocking or nonblocking.
iln

or nonblocking mode. Different


Sender and receiver process can be blocking mode :
are as follows
possibility of sender and receivers
m

1. Blocking send, blocking receive.


Ta

2. Nonblocking send, block receive.


3. Nonblocking send, Nonblocking receive.
Blocking send, blocking receive message. synchronous
Blocking send must wait for the receiver to receive the
processes (sender and
communication is an example of blocking send. Both
message is delivered.
receiver) are blocked untill the
process leaving the sender process
Rendezvous : Sending a message to another
processed.
Suspended until the message is received and

TECHNICAL PUBLICATIONs an up-thrust for knowledge


-
<br>

Page 325 of 446

Embedded Systems and loT Design 8-30 Processes and Operating Systems

Nonblocking send, blocking receive


Sender is free to send the messages but receiver is blocked until the requested
message arrives.
Asynchronous communication is an example of nonblocking send. Asynchronous
communication with nonblocking sends increases throughput by reducing the time

g
that processes spend waiting.

in
Natural concurrent programming task uses the nonblocking send. Nonblocking

er
send is the overhead on the programmer for determine that a message has been
received or not.

e
in
8.5.4 Shared Memory

ng
A region of memory that is shared by co-operating processes is established.
Processes can then exchange information by reading and writing data to the
shared region.
fE
Shared memory allows maximum speed and convenience of communication, as it
O
can be done at memory speeds when within a computer.
Shared memory is faster
than message passing, as message-passing systems are typically implemented
e

using system calls and thus require the more time-consuming task of Kernel
g

intervention.
le

• In contrast, in shared-memory systems, system calls are


required only to establish
ol

shared-memory regions.
Once shared memory is
C

established, all accesses Client


Shared memory Server
are treated as routine
u

memory accesses, and no


ad

assistance from the


Kernel is required.
iln

Fig. 8.5.3 shows client / Kernel


server
m

with shared Output file


memory. Input file
Ta

Advantages Fig. 8.5.3 Client lserver with shared menmory


1.Good for sharing large amount of
data. 2. Very fast.
Limitations
1 Nosynchronization provided -
applications must create their own.
Alternative to Shared memory is mmap
system call, which maps file
address space of the caller. into the

TECHNICAL PUBLICATIONs
an up-thrust for knowledge
<br>

Page 326 of 446

8-31 Processes and Operating Systems


Review Questions
1 Discuss about interprocess
communication mechanisms.
2. Explain in detail AU : Dec.-12, Marks 6
how shared memory and message
passing mechanisms are used
communication. for inter process
:
AU May-13, Marks 16
3. Explain about
inter process communication mechanism
with neat sketch.

g
AU : Dec.-13, Marks 16

in
8.6 Distributed Embedded Systems :
AU May-13, Dec.-13,14
. In a distributed

er
embedded system, several Processing Elements
(PES) are

e
connected by a network that allows them to
communicate. Fig. 8.6.1 shows an

in
example of a distributed emnbedded system.

ng
Processing element 1
Processing element 2
(16-bit CPU), (Sensor)
fE Processing element 3
(Digital signal processing)
O
Network
g e

Processing element 4 Processing element 5


(ASIC) (Microcontroller)
le
ol

Fig. 8.6.1 Distributed embedded system


C

Processing elements may includes DSP, CPU or microcontroller.


u

Nonprogrammable unit such as the ASICs is also used to implement as PE.


ad

• By using this entire processing elenent, it forms bus topology. It is also possible
to form other topology also. It is also possible that the system can use more than
iln

one network, such as when relatively independent functions require relatively little
m

communication among them.


link. The system of
All the processing elements are connected by communication
Ta

on which the application runs.


PEs and networks forms the hardware platform

8.6.1 Why Distributed


cost.
Higher performance at lower
constants may not allow transmission to
Physically distributed activities, i.e. time
central site.
debugging :
Use one CPU in network to debug others.
Improved

TECHNICAL PUBLICATIONS
- an up-thrust for knowiedge
<br>

Page 327 of 446

Embedded Systems and loT Design 8-32 Processes and Operating Systems

May buy subsystems that have embedded processors.


Distributed systems are necessary because the devices that the PEs communicate
with are physically separated.

8.6.2 Network Abstractions


• Networks are complex systems. They provide high-level services while hiding

g
many of the details of data transmission from the other components in the system.

in
• To understand network design, the International Standards Organization has

er
developed a seven-layer mnodel for networks known as Open Systems

e
Interconnection (OSI ) models.

in
• It is based on a common model of network architecture
and a suite of protocols

ng
used in its implementation. The International Organization for Standardization
(SO) established the Open Systems Interconnection (0SI) Reference Model.

seven layers in the model, hence the name


fE
Each layer deals with a particular aspect of network communication.
There are
the 7-Layer model. The model acts as a
O
frame of reference in the design of communications
and networking products.
Fig. 8.6.2 shows OSI layers.
g e

7. Application layer
le

6. Presentation layer
ol

5. Session layer
C

4. Transport layer
u

3. Network layer
ad

2. Data link layer


iln

1. Physical layer
m

Fig. 8.6.2 OSI layers


Ta

The OSI model describes


how information or data
programmers makes its way from application
through a network medium to
located on another network. another application programmer
The OSI reference model
Changes in one layer should is a hierarchical structure.
. not require changes
Fig. 8.6.3 shows flow in other layers.
of data from sending computer
1. Physical layer : The lowest to receiving computer.
layer of the OSI model.
transmission and reception It is concerned with the
of the unstructured raw
medium. It describes the electrical/optical, bit stream over a physical
the physical medium and carries mechanical and functional
interfaces to
the signals for the entire
higher layer.
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 328 of 446

Embedded Systems and loT Design


8-33 Processes and Operating Systems

Sending computer
Receiving computer
Application Application
Presentation
Presentation
Session Session
Transport Transport

g
in
Network Network

er
Data link Data link
Physical

e
Physical

in
ng
Fig. 8.6.3 Flow of data
2. fE
Data link layer : DLL is responsible for the transfer of data over the channel. It
groups zeros and ones into frames. A frame is a series of bits that forms a unit of
O
data. The data link layer provides error-free transfer of data frames from one node
to another over the physical layer. It contains two sublayers : Medium Access
e

Control (MAC) and Logical Link Control Layer (LLC). DLL divides the bit stream
g

of the physical layer into frames, messages containing data and control
le

information. It handles lost, damaged and duplicate frames.


ol

3. Network layer : This is responsible for addressing messages and data so they are
sent to the correct destination and for translating logical addresses and names into
C

physical addresses. This layer is also responsible for finding a path through the
network to the destination computer. Lowest layer that deals with host-to-host
u

communication, call this end-to-end communication. Functions of network layer :


ad

Logical addressing, Routing and Frame fragmentation


iln

4. The transport layer ensures that messages are delivered error-free, in sequence, and
with no losses or, duplications. It relieves the higher layer protocols from any
m

concern with the transfer of data between them and their peers. It also provides
message acknowledgement.
flow control, sequence numbering and
Ta

Function of transport layer : Message segmentation, Message acknowledgment,


Session multiplexing
manace
5. The session layer adds mechanisms to establish, maintain, synchronize and
communication between network entities. The session layer allows session
establishment between processes running on different stations. Services provided
management.
by session layer Synchronization and dialog
:

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 329 of 446

Embedded Systems and loT Design 8-34 Processes and Operating Systems

6. The presentation layer is responsible for data compression, data expansion, data
encryption and data decryption.
7. Application layer : It contains all services or protocols needed by application
software or operating system to communicate on the network. Typical applications
include a client/server application, an e-mail and an application to transfer files

g
using FTP or HTTP.

in
8.6.3. Hardware and Software Architectures

er
Distributed embedded systems can be organized in many different ways

e
depending upon the needs of theapplication and cost constraints.

in
Point-to-point :

ng
Point-to-point link establishes a connection between exactly two PEs. Point-to-point
links are simple to design precisely because they deal with only two components.
Fig. 8.6.4 shows point-to-point link. fE
O
PE 1
PE 2 PE 3
Link 1
Link 2
g e

Fig. 8.6.4 Signal processing system built from print-to-point


links
le

Input device sampled the signal and passed to the first


digital filter (F1) by using
point-to-point link. The results of that filter are sent
ol

through a second
point-to-point link to filter (F2). The results in turn are sernt to
the output device
C

over a third point-to-point link.


• Filters must process their
inputs in a timely fashion. It is possible to
u

duplex point-to-point distributed system. build full


ad

A bus is a more general form of


network since it allows multiple
connected to it. Like a microprocessor devices to be
iln

bus, PEs connected to the


addresses. bus have
m

Communication between processing


elements takes place
Fig. 8.6.5 shows format
of packet. by using packets.
Ta

Header Address Data Error


correction

Fig. 8.6.5 Format Time


of packet
Dnt contains destination address, user
data and error correction
data size is not exdctuy codes, Sending
t into paCket but processing elemernts must
take care of
packet.
TECHNICAL PUBLICATIONS an up-thrust
for knowledge
<br>

Page 330 of 446

Embedded Systems and loT Desian


8-35 Processes and Operating Systems
. The data to be transmitted from one PE to another may not fit exactly
into the
size of the data payload on the packet. It is the responsibility of the
transmitting
PE to divide its data into packets; the receiving PE must of course
reassemble the
complete data message from the packets.
Arbitration scheme

g
The device that is allowed to initiate transfers on the bus at any given time is

in
called the bus mnaster.
1. Fixed-priority arbitration : High priority devices always get chance to transmit

er
data. If low priority device and high priority device are ready to transmit data,

e
then high priority device will transmit data then low priority device will transmit

in
data.

ng
2. Fair arbitration schemes : This scheme take care of starvation. Round-robin
arbitration is the most commonly used of the fair arbitration schemes. The PCI bus
fE
requires that the arbitration scheme used on the bus must be fair, although it does
"not specify a particular arbitration scheme. Most implementations of PCI use
O
round-robin arbitration.
e

Crossbar network
• A bus topology provides limited available bandwidth. Since all devices connect to
g

the bus, communications can interfere with each other. For reducing
le

can be used.
communication conflicts, other network topology
ol

a switch that connects an input to an


Fig. 8.6.6 shows crossbar. A cross point is
C

output.
u
ad

switching
A

element
o
iln
m

2
Ta

Fig. 8.6.6 Direct network crossbar

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 33 l of 446

Embedded Systems and loT Design 8-36 Processes and Operating Systems

A crossbar network uses an p x m grid of switches to connect p inputs to m


outputs in a non-blocking manner. A connection of one processor to a given
memory bank does not block a connection of another processor to a different
memory bank. There must be p x b switches. It is reasonable to assumne that b> p.
• A link carries one message; a switch can process up to two messages at the same

g
time. Crossbar is not fault tolerant, failure of any switchbox will disconnect certain

in
pairs.

er
To connect an input to an output, we activate the cross point at the intersection
between the corresponding input and output lines in the crossbar.

e
Crossbars have excellent performance scalability but poor cost scalability.

in
Fig. 8.6.7 shows multistage network. One of the most commonly used multistage

ng
interconnects is the Omega network. This network consists of log p stages, where
p is the number of inputs and also the number of outputs.
fE
O
g e
le
ol

Fig. 8.6.7 Muitistage network


• A crossbar is non-blocking.
C

Most embedded network ports on


implement the basic communication functions microprocessors
in hardware and implement many
u

other operations in software.


ad

8.6.4 Message Passing Programming


iln

• A message-passing system. a
is subsystem of
provides a set of message-based IPC protocols distributed operating system that
m

of complex network protocols and does so by shielding the details


programmers. It enables processes and multiple heterogeneous platforms from
Ta

to communicate
allows programs to be written by by exchanging messages and
using simple communication primitives,
send and receive. such as
Transport layer provides message-based programming
interface:
send_msg (adrs, datal);
Data must be broken into packets at source,
reassembled at destination.
Data-push programming Receivers respond to new data.
:

TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>

Page 332 of 446

Embedded Systems and loT Desian Processes and Operating Systems


8-37

Review Questions

1. Explain any one type of network used for embedded system design. AU: May-13, Marks 8

2. Discuss in detail about distributed embedded architecture with neat sketches.


AU:: Dec.-13, Marks. 16
3. Discuss in detail about the distributed embedded architecture. AU.: Dec:-14, Marks.16

g
8.7 MPSoCs and Shared

in
Memory Multiprocessors

er
Single processors may be sufficient for low-performance applications that are
typical of early microcontrollers, but an increasing number of applications require

e
multiprocessors to meet their performance goals.

in
Multiprocessor Systems-on-Chips (MPSoC) are one of the key applications of

ng
today. MPSoC are increasingly used to build complex integrated system. A MPSoC
is more than just a rack of processors shrunk down to a single chip.
fE
• Definition : Multiprocessor is Parallel processors with a single shared address.
O
Microprocessor is now the most cost-effective processor. Multiprocessors have the
highest absolute performance-faster than the fastest uniprocessor.
e

• Parallel processing program is a single program that runs on multiple processors


g

simultaneously.
le

Cluster is a set of computers connected over Local Area Network (LAN) that
a
ol

function as a single large multiprocessor.


C

a space,
Shared memory is a memory for a parallel processor with single address
loads and stores.
implying implicit communication with
u

may be several
:

The typical MPSoC is a heterogeneous multiprocessor. There


ad

may be heterogeneously distributed


different types of PEs, the memory system
PEs and the
around the machine and the interconnection network between the
iln

memory may also be heterogeneous.


m

memory. The device may have embedded


MPSoCs often require large amounts of memory.
memory on-chip as well as relying on off-chip commodity
Ta

force of a number
System-on-Chip (SoC) designs increasingly become the driving
on Chip refers to integrating
of modern electronics systems. Conceptually System
a single chip. Looks straightforward but
the components of a board onto
make it a reality.
productivity levels are too low to
: processor, ASIC logics and analog circuitrv
The Soc chip includes Embedded
and Embedded memory.

TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 333 of 446

Embedded Systems and loT Design 8-38 Processes and Operating Systems

The SoC software includes : 0S, compiler, simulator, firmware, driver, protocol
stack Integrated development environment (debugger, linker, ICE) application
interface (C/C++, assembly)
Fig. 8.7.1 shows block diagram of SoC.

g
Embedded software

in
AP

er
Memory MPU/CPU

e
in
Configurable
hardware

ng
Interface DSP
and peripherals Core
ASIC
fE
ADC
O
DAC
g e

RFIF subsystem
le

Fig. 8.7.1 System on chip


ol

1. Memory controller : Interfaces with the onboard RAM.


C

2. DMA : Handles the automated


transfers of data between the RAM
and
u

memory-mapped hardware.
ad

3. USB controller: Manages


the hardware side of the device's USB
core connections.
4. DSP : It provides
hardware acceleration for some signal
iln

JPEG encoding. processing, such as


5. Display : Enables
the SoC to drive various display types.
m

6. Camera : Allows
the SoC to interface with a camera.
Ta

7. Storage : Manages
I/O with the various types of storage that can
SoC. be used with the
8. Debug : Enables
the SoC to be connected to
various mechanisms, hardware debugging tools
such as JTAG. through
Fig. 8.7.2 shows the
traditional view of a shared-memory
consists of a pool of processors multiprocessor. It
and a pool of memory are
interconnection network. connected by an

TECHNICAL
PUBLICATIONs -
an up-thrust for knowledge
<br>

Page 334 of 446

Embedded Systems and loT Desian 8-39 Processes and Operating Systems

CPU 1
CPU 2 CPU N

Interconnection hetwork

g
Main Main Main Min

in
memory 1
memory2 memory3 memory N

er
Fig. 8.7.2 Shared memory
• A shared-memory model is often preferred because it makes life simpler for the

e
programmer. The Raw architecture is a recent example of a regular architecture

in
designed for high-performance computation.

ng
Signal address : Offer the programmer a single memory address space that all
processors share. Processors communicate through shared variables in memory,
fE stores.
with all processors capable of accessing any memory location via loads and
O
Message passing : Communicating between multiple processors by explicitly
sending and receiving information.
e

mnemory may be accessible by


Heterogeneous memory systems Some blocks of
:
g

memory systems are harder to


only one or a few processors. Heterogenous
le

access
program because the programmer must keep in mind what processors can
ol

what memory blocks.


necessary in MPSoCs. One reason that
C

Irregular memory structures are often


memory is to support real-time perfornmance.
designers resort to specialized
u
ad

Challenges and Opportunities


systems and
MPSoCs combine the difficulties of building complex hardware
iln

complex software systems.


Methodology is critical to MPSoC design. Methodologies that
work offer many
m

to design a system; they also make it


advantages. They decrease the time it takes resources it will
take and how many
Ta

easier to predict how long the design will


for improving performance and
require. Methodology also codify techniques many
can apply to different designs.
power consumption that developers
a target for the next decade.
Methodology will necessarily be moving
• MPSoC hardware architectures present challenges
in all aspects of the
memory and interconnects.
multiprocessor : Processing elements,
sets are one way to improve
Configurable processors with customized instruction
characteristics of processing elements; hardware/software code sign of
the
accelerators is another technique.
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 335 of 446

Embedded Systems and loT Design 8-40 Processes and Operating Systems
:
8.8 Design Example Audio Player
Audio players are often called MP3 players after the popular audio data format.
An MP3 player performs three basic functions : Audio storage, audio
decompression and user interface.

g
The MP3 player we designed is main made up of four parts, which are embedded

in
processor, interface module, storage and external devices. Fig. 8.8.1 shows

er
hardware design of MP3 player.

e
in
Network
module

ng
JTAG LCD
controller
UART MCU
fE
based on
controller
LED
LCD

controller ARM LED


Controller
O
Audio data Flash
Audio Button
decoding. controller SDRAM Button
controller
e

module 12C I Embedded processor SD card


g

controller SD card
controller
le

MP3 decoder
ol
C

Fig. 8.8.1 Hardware design of MP3 player


u

• The most important


hardware module in MP3 player is the decoder
module.
ad

Generally speaking, most MP3 players use DSP core or


dual core which is
comprised by DSP and RISC to solve the complexity
of application algorithms.
iln

However, with the rapid development of processor


design and related technology,
the capability of digital signal processing of RISC
approaches DSP level in the last
m

few years.
Ta

Therefore, it is of vital importance to


implement MP3 decoder based RISC core.
On the other hand, as RISC core can be
control unit, it is useful for resource used as both audio decoding unit
constrained System on Chip design. and
From all the above analysis, we
adopt RISC32 architecture based
processor in our design. embedded
Our MP3 decoder reads the MP3 file and
samples through I2S interface. sends the

TECHNIGCAL PUBLICATIONS - an up-thrust


for knowladge
<br>

Page 336 of 446

Fmbeted Systams and io T Desgn


Procssss nd Operaiing Systens

B9 Engine Control Unit


. Engine Control Unit (EC)
management systrm It coetrols
he cntral cuntrslet
he fui aupy,
a
heart d
aageent tueš
ege
Tea
e
and ignition
. The engine cotrol unit manages
aregreet e the ergh. peiars

g
then implement the Esampies ot tuiete
tade crieret pente

in
position and eshauat yat tquitmets foe
. he mitte (oegeior
Torqu serves as the kry entsos o peng

er
at equente The kast
tatso i regulate athat he ogar i peosdet t etcienty A peibia

e
in
afety and diagrotac fu ara

ng
fE
O
g e
le
ol
C
u
ad

prvent a coso
to
iln

8.10 Video Accelerator


m

at ptot a
* In block baned mothos eetiata, hal i ofac
Ta

pixels, every frame is lacks et ega eah b k


y
divae
Current tratne a rsch perfarme eteeE ate ht bak
tesembling the current block e iel
• Block motion estimation i u ga! vls éosgin alge a
one frare in the vdeo can be decte etha ed
e ditieecs et
d
aother frame.

THONS
TECHINIAL PUBLICA
<br>

Page 337 of 446

Embedded Systems and loT Design 8-42 Processes and Operating Systems

• Frame is selected as a reference and subsequernt frames are predicted from the
reference. The 60 % computational complexity at encoder side. Fast algorithms are
necessary for real time applications.
The' process of video compression using motion estimation is also known as
inter-framne coding. For scene (shot) changes, inter-frame coding does not work

g
well.

in
A second compression technique is used, known as intra-frame coding.

er
• For each block of 16 x 16 luminance pels in the current frame, a
motion vector is

e
computed. This motion vector contains the relative position of the block mnost

in
closely resembling the current block in the reference frame.
The motion estimation creates a model by modifying one or more

ng
to match the current frame as closely as
reference frames
possible.
The current frame is motion compensated by subtracting
fE the model fromn the
frame to produce a motion-compensated residual
frame. This is coded and
transmitted, along with the information required
O
for the decoder to recreate the
model.
At the same time, the encoded residual
e

is
reconstruct a decoded copy of the currentdecoded and added to the model to
g

frame. This reconstructed frame is


stored to be used as reference frame for
le

further predictions.
Accelerator requirements
ol
C

Name Block Motion Estimator


Purpose
Block motion est.
u

in PC.
Inputs
ad

Macrotblocks, search areas.


Outputs
Motion vectors.
iln

Functions
Compute motion vectors
Performance
with full search.
m

As fast as possible.
Manufacturing cost
Ta

Hundreds of dollars.
Power
From PC power supply.
Physical size/weight
PCI card.
Fig. 8.10.1 shows an architecture
for
the motion estimation accelerator.
e The machine consists of two memory
. :Macroblock memory
It has 16 PEs that perform and search memory.
the difference calculation on a
comparator sums them up and selects pair of pixels;
the best value to find the motion vector. the
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 338 of 446

Embedded Systems and loT Desian 8- 43 Processes and Operating Systems

Address generator

Macroblock Search area

g
in
Network Network

er
Network
control

e
in
|PE15 PEO

ng
fE
Comparator
O
e

Motion vector
g
le

Fig. 8.10.1 Architecture for the motion estimation accelerator


ol

you want
Depending on the number of different motion estimation algorithms that
C

to execute on the machine, the networks connecting the memories to the PEs may
also be simplified.
u
ad

Review Question
iln

concepts in the design of video accelerator.


1. Write in detail about the embedded
AUDec-16; Mrks 8
m
Ta

PUBLICATIONSo - an up-thrust for knowledge


TECHNICAL
<br>

Page 339 of 446

UNIT II: PROCESSES AND OPERATING SYSTEMS

Two MARKS QUESTIONS WITH ANSWERS

g
Q.1 Specify the MPEG layer 1
data frame format set for the audio player

in
application.

er
Ans. : • Lossless compression of subbands + Optional simple masking model.

e
384 samples/block at all frequencies.

in
Optional masking model. Drivern by separate FFT for better accuracy.

ng
Header CRC
Bit Scale |Subband Samples Aux.
allocation factors data
Fig. 8.1 MPEG layer 1
fE
data frame format
O
Bit allocation codes specify word length in each subband. Scale factors give
gain for each band.
e

Q.2 List the advantages of software modem.


g

:
Ans.
le

a. It can be easily upgradable of newer


modem.
ol

b. It is less cost and less weight.


C

c. Low power consumption.


d. It can be programmed.
u
ad

Q.3 What is a set-top-box ?


Ans. : Set top box
is a device
or satellite with a consumer used to interface a video delivery service such as
iln

television. Set top boxes for cable


on analog circuit cable TV is traditionally based
for television signal a small amount
functionality provided by a microcontroller. with
m

of user interface
Ta

Q.4 Define software modem.


Ans. : A software modem or
soft modem is a modem
capacities designed to use a with minimal hardware
host computer's resourcesto perform most of
performed by dedicated hardware a the tasks
in traditional modem.
Q.5 List out the advantages
of set-top-box?
:
Ans.
1. Video quality is very good.
2. Audio quality is also very
good.
-
(8 44)
<br>

Page 340 of 446

Embedded Systems and loT Design


8-45 UNIT II
3. Set top box are
provided in standard quality
4. Number of
picture, high definition picture.
channeis increases to a great
extent.
5. Allsorts
of disturbances will be lessened.
0.6 What do you mean by co-design
?
Ans : The simultaneous
design of hardware and software to meet system
objectives.

g
Q.7 What is meant the by processing

in
element ?
Ans. : Processing element is a
unit which is responsible for performing computation. It

er
may be programmable or not.
Accelerator is one kind of processing element.

e
Q,8 Define distributed embedded systems.

in
Ans. : In a distributed embedded system several processing elements are connected by

ng
a network
that allows communicating. More than one computer or group of computers
and PEs are connected via a network that forms distributed embedded systems.
fE
Q.9 What are the merits of embedded distributed architecture ?
O
: :
Ans. Merits
more cost-effective.
a. It is
e

can be
b. Distributed system with several CPUs is that one part of the system
g

part.
le

used to help diagnose problems in another


ol

C. Sharing of
resources.
in the design of embedded systems ?
C

Q.10 What is the role played by the accelerator


to quickly execute certain key functions.
Ans. : An accelerator is attached to CPU buses
u

It
performance for many applications with computational kernels.
If provides large
ad

low-latency I/0 furnctions.


Provides critical speedups for
embedded architecture
iln

Q.11 What is a distributed


architecture several processing elements are
Ans, : In a distributed embedded one computer or group
m

communicating. More than


Connected by a network that allows a network that forms distributed embedded
Ta

are connected via


computers and PEs
architecture.
Q.12 What is an accelerator ?
important category of processing element for embedded
Ans. : An accelerator is
one execute certain key functions. It
to CPU buses to quickly
multiprocessors. It is attached many applications
with computational kernels. It
for
provides large performance low-latency I/O functions.
for
speedups
provides critical

PUBLICATIONS® an up-thrust for knowledge


TECHNICAL
<br>

Page 34 l of 446

UNIT IV
nosoavwee

9 IoT Architecture and Protocols

g
in
er
Syllabus

e
in
Internet - of -- Things - Physical Design, Logical Design - loT Enabling Technologies - Domain

ng
Specific loTs IoT and M2M- loT System Management
with NETCONF - YANG - loT Platform
Design - Methodology - loT Reference Model - Domain Model -
Communication Model - IoT
Reference Architecture - loTProtocols - MQTT, XMPP, Modbus, CANBUS
fE and BACNet.

Contents
O
9.1 Introduction of Internet- of - Things
e

9.2 Physical Design


g
le

9.3 Logical Design


ol

9.4 loTEnabling Technologies


9.5 Domain Specific loTs
C

9.6 loT and M2M


u

3.7 loT System Management with NETCONF- YANG


ad

9.8 loTPlatform Design Methodology


iln

9.9 loT Reference Model


9.10 loT Protocols
m
Ta

(9- 1)
<br>

Page 342 of 446

Embedded Systems and loT Design 9-2 loT Architecture and Protocols

9.1 Introduction of Internet -


of - Things
. The Internet of Things (loT) refers to the capability of everyday devices to connect
to other devices and people through the existing Internet infrastructure. Devices
connect and communicate in many ways.
Examples of this are smartphones that interact with other smartphones,

g
vehicle-to-vehicle communication, connected video cameras, and connected medical

in
devices.

er
They are able to communicate with consumers, collect and transmit data to
companies, and compile large amounts of data for third parties.

e
Things are objects of the physical world (physical things) or of the information

in
world (virtual world) which are capable of being identified and integrated into

ng
communication networks. Things have associated information, which can be static
and dynamic.
fE
Physical things exist in the physical world and are capable
of being sensed,
actuated and connected. Examples of physical things include
O
the surrOunding
environment, industrial robots, goods and electrical equipment.
Virtual things exist in the information world
e

and are capable of being stored,


processed and accessed. Examples of virtual things
g

include multimedia content


and application software.
le

• A device is a piece of
equipment with the mandatory capabilities
ol

communication and optional capabilities of


of sensing, actuation, data capture,
storage and data processing data
C

The devices collect various kinds


of information and provide it to
u

and communication networks for the information


further processing. Some devices
ad

operations based on information also execute


communication networks. received from the information and
iln

Fig. 9.1.1 shows evolutionary


phase of internet.
m

Internet of things
Ta

Immersive (Digitize the


Connectivity Networked world)
economy experiences
Business(Digitize (Digitize (Digitize Connecting:
and access) business) interaction) • People
societal
impact•Email •E- commerce •Social •Process
Web
•Digital supply •Mobility • Data
browser chain •Cloud •Things
Intelligent connection
Fig. 9.1.1 Evolutionary
phase of internet
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 343 of 446

Enbeddecd Systems and loT Design


9-3 loT Architecture and Protocols

Evolutionary phase of internet is Connectivity, Networked


Economy, Immersive
Experiences and IoT.
1, Connectivity : In the phase, peoples are
connected to email, web services and
searches the information.
2 Networked Economy :
This phase support e-commerce and supply chan
enhancements along with collaborative engagement to drive increased
efficiency in business processes.

g
in
3. Immersive Experiences: This phase extended the Internet experience to
encompass widespread video and social media while always being connected

er
through mobility.

e
4. Internet of Things : It adds connectivity to objects and machines in the world

in
around us to enable new services and experiences.

ng
9.1.1 Definition of loT

fE
The Internet of Things (IoT) is the network of physical objects i.e. devices, vehicles,
buildings and other items embedded with electronics, software, sensors, and
network connectivity that enables these objects to collect and exchange data.
O
Wikipedia definition : The Internet of Things, also called The Internet of Objects,
e

refers to a wireless network between objects, usually the network will be wireless
g

and self-configuring, such as household appliances.


le

a wide
WSIS 2005 Definition By embedding short-range mobile transceivers into
:

array of additional gadgets and everyday items, enabling new forms of


ol

communication between people and things, and between things.


C

• The Internet of Things refers to the capability of everyday devices


to connect to
u

other devices and people through the existing


Internet infrastructure.
ad
iln

Anytime
Transportation
any context
m

Anything Anyone
any device anybody Robots and
Ta

Healthcare
and hospitals Internet drones
Internet of
of Things
Things
Connected
JAny service home and
Smart
Any place any phones
offices
anywhere business

Any path
any network

PUBLICATIONS an up-thrust for knowledge


TECHNICAL
<br>

Page 344 of 446

Embedded Systems and loT Design 9-4 loT Architecture and Protocols

Devices connect and communicate in many ways. Examples of this are smart
phones that interact with other smart phones, vehicle-to-vehicle communication,
connected video cameras, and connected medical devices. They are able to
communicate with consumers, collect and transmit data to companies,
and compile
large amnounts of data for third parties.
• IoT data differs from traditional computing. The data can be
small in size and

g
frequent in transmission. The number of devices, or nodes, that are
connecting to

in
the network are also greater in loT than in traditional PC computing.

er
Machine-to-Machine communications and intelligence drawn from
the devices and
the network will allow businesses to automate certain basic

e
tasks without
depending on central or cloud based applications and services.

in
loT impacts every business. Mobile and the Internet of Things

ng
will change the
types of devices tha connect into a company's systems.
These newly connected
devices will produce new types of data. fE
The Internet of Things will help a business
gain efficiency, harness intelligence
from a wide range of equipment, improve
O
operations and increase customer
satisfaction.
e

Ubiquitous computing, pervasive computing


Internet Protocol, sensing
g

technologies, communication technologies,


and embedded devices are merged
le

together in order to form a system where


the real and digital worlds meet and are
continuously in symbiotic interaction.
ol

The smart object is the building


C

block of the IoT vision. By


into everyday objects, they are turned putting intelligence
into smart objects able not only to collect
information from the environment
u

and interact /control the physical world,


also to be interconnected, to each but
ad

other, through Internet to exchange


information. data and
The expected huge number of
iln

interconnected devices and


of available data open new opportunities the significant amount
to create services that
benefits to the society, environment, economy will bring tangible
m

and individual citizens.


However, the IoT is still maturing,
Ta

in particular due to a number of


limit the full exploitation of the factors, which
loT. Some of the factors are
1. There is no
unique identification number system listed below:
2. IoT uses Architecture for object in the world.
Reference Model (ARM)
development in ARM. but there is no further
3. Missing large-scale testing
and learning environments.
4. Difficulties in exchanging
of sensor information
environments. in heterogeneous
K
Difficulties in developing business
which embraces the full support of
Internet of Things. the

TECHNICAL PUBLICATIONS - an
up-thrust for khowledge
<br>

Page 345 of 446

Embedded Systems and loT Design 9-5 loT Architecture and Protocols

9.12 loT Characteristics


Interconnectivity : Everything can be connected global information and
1.
to. the
communication infrastructure.
. Heterogeneity Devices within loT have different hardware and use different
:

networks but they can still interact with other devices through different networks.

g
3. Things-related services : Provides things-related services within the constraints of

in
things, such as privacy and semantic consistency between physical and virtual

er
thing.
4. Dynamic changes : The state of a device can change dynamically, thus the

e
number of devices can vary.

in
Integrated into information network IoT devices are integrated with information
:

ng
5.

network for communication purpose. It will exchange data with other devices.
6. fE
Self-adapting : Self-Adaptive is a system that can automatically modify itself in the
face of a changing context, to best answer a set of requirements.
O
service
7. Self-configuration primarily consists of the actions of neighbour and
resource provisioning.
discovery, network organization, and
g e

9.1:3 Component of loT


le

a rernote dashboard,
hardware utilized in IoT systems includes devices for
ol

• The
or bridge device, and sersors. These devices
devices for control, servers, routing
a
C

specificaiions.
manage key tasks and functions such as system activation, action
to support-specific goals and actions.
Security, communication, and detection
u

are as follows :
ad

Major components of loT devices


a single integrated circuit containing
L.
Control units
:
A small computer on
It is responsible for
iln

core, memory and a programmable l/O peripheral.


Processor
the main operation.
m

a
a physical quantity and convert it into signal,
2. Sensor : Devices that can measure devices
These
Ta

Which can be read and interpreted


by the microcontroller unit.
energy modules, power marnagement modules, RF modules, and sensing
cOnsist of
sensors into 2 categories : Digital or analog. An analog data is
nodules. Most fall
can be transmitted to the Internet.
sOnverted to digital value that
accelerometers
a.
Temperature sensors :
b. Image sensors :gyroscopes
sensors
Light sensors : acoustic
sensors
Micro flow sensors humidity
:
d

Gas RFID sensors


: pressure sensOrs
PUBLICATIONs an up-thrust for knowledge
TECHNICAL
<br>

Page 346 of 446

Embedded Systems and loT Design loT Architecture and Protocols


9-6

3. Communication modules These are the part of devices and responsible for
:

communication with rest of loT platform. They provide connectivity according to


wireless or wired communication protocol they are designed. The communication
between IoT devices and the Internet is performed in twO ways :
a) There is an Internet-enable intermediate node acting as a gateway;
b) The IoT Device has direct communication with the Internet.

g
• The communication between the main control
unit and the communication module

in
uses serial protocol in most cases.

er
4. Power sources : In small devices the current is
usually. produced by sources like
batteries, thermocouples and solar cells. Mobile
devices are mostly powered by

e
lightweight batteries that can be recharged for longer life

in
duration.
Communication technology and protocol :
loT primarily exploits standard

ng
protocols and networking technologies. However,
the major enabling technologies
and protocols of IoT are RFID, NFC, low-energy
low-energy radio protocols, LTE-A, fE Bluetooth, low-energy wireless,
and WiFi-Direct. These technologies support
the specific networking functionality
needed in an loT system in contrast
O
standard uniform network of common to a
systems.
9.14 Working of loT
g e

Fig 9.1.2 shows working of IoT.


le
ol
C

Users
u
ad

Actuators

Micrccontrollers
iln

Environment
| Interfaces
Things
m

Sensors
Ta

The internet

Web
applications
Data
management & Communication
Data interfaces
repositories
Fig. 9.1.2 Working
of loT
TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>

Page 347 of 446

Embedded |Systems and loT Design


9-7 loT Architecture and Protocols
1. Collectand transmit data : The
device can sense the environment and collect
information related to it and transmit to a
it diferent device or to the Internet.
Actuate device based on triggers : It can be
programmed to actuate other devices
based on conditions set by user.
a Receive information : Device can also receive information
from the network.

g
A.
Commnunication assistance : It provides communication between two
devices of

in
same network or different network.

er
Sensors for various applications are used in different IoT devices as per different
applications such as temperature, power, humidity, proximity, force etc.

e
Gateway takes care of various wireless standard interfaces and hence one gateway

in
can handle multiple technologies and multiple sensors.

ng
The typical wireless technologies used widely are 6LoWPAN, Zigbee, Zwave,
fE
RFID, NFC etc. Gateway interfaces with cloud using backbone wireless or wired
technologies such as WiFi, Mobile, DSL or Fibre.
O
9.1.5 Advantages and Disadvantages
e

Advantages of loT
g

Improved customer engagement and communication.


le

1.

Support for technology optimization


ol

2.

Support wide range of data collection


C

3.

4. Reduced waste
u
ad

Disadvantages of loT
: As all. the household appliances, industrial
1 Loss of privacy and security
iln

many other
sector services like water supply and transport, and
machinery, public a lot of information is available
on it. This
Internet,
m

devices all are connected to the


attack by hackers.
information is prone to
Ta

an IoT system to integrate


2 are concerned about the flexibility of
Flexibility : Many
easily with another or bugs in
a diverse and complex network. Any failure
Complexity : The IoT is power failure can
have serious consequences. Even
O.
will
the software or hardware
cause a lot of inconvenience. international standard of compatibility for
Currently, there is no
4.
Compatibility :
tagging and
monitoring equipment
ie
5. Save time and money•

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 348 of 446

Embedded Systemns and loT Design 9-8 loT Architecture and Protocols

9.1.6 Applications of loT


1. Home : Buildings where people live. It controls home and security systems.
2. Offices : Energy management and security in office buildings; improved
productivity, including for mobile employees.
3. Factories :
Places with repetitive work routines, including hospitals and farms;
operating efficiencies, optimizing equipment use and inventory.

g
4. Vehicles: Vehicles including cars, trucks,

in
ships, aircraft, and trains;
condition-based maintenance, usage-based design, pre-sales analytics

er
5. Cities: Public spaces and infrastructure in urban settings;
adaptive traffic control,

e
smart meters, environmental monitoring, resource management.

in
6. Worksites : It is custom production
environments like mining, oil and gas,

ng
construction; operating efficiencies, predictive maintenance, health
and safety.

e
fE
SEzurity
Ta Fakig
O
Ertetairiert Jthtes and
appaces Emsrgency Environmert
servites Retai
g e

Haattr Facterv
Fing veray Surellance
le

Bus:ness
Transport intsiçenco
Home
ol

Goninunity Smart
ieterirsg
C

tesnet of Thirgs
Door'ae Seheing analyios afd
VIsalisatien tool
u

Uties
ad

Anytime, Anything. Angvasere Inrastuctsre


National Smart
grid
iln

Defense
Rete
montorra
m

c5Taiss
Ta

Fig. 9.1.3

92 Physical Design
Physical Design of loT system
refers to IoT Devices and IoT
Protocols.
921 Things in loT
. IoT devices have unique
identity and they are refer as "things"
perform remote sensing, actuating and monitoring. in loT. Device can
loT devices can exchange data
TECHNICAL PUBLICATIONS® an up-thrust for
knowledge
<br>

Page 349 of 446

Embeddead Systems and loT Design


9-9 loT Architecture and Protocols

between them and process data or send to centralized location


for processing and
storage. Fig. 9.2.1 shows block
diagram of IoT device.

Network Audio/ Video


connectivity Input/ Output
Interface Interface
Central

g
Ethernet RCAvideo
processing unit CAN

in
USB host HDMI

er
AUDIO SPI
Main memory

e
interface

in
Graphics
processing NAND/ NOR Storage interface

ng
unit
DDR MMC UART
SDIO
SD fE
O
Fig. 9.2.1 Block diagram of loT devices
e

• IoT devices provide interface to various wire and wireless devices. Interface
g

includes memory interface, I/O interface for sensors, Internet connectivity


le

interface, storage interface etc.


ol

temperature, light intensity.


Using sensors, IoT collects various information like
C

cloud based storage. Collected


humidity, air pressure. Some application used
to other devices.
information is stored in cloud and transmitted
u

sensors.
Various types of IoT devices are smart clothing Smart watch, wearable
ad

etc. Fig. 9.2.2 shows IoT devices.


LED lights, automobile industry
iln

Agriculture Travel
Personal and pet Energy Everyday
m

monitoring use things


Ta

Telemedicine Internet of Things


and
healthcare Building
he
management
Embedded
mobile
M2M and
wireless sensors Security
Smart homes and cities
Fig. 9.2.2 loT devices

PUBLICATIONs. an up-thrust for knowledge


TECHNICAL
<br>

Page 350 of 446

Embedded Systems and loT Design 9-10 loT Architecture and Protocols

9.2.2 loT Protocol


• Fig. 9.2.3 shows IoT protocols.

Application layer
HTTP

g
COAP DDS XMPP AMQP Websockets MQTT

in
Transport layer

er
TCP UDP

e
in
Network layer

ng
IPv4 IPv6 6LoWPAN

Ethernet Wifi
fE
Link layer
802.15.4 Mobile cellular
O
WiMax
e

Fig. 9.2.3 loT protocol


g
le

1. Link layer
• Link layer protocols decide
ol

how data is sent on physical medium. Link


works within the local area network. layer
Protocol of link layer is explained
C

a. 802.3 Ethernet below :


This protocol is used for wired
u

medium. Ethernet, in its most basic


at 10 Mbit/s. Ethernet version runs
ad

has traditionally been used to


workstations and to transfer non-real-time network enterprise
data.
iln

The Ethernet standard allows


for several different implementations
pair and coaxial cable. The maximum such as twisted
length of an Ethernet is determined
m

nodes' ability to detect collisions. by the


Ta

The worst case occurs


when two nodes at opposite
transmitting simultaneously. ends
Ethernet does not provide any of the bus are
acknowledging received frames, mechanism for
making it what is known as an
medium. unreliable
Carrier sense multiple aCcess
with collision detection (CSMA/CD)
commonly used protocol is the most
for LANs. 10BASE5 is generally
alternative for fiber optic media used as low cost
for use as a backbone segment
building. with in a single

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 35 of 446
1l

EmbeddedSystems and loTr Design


9-11 loT Architecture and Protocols

. 10BASET is 10 MHz Ethernet running over UTP cable. It also uses passive star
topology. The maximum cable segment allowed
is 100 - 150 meters. There is no
minimum distance requirements between
devices, such devices cannot
be

connected serially but in star wired.


Wifi
b. 802.11
Commonly referred to as Wi-Fi the 802.11 standards define a through-the-air

g
interface between a wireless client and a base station access point or between two

in
or more wireless clients.

er
. 802.11a
The 802.11a standard uses the 5 GHz spectrumn and has a maximum
:

e
theoretical 54 Mbps data rate. The 5 GHz spectrum has higher attenuation than

in
lower frequencies, such as 2.4 GHz used in 802.11b/g standards. Products with

ng
802.11a are typically found in larger corporate networks or with wireless Internet
service providers in outdoor backbone networks.
fE
. 802.11b : The 802.11 standard provides a maximum theoretical 11 Mbps data rate
in the 2.4 GHZ Industrial, Scientific and Medical (1SM) band.
O
802.11b uses Complementary Code Keying (CCK) instead of
Differential
Quadrature Phase Shift Keying (DQPSK) used at lower rates.
e

more in the 2.4 GHZ band.


g

802.11g : It provides 20 Mbps and


le

c. 802.16 WiMax
are based on the IEEE 802.16
ol

• WiMAX refers to broadband wireless networks that


interoperability between broadband
standard, which ensures compatibility and
C

wireless access equipment.


2-to-11 GHZ frequency range. The
u

• The 802.16 astandard will support OFDM in the can


ad

1SM band. A single WiMAX tower


802.16b standard will operate in the 5 GHz
square miles.
very large area as big as 3000
provide coverage to a
iln

:
The receiver and antenna could be a small box or Personal
WiMAX receiver a laptop the way WiFi access
built into
m

Computer Memory card or they could be


Ta

is today.
d. 802.15.4
Zigbee nor Bluetooth could not fit some of their needs
Wi-Fi
• In 2002; seeing that neither of industrial companies formed the consortium
a number
for embedded systems providing standards for low cost/low
called ZigBee Alliance, aimed at with the birth of IEEE 802.15.4
communications. Then,
consumption wireless
group.
with a
data rate of up to 250 kbs,
can reach up to 500m,
ZigBee communications 400
W.

consumption of 125 to
for a typical power

PUBLICATIONS - an up-thrust for knowledae


TECHNICAL
<br>

Page 352 of 446

Embedded Systems and loT Design 9-12 loT Architecture


and Protocols

As ZigBee is based on TEEE 802.15.4, there is no wake-up signal, but slots foe
sleep or activity, or in asynchronous mode, devices sleeping anytime they have
nothing to say, with an ever-vigilant co-ordinator.
To use a ZigBee module with a microcontroller, you need to connect it to a UART
There are other, optional pins use, including a number of analog inputs /
to
digital IOs and a PWM output indicating the strength of the signal which you can

g
directiy connect to a LED pin for observation purposes.

in
There are two modes of data transfer namely Beacon mode and Non Beacon mode.

er
• In Beacon mode, when the devices are not
sending the data they may enter a low

e
power state and reduces the power consumption.

in
In Non-beacon mode, the end devices need to be wake up only while sending the

ng
data while the routers and coordinators need to be active most of
the time.
e. Mobile Communication
(2G/3GI4G)
GSM frequencies originally designed on 900
fE
MHz range, now also available on
800 MHz, 1800 MHz and 1900 MHz ranges.
O
The backbone of a GSM network is a
telephone network with additional cellular
network capabilities.
e

4G is also called as Long Term


Evolution. It's promises data transfer rates of
g

100 Mbps.
le

2. Network layer
ol

The network layer is responsible for


the delivery of packets from
the source to
C

destination.
Network layer uses IP address to
choose one host among
u

network layer, datagram needs a millions of host. n


destination IP address for
ad

IP address for a destination delivery and a source


reply.
a. IPv4
iln

IP is used for communicating


all Internet enabled
devices. The transport layer
m

responsible for delivery message


of from one process
The
to another.
network does the host
Ta

to destination delivery
considering it as independent of individual packets
message arrives packet. But transport
intact and in order layer ensures the whole
with error control and process that
An
IP address is a numeric identifier control.
assigned
IP address is a software to
address, not a hardware each machine on an IP network.
the machine or NIC. address, which is hard-coded in
'An IP address is made up of 32 bits
of information.
four parts containing 8 bit each. These bits are divided into

TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>

Page 353 of 446

Embedded Systems and loT Design 9-13 loT Architecture and Protocols

IPv4 addresses are unique. Two devices on the


internet can never have the same
address at thesame time.
.
Packets in the IPv4 layer are called datagrams. A datagram is a variable
length.
b. IPv6
. IPv6 addresses are 128 bits in length. Addresses are assigned to individual

g
interface on nodes, not to the node themselves.

in
A single interface may have multiple unique unicast addresses. The first field of

er
any IPv6 address is the variable length format prefix, which identifies various
categories of addresses.

e
in
c. 6LoWPAN

IPv6 over Low power Wireless Personal Area Network enables IPv6 in low-power

ng
and lossy wireless networks such as' WSNs.
6LoWPAN defines header compression mechanisms. fE
3. Transport layer
O

A transport layer protocol provides for logical communication between application
processes running on different hosts.
e

one process to
The trarnsport layer is responsible for delivery of message from
g

another. The network does the host to destination delivery of individual packets
le

considering it as independent packet.


ol

message arrives intact and in order



But transport layer ensures that the whole
C

with error control and process control.


service to an application even
A transport protocol can offer reliable data transfer
u

even when the network


when the underlying network protocol is unreliable,
ad

packets.
protocol loses, garbles and duplicate
iln

a. TCP (Transmission Control Protocol)


connectionless protocol.
• TCP is the connection oriented protocol whereas UDP is
m

the transport layer.


Both are internet protocols used in
term
reliable, byte stream service. The
Ta

TCP provides a connection-oriented, a


using TCP must establish TCP
connection oriented means the two applications
they can exchange data.
connection with each other before
support multicasting and broadcasting. The application data is
TCP does not The unit of
what TCP considers the best sized chnks to send.
broken into. segment.
IP is called a
information passed by TCP to
a segment it maintains a timer, waiting for the other end to
• When TCP sends
segment. If an acknowledgement isn't received in time,
acknowledge reçeption of
retransmnitted.
the segment is
PUBLICATIONSe.- an up-thrust for knowledge
TECHNICAL
<br>

Page 354 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-14

b. (UDP) User Datagram Protocol


UDP is a simple, datagram-oriented, transport layer protocol. This protocol is used

in place of TCP.
or flow
• UDP is connectionless protocol provides no reliability control mechanisms.
It also has no error recovery procedures.

g
UDP makes use of the port concept to direct the datagrams to the proper

in
upper-layer applications. UDP serves as a simple application interface to the IP.

er
• ÜDP uses port numbers as the addressing mechanism in the transport layer.

e
4. Application layer

in
Application layer is responsible for accessing the network by user. It provides user

ng
interfaces and other supporting services such as e-mail, remote file access, file
transfer, sharing database, message handling (X.400), directory services (X.500).
a. HTTP (Hyper Text
Transport Protocol)
fE
HTTP is an application protocol. HTTP is used to
retrieve Web pages from remote
O
servers.
• HTTP uses the services of TCP. HTTP a
e

is stateless protocol. The client initializes


the transaction by sending a request message.
g

The server replies by sending a


le

response.
HTTP includes commands such as GET,
ol

PUT, POST, HEAD, DELETE, MOVE,


LINK and UNLINK.
C

HTTP messages are two types :


Request and Response.
s
u

URL a standard for specifying any


kind of information on the
ad

uses URL. internet. HTTP


b. CoAP-Constrained Application
Protocol
iln

• CoAP is a specialized
web transfer protocol for use
constrained (e.g., low-power, with constrained nodes and
m

lossy) networks.
CoAP is designed
for simplicity, low
Ta

resource-constrained environments. overhead and multicast


support n
COAP is a web
protocol that runs over
Layer Security (DTLS) the UDP for IoT. Datagram
is used to protect CoAP Transpor.
The protocol
transmission.
is designed for machine-to-machine
energy and building automation. (M2M)
. applications such as smart
COAP provides a
request/ response
endpoints, supports built-in discovery interaction model between applicato
of services
concepts of the Web such as URIs and resources,
and Internet and includes key
media types.

TECHNICAL PUBLICATIONS® - an
up-thrust for
knowledge
<br>

Page 355 of 446

Enbedded Systems and loT Design


9-15 loT Architecture and Protocols

CoAP is designed to easily interface with Web


HTTP for integration with the
while meeting specialized requirements
such as multicast support, very low
overhead, and simplicity for constrained
environments.
Websocket
c.
WebSocket is a communications protocol, providing full-duplex
communication
channels over a single TCP connection. The WebSockets protocol does not run

g
over HTTP, instead it is a separate

in
implementation on top of TCP.
The WebSocket protocol starts by a handshake in order to start the communication

er
and exchange messages formatted as frames.

e
After conrnection is established, messages can be transmitted, either client or server

in
initiated. This means that you can make a dynamic web page where changes occur

ng
in real time.
• In thatway Websockest communication presents a suitable protocol for loT world
fE
where changes are usually asynchronously occurring and number of clients can be
very large.
O
d. MQTT (Message Queue Telemetry Transport)
e

MQTT is Open Connectivity for Mobile, M2M and IoT. MQTT is designed for
g

high latency, low-bandwidth or unreliable networks. The design


principle
le

resource requirements.
minimizes the network bandwidth and device
ol

publish/subscribe messaging protocol


MQTT is a lightweight broker-based
easy to implement.
C

designed to be open, simple, lightweight and


exchanging a series of MQTT control packets in a
The MQTT protocol works by
u

a specific purpose and every bit in the


defined way. Each control packet has
ad

the data transmitted


over the network.
packet is carefully crafted to reduce
server and a MQTT client. MQTT control packet
iln

a
A MQTT topology has MQTT
as possible.
headers are kept as small
m

this protocol appropriate for IoT by


Having a small header overhead makes networks.
transmitted over constrained
Ta

lowering the amount of data


M2M and loT which is used to
provide new and
MQTT is the protocol built for
revolutionary performance.
e. XMPP Presence Protocol)
(Extensible Messaging messages and presence information
T
delivering instant
The XMPP is targeted at
-
XML Based protocol.
S an open and communicating parties typically end
a service, where
Instant messaging (IM) is
one -many tashion in near real - time
one- to-one or -to
users send messages in

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 356 of 446

Embedded Systems and loT Design 9- 16 loT Architecture and Protocols

open technology for real-time communication, which powers


a
• An wide range
of
applications including instant messaging, presence, multi-party chat, voice and
video calls, collaboration, lightweight middleware, content syndication, and
generalized routing of XML data.
XMPP support server-to-server communication and client-to-server communication

g
f. DDS (Data Distribution Service)

in
The first open international middleware standard directly addressing
publish-subscribe communications for real-time and embedded systems.

er
The DDS is an Object Management Group (0MG) standard for Pub/Sub that

e
addresses the needs of mission and business critical applications, such as, financial

in
trading, air traffic control and management, and complex
supervisory and

ng
telemetry systems.
• DDS provides a shared "global
data space" where any application can publish
fE
the data it has & subscribe to the data it needs.
• DDS is highly configurable
by means of QoS settings. Heterogeneous systems can
O
be easily accommodated.
g. AMQP (Advanced
e

Message Queuing Protocol)


g

A protocol to communicate between clients


and messaging middleware servers
le

(brokers). The Broker is the AMQP Server.


AMQP supports both publish-subscribe
ol

model and point-to-point communication,


routing and queuing
C

AMOP divides the brokering


task between exchanges
the first is a router that accepts and message queues, where
u

incoming messages and


route the messages to, decides queues to
ad

and the message queue stores messages which


message consumers. and sends them to
iln

AMQP supports username


and password authentication as
authorization. It also supports well as SASL
m

TLS encryption.

9.3 Logical Design


Ta

It is an abstract
representation of an
low level implementation. entities and processes
but it can not speay
9.3.1 loT Functional Blocks
• The Functional Model (FM)
Functional
is derived from
internal and
view is derived from external requirements.
the Functional Model
high-level requirements. in conjunction with

TECHNICAL PUBLICATIONS8
- an up-thrust
for knowledge
<br>

Page 357 of 446

Embedded Systems and loT Desian 9- 17 loT Architecture and Protocols

. IoT Functional model identifies Functional Groups (FGs) that is, groups of
functionalities, grounded in key concepts of the IoT Domain Model.
Functional Model is an abstract framework for understanding the main
Functionality Groups (FG) and their interactions. This framework defines the
common semantics of the main functionalities and will be used for the
development of loT-A compliant Functional Views.

g
in
The functional model is not directly tied to a certain technology, application
domain, or implementation. It does not explain what the different Functional

er
Components are that make up a certain Functionality Group.

e
Fig. 9.3.1 shows loT functional model.

in
ng
User applicaton

Service
organisaticn
loT
process
management entty
fE
Virtual IoT
service
O

Secunty
e

Management
g
le
ol

Communication
C

Hardware device
u

Fig. 9.3.1 loT functional model


ad

are generated by
loT Service, and Device FGs
iln

The Application, Virtual Entity,


Service and Device classes from
starting from the User, Virtual Entity, Resource,
m

the IoT Domain Model.


the
the possible functionality hosted by
Ta

Device functional group contains all


sensing, actuation, processing,
physical devices. Device functionality includes on the
components, the sophistication of which depends
storage, and identification
device capabilities.
the communication used by devices.
Communication functional group supPort all
technology.
It uses wired and wireless
such as directory services, which
• loT Service functional group Support functions
:
resources.
discovery of Services and resolution to
allow

PUBLICATIONS an up-thrust for knowledge


TECHNICAL
<br>

Page 358 of 446

loT Architecture Gnd Protocols


Embedded Systems and loT Design 9-18

: It is related to the Virtual Entity class in dthe lo]


group
Virtual Entity functional
Entities can be static or
Domain Model. Associations between Virtual to the corresponding
dependingon mobility of the Physical Entities related
the
Virtual Entities.
components h.
• IoT Service Organization functional group To host all functional
:

services.
support the composition and orchestration of loT and Virtual Entity

g
Finally, the "Management" transversal FG is required for the management
of

in
and/or interaction between the functionality groups.

er
The loT Process Management FG relates to the conceptual integration of (business)

e
process management systems with the loT ARM.

in
• The Service Organisation FG is a central Functionality Group that acts as a

ng
communication hub between several other Functionality Groups.
The Virtual Entity and IoT Service FGs include functions that relate to interactions
fE
on the Virtual Entity and IoT Service abstraction levels, respectively.
• The Virtual Entity FG contains functions for interacting
with the IoT System on
O
as as
the basis of VEs, well functionalities for discovering and looking up Services
that can provide information about VEs or which allow the interaction with VEs.
g e

Communication FG provides a simple interface for instantiating


and for marnaging
le

high-level information flow. It can be customized according to


the different
requirements defined in the Unified Requirements list.
ol

The Management FG combines all functionalities


that are needed to govern an lo1
C

system. The need for management can


be traced back to at least four high-level
system goals : Cost reduction; Attending
u

unexpected usage issues; Fault handing


and
ad

Flexibility.
The Security Functionality Group
is responsible for ensuring
a
iln

privacy of IoT-A-compliant systems. the security


registration of a client to
It is in charge of handling the initial
the system in a secure manner.
m

legitimate clients may access This ensures that oy


services provided by the
IoT infrastructure.
Ta

9.3.2 loT Communication Model


Request IResponse model :
• In the Request/Response Client
Server
model,
client requests information from the HTTP GET
server and waits till
the response is
served from the server. Fig. 9.3.2
shows Request/Response model. HTTP 200 OK
(content)
Fig. 9.3.2
Request I Response model

TECHNICAL PUBLICATIONS®
- an up-thrust
for knowledge
<br>

Page 359 of 446

Enbedded Systems and loT Design


9-19
loT Architecture and Protocols
HTTP protocol
is used by Request/Response model.
may request a web page For example, a browser client
from the server
corresponding web
page will be through a "Request" and the
served
the server as a "Response".
by
. The client and the server
can communicate
requests. one to one,
Or one to many with more
This model is
stateless communication
model and each request-response

g
independent of others. pair 13

in
Publish / Subscribe model :
.

er
Publishers : Publishers generate
event data and publishes
Subscribers : Subscribers them.

e
submit their subscriptions
and process the events

in
received
. Publish/Subscribe

ng
service :
It's the mediator/broker that filters
from publishers to interested subscribers. and routes events
. Fig. 9.3.3 shows Publish/Subscribe model.
fE
O
Consumer
Sage
Message
g e

Broker
le

Message Message
Producer Topic
ol

Consumer
C

Message
Conisumer
u
ad

Fig. 9.3.3 Publish l Subscribe model


iln

• The publishers and subscribers are autonomous, which means that they do not
need to know the presence of each other.
m

• This model is highly suited for mobile applications, ubiquitous computing and
Ta

distributed embedded systems.


down the entire system.
Failure of publishers or subscribers does not bring
• No strong guarantee on broker to deliver content to subscriber. After a publisher
corresponding subscribers would receive it
Publishes the event, it assumes that all
and publishers overload them.
Potential bottleneck in brokers when subscribers
Push Pull model:
queues and consumers pull the data from the
Data
procedure push the data to model.
queues. 9.3.4 shows
push-pull
ig.
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 360 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9- 20

Queue 1 Consumer A
Publisher
Consumer B
Queue 2.

Consumer C

g
Fig. 9.3.4 Push-Pull model

in
er
• Sometimes queue act as buffer in between producer and consumer. Producer does
not need to be aware of the consumers.

e
in
Exclusive pair model :
This communication model is full duplex, bi-directional communication model. I

ng
uses persistent connection between client and server. Fig. 9.3.5 shows exclusive
pair model. fE
Request for connection
O
Response (ACK)
g e

Client Data
Server
le

Data + ACK
ol

Request for closing connection


C

Response for closing connection


u

Fig. 9.3.5 Exclusive


pair model
. Client
ad

send request to server for opening the


connection. This connection is open
till the client send request for closing
the connection.
iln

9.3.3 loT Communication APIl's


m

1. REST based communication API :


Ta

A large part of the interoperability,


scale, and control for IoT can
through API management. Standards-based be achieved
management, and a RESTful design patterns for Web
architecture provide APs, API
the task of interoperability across tremendous value in simplifying
heterogeneous systems handling
data. vast amounts of
Representational State Transfer (REST)
APIs follow the request-response
communication model.
Applications conforming to
the KESTconstraints can
systems typically communicate over HTTP be called RESTAul. RESTul
with the same
Methods (GET, POST,
TECHNICAL PUBLICATIONS® - an up-thrust
for knowledge
<br>

Page 36l of 446

Embedded Systems and loT Design


9-21 loT Architecture and Protocols
pUT, DELETE etc) that
browsers use to retrieve web pages
remote servers. and to send 'data to
1
Client-Server: Requires that a
services wait for clients to servic offer one or more operations and tnat
request these operations.
2. Stateless : Requires communication
between service consumer (client)
service provider (server) to be stateless. and

g
3. Cache : Requires responses to be clearly labeled as
cacheable or non-cacheable.

in
4. Uniform Interface : Requires all service providers-
and consumers within a
REST-comnpliant architecture to

er
share a single common interface for all
operations.

e
5. Layered System : Requires the ability to add or remove intermediaries at

in
runtime without disrupting the system.

ng
6. Code-on-Demand : Allows logic within clients (such as Web browsers) to be
updated independently from server-side logic using executable code shipped
from service providers to consumers. fE
Each client request and server response is a message and REST-compliant
O
applications expect each message to be self-descriptive. That means each message
must contain all the information necessary to complete the task. Other ways to
e

describe this kind of message are "stateless" or "context-free." Each message passed
g

between client and server can have a body and metadata.


le

:
HTTP request methods and actions
ol

1. GET : Return whatever information is identified by the Request-URI.


C

2. HEAD : Identical to GET except that the server must not return
a
message-body in the response, only the metadata.
u

3. OPTIONS : Return information about the communication options available


on
ad

the Request-URI.
the request/response chain identified by
be stored under the supplied
4. PUT: Requests that the enclosed entity
iln

Request-URI.
m

5. enclosed in the request


POST: Requests that the origin server accept the entityRequest-URI.
resource identified by the
as a new subordinate of the
Ta

server delete the resource identified by the


6. DELETE : Requests that the origin
Request-URI.
last three are write operations.
The first three are read-only operations, while the
WebSocket based communication API
communication between client and
WebSocket support full-duplex, twO-way
Server.
netwwork traffic and latency as there is no overhead for
reduce the
WebSocket APls
requests tor each message.
Connection setup and termination
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 362 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9- 22

sequence to establish a
WebSocket uses a standard HTTP request-response a
connection. When the connection is established, the WebSocket API provides
over the established
read and write interface for reading .and writing data
marnner.
connection in an asynchronous full duplex
WebSocket also provides an interface for asynchronously closing the connection
from either side.

g
in
9.4 loT Enabling Technologies

er
• IoT is enabled by several technologies including wireless sensor networks, cloud
computing, Big data analytics, Embedded Systems, Security Protocols and

e
in
architectures, communication protocols, web services, Mobile Internet, and
Semantic Search engines.

ng
9.4.1 Cloud Computing
fE
Cloud computing has the almost unlimited capacity of storage and processing
power which is a more mature technology at least to a certain extent to solve the
O
problem of most of the Internet of things.
Cloud computing is a pay-per-use model for enabling available, convenient,
e

on-demand network access to a shared pool of configurable computing resources


g

(e.g., networks, servers, storage, applications, services) that can


le

be rapidly
provisioned and released with minimal management effort or
service-provider
ol

interaction.
C

Cloud storage services may be accessed through a web


service API, a cloud
storage gateway or through a web-based user interface.
u

• Cloud computing services are


offered to users in different forms : Infrastructure
ad

as-a-Service (laaS), Platform-as-a-Service (PaaS)


and Software-as-a-Service (SaaS).
Software as a Service (SaaS) : Model
iln

in which an application is hosted as a


service to customers who access
it via the Internet. The provider does all
the
m

patching and upgrades as well as


keeping the infrastructure running. The
traditional model of software distribution,
Ta

in which software is purchased for and


installed on personal computers.
Platform as a Service (PaaS) : Platform as a
model and also known as cloud-ware. service is another application delivery
Supplies all the resources
applications and services completely reguired to build
download or install software. Services from the Internet, without having to
includes application design, development,
testing, deployment, and hostng, team
. collaboration,
database integration, security, scalability, storage, web service integration,
versioning. PaaS is closely related to SaaS but delivers statea
management, and
work rather than an application to work with. platform from which to
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 363 of 446

Embedded Systems and loTDesian


9-23 loT Architecture and Protocols

Infrastructure as a Service (IaaS) :


SaaS and PaaS are providing apples to
customers, laaS doesn't. It offers
the hardware so that your organization can
whatever they want onto it. Rather than purchase servers, put
software, racks, and
having to pay for the datacenter space for them,
the service provider rents for
resources like server space,
network equipment, memory etc.

g
9.4.2 Big Data Analytic

in
er
• A category of technologies and services where the capabilities
provided to collect,
store, search, share, analyze and visualize data which have the

e
characteristics of

in
high-volume, high-velocity and high-variety.

ng
Examples of big data generated by IoT systems :
a) Weather monitoring stations
b) Machine sensor data from industrial systems fE
c) Health and fitness data
O
d) Location and tracking systems
g e

Data Data Data Data


processing analysis
le

collection execution
ol

Fig. 9.4.1
C

9.4:3 Wireless Sensor Networks


u

a large number of
• A Wireless Sensor Network (WSN) is a network formed by
ad

sensor nodes where each node is equipped with a sensor to detect physical
phenomena such as light, heat, pressure, etc.
iln

• WSNs nowadavs usually include sensor nodes, actuator nodes, gateways and
inside of or near the
m

clients. A large number of sensor nodes deployed randomly


self-organization.
monitoring area, form networks through
Ta

to transmit along to other sensor nodes by


Sensor nodes monitor the collected data
monitored data may be handled by
hopping. During the process of transmission,
node after multi-hop routing, and finally reach
multiple nodes to get to gateway
or satellite.
management node through the internet
e
Standards for WSN technology have been
well developed, such
as
Zigbee (EEE
lightweight wireless
802.15.4). TheJEEE 802.15.4 is simple packet data protocol for
networks.
controllers, sernsors, remote
lt works long battery life, selectable latency tor
well for

monitoring and portable electronics.

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 364 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-24

9.4.4 Communication Protocols


Communication protocols are used
as a backbone of loT systems. It enable
network connectivity and coupling to applications. Communication protocols
allow devices to exchange data over the network.
Communication protocol also performs error correction and detection, flow control.

g
data encoding, addressing mechanism etc.

in
Sequence control, lost of packet, retransmission are the other functions of

er
communication protocol.

e
9.4.5 Embedded System

in
• A system is a set of interacting or interdependent component parts forming a

ng
complex unit. It is a fixed plan to perform, one or many task.
fE
• Embedded system is an electronic system which is designed to
perform one or a
limited set of functions using software and hardware.
O
General definition of embedded systems is : Embedded systems are
computing
systems with tightly coupled hardware and software integration that are designed
e

to perform a dedicated function. The word embedded reflects


the fact that these
g

systems are usually an integral part of a larger system,


known as the embedding
le

system. Multiple embedded systems can coexist


in an embedding system.
ol

• An embedded system has three main components:


Hardware, Software and time
C

operating system.
Hardware parts includes power supply, processor, memory,
u

communication ports, system application specific times &


circuit etc.
ad

Software parts includes the application


software is required to perform the series
of tasks. An embedded system has
iln

software designed to keep in view


of three
constraints :
m

a. Availability of system memory


b. Availability of processor speed
Ta

c. The
need to limit power dissipation
when unning the system continuously
cycles of wait for events, run , stop
. Demand for and wake up.
low cost and higher density platform
devices. As integration levels requires the integration o
increases, more and more logic
processor die, creating is added to tne
families of applications specific
service processors.
System-on-Chip (SoC) designs increasingly become
of moderm electronics systems. A the driving force of a number
number of key technologies integrate
forming the highly complex embedded platform. together

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 365 of 446

Embedded Systems and loT


Desian
9-25 loT Architecture and Protocols

C46 Unmanned Aerial Vehicle


IÜnmanned Aerial Vehicle (UAV), popularly known as Drone, is an airborne
system or an aircraft operated remotely by a human operator or autonomously by
an onboard computer.

g
An Unmanned Aerial System has three components :

in
1. An autonomous or human-operated control system which is usually on the
ground or a ship but may be on another airborne platform;

e er
2. An Unmanned Aerial Vehicle (UAV);

in
3. Acommand and control (C2) system sometimes referred to as

ng
communication, command and control (C3) system - to link the two.
• UAVS. Fig. 9.4.2 shows UAV.
fE
Datalink Avionics
O
Gimball control
g e
le

Flight control
systems
ol
C

Imaging
u
ad

Radar
iln

vehicle block diagram


Fig. 9.4.2 Unmanned aerial
m

new addition to the North Eastern


UAV based Remote Sensing (UAV-RS) is the
(NE-SAC) tor large-scale mapping and real time
Ta

Space Applications Centre


applications.
assessment and monitoring activities of various
Nishant is a multi-mission Unmanned Aerial Vehicle with
day/night capability
reconnaissance, target tracking & localizaion
used for battlefield surveillance and
mage processing system is used for
and artillery fire correction. A sophisticated
analyzing the images transmitted from
the UAV. It is launched using a Mobile
Hydro pneumatic Launcher.

PUBLICA TIONs® - an up-thrust for knowledge


TECHNICAL
<br>

Page 366 of 446

9-26
loT Architecture and Protocols
Embedded Systems and loT Design


UAVs are now capable of carrying out remote sensing, remote monitoring, courier
delivery and a lot more. UAV networks are many times used for unmanno!
missions. There have been many attacks on civilian, military, and industrial targets
that were carried out using remotely controlled or automated.
UAVS can be categorized into fixed wing, multi-rotor, flapping and vertical flier
kinds. Recently, many challenging tasks have been carried out using UAVs such as

g
patrolling, border surveillance and wildfire monitoring.

in
In the civilian sector, UAVs are currently used as toys, hobby aircraft, and

er
research flight platforms. They have been employed in such tasks as airport

e
wildlife control and population monitoring and are expected to contribute to

in
autonomous crop surveying, atmospheric weather monitoring and search and
rescue missions.

ng
9.5 Domain Specific loTs
fE
Nowadays, Internet of Things plays a vital role in industry, policy and engineering
O
circles. IoT system is contained in a large number of networked products, systems
and sensors. The revolution of IoT creates new market opportunities and business
e

models by considering the security, privacy and technical interoperability aspects.


g

• IoT - enabled products like smart


le

appliances, smart vending machine, smart


lighting and smart payments system' offer more
security, privacy and energy
ol

efficiency to the user. There are vast numbers of IoT


applications including home
C

automation, environment monitoring, healthcare


applications, wearable devices
which are available.
u
ad

9.5:1 Inventory Management in Retail


Retail involves the sale of goods
iln

from a single point (malls, markets,


stores etc) directly to the consumer department
in small quantities for his end use.
m

Retail is a challenging business


but the pressures of todav's economic
Ta

are resulting even more condition


in selective consumer shopping
The effect of internet of things on and spending.
inventory management is
progress when it comes to Business the next huge thing
Process Management
(BPM).

In any typical business, the process of
ordering, storing,
good is a day to day requirement. As tracking and managing
with all high
this process becomes more complex investment top-tier businesses,
with increasing
demand. amount of supply and

TECHNICAL PUBLICATIONS®
- an
up-thrust for knowledge
<br>

Page 367 of 446

Embedded Systems and loT Design


9-27 *
loT Architecture and Protocols
This process involves huge
transaction of monetary
impervious that a high preference resources and hence it is

is given to this in a BPM. Inventories that are


mismanaged can create significarnt
financial problems for a business, leading to a
inventory shortage.
Existing technologies such as bar coding
and Radio-Frequency IDentification
(RFID) already let retailers monitor
their inventories.

g
IoT will enable this to be taken to the next level

in
with significantly more data
coming in the monitoring systems and products moving through the chain.supply

er
. This can
considerably improve supply chain efficiencies and enable leaner

e
as
inventories. Large retailers such Walmart are already using loT for supply chain

in
and inventory management.

ng
Tracking is done using RFID readers attached to the retail store shelves

9.5.2 Smart Payments in Retail


fE
(NFC) and Bluetooth
O
Smart payment system uses Near Field Communication
communication.
e

is a standards-based wireless
Near Field Communication (NFC) technology
g

to exchanged between devices that


communication technology that allows data be
le

are a few centimeters apart.


ol

transfers data at up to 424 kbits/second.


• NFCoperates at 13.56 MHz and
C

allows
functionality in many mobile phones and
• NFC is available as standard content, and
transactions, access digital
u

consumers to perform safe contactless


ad

connect electronic devices simply. enabling.


a mobile device can act
as a card or a reader or both,
An NFC chip in make secure payments quickly.
iln

share information and to


consumer devices to or
payments can be made using a simple tap
m

applications,
Using smart phone
the proximity.
waving the card within
Ta

an NFC
payment option into smart phones using
can integrate and
Service providers pay, Google wallet (Android pay)
the device. Apple smart phone payment systems.
tag embedded inside among
are most popular
Samsung pay the possible using
NFC technology like Android
are
Data transfer using
smart device photos,
resumes and business cards by just
can share
documents,
beam. Two users
phone.
waving their smart

PUBLICATIONS® - an up-thrust for knowledge


TECHNICAL
<br>

Page 368 of 446

Embedded Systems and loT Design 9-28 loT Architecture and Protocols

9.5.3 Smart Vending Machine


Smart vending is about building remote management systems and telemetry tools,
which integrate monitoring, transmission and delivery of operational data rom
each vending machine via the Internet.
Smart vernding solution offers its customer's flexibl payment options and monitors

g
the machines remotely and in real time.

in
Smart phone applications that communicate with smart vending machine allow

er
user preferences to be remembered and learned with time.

e
For instance, Innovations like RFID based "smart" shelves continuously scan items

in
on the shelf and notifies the appropriate systems. During low or out of stock
situations they create automatic replenishment alerts and send automatic orders

ng
directly to central warehouse and to manufacturers.
• Smart vending machine provided following : fE
1. Achieve high levels of efficiency in the management of their assets.
2. Offers its customer's flexible payment options: RFID/NFC
Card; - Mobile
O
-
Payments; Smartphone payments; Cash; Debit and Credit Card.
e

3. Monitor the machines remotely arnd in real


time.
g

4. Simplifies business since the vending machines


contain multiple sensors that
le

alert the owners about their location, the state inventory


and eventual
maintenance issues.
ol
C

9.5.4 Route Generation and Scheduling in Logistics


Modern transportation system collects data from
u

sources. Collected data is processed various places and multiple


ad

and decision is taken according to this. This


information is also provided to stakeholders.
.
iln

Data driven transportation system is


provided by using this data.
Route generation and scheduling system can
m

generate end to end routes


combination of route patterrns and transportation using
modes.
Ta

Cities around the world face common


transport challenges from increasing
congestion, safety concerns and aging
infrastructure to a lack of funding
increasing environmental impacts. Like and
government, transport officials are their colleagues in city admninistration
and
starting to implement "smart
address these challenges and provide solutions" to
improved mobility in their cities, better
services for citizens and a more cost-effective
. transport network.
Vehicle networking
Utilizing the new technologies,
communication, positioning and such as wireless
oonnections between vehicle to navigation, context awareness, to implemernt the
vehicle, vehicle to man, vehicle
to infrastructure, so
that the integrated service can be provided.
TECHNICAL PUBLICATIONS - an
up-thrust for knowlodge
<br>

Page 369 of 446

Emboddad Systems and | loT Design


9-29 loT.Architecture and Protocols

. The Internet of Vehicles (IoV) an integration of


is three networks : an inter-vehicle
network, an intra-vehicle network, and vehicular
mobile Internet.
The application of loT technology in providing
information services, improvin8
traffic efficiency, enhancing traffic safety,
implementing supervision and controt
and other aspects will make millions of people enjov more comfortable, convenient
and safe traffic service.

g
in
955 Fleet Tracking in Logistics

er
• It is automated vehicle routing and scheduling. It supports driver compliance,

e
safety and performance reporting.

in
Vehicle fleet tracking systemn uses GPS technology to track the location of the

ng
vehicle in the real time.
Fleet maintenance and fuel conservation capabilities. Track, schedule and route
fE
vehicles in real time.
Proactively manage fleet maintenance and fuel economy. It is also possible to
O

monitor driver behavior and performance (distance traveled, speed, location).


g e
le

Smart applications automatically route trams


ol
C
u
ad

time
sensors monitor load conditions in real
iln

Passenger counters and


Fig. 9.5.1
m
Ta

BRMS transfoms raw data into actionable information

environmental conditions
On-board sensors monitor
Fig. 9.5.2
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 370 of 446

Embedded Systems and loT Design 9-30 loT Architecture and Protocols

:
Benefits
a) Accelerate delivery and dispatch rates.
b) Improve customer satisfaction.
) Reduce fuel consumption and vehicle maintenance costs.
d) Ensure compliance with government and industry regulations.

g
e) Improve fleet productivity, uptime and safety.

in
er
9.6 loT and M2M

e
Machine to Machine (M2M) communication is the communication among the

in
physical things which do not need human intervention.

ng
M2M communication is a form of data communication that involves one or more
entities that do not necessarily require human interaction or intervention
fE in the
process of communication. M2M is also
named as Machine Type Communication
(MTC) in 3GPP.
O
M2M communication could be carried over mobile
networks (e.g. GSM-GPRS,
CDMA EVDO networks). In the M2M communication,
the role of mobile network
e

is largely confined to serve as a transport


network.
g

• M2M is only a subset of loT. IoT a more


le

is encompassing phenomenon because it


also includes Human-to-Machine communication
(H2M).
ol

Radio Frequency Identification (RFID),


Location-Based Services (LBS),
C

Lab-on-a-Chip (LOC), sensors, Augmented


Reality (AR), robotics and vehicle
telematics, which are some of the
technology innovations that employ
u

and H2M communications. both M2M


ad

• Reasons for shifting from M2M to IoT :

1. It supports multiple
application with multiple device.
iln

2. It is information
and service centric.
m

3. It supports open market place.


Ta

4. IoT uses horizontal enabler approach.


5. It requires generic cormmodity
devices.
6. Used in B2B and B2C.
Key features of M2M :
1. Low mobility : M2M
Devices do not move
and if moves onlv within a
area. certairn
2. Time controlled : Data can be sent or receive
periods. only at certain pre-defined time

TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>

Page 371 of 446

Embedded Systems andIloT Design


9-31 loT Architecture and Protocols
3. Time tolerant : Sometimes data
transfer can be delayed.
Packet switched : Network operator
to provide packet switched
Online small service.
data transmissions : Devices frequently
or send receive
amounts of data. Sau
6 Low power consumption : To improve the ability of the system to
efficiently
service M2M applications.

g
7.
Location specific trigger :
Intending to trigger M2M device in a particular area

in
e.g. wake up the device.

er
:
Six pillars of M2M

e
The six pillars of M2M are as follows:

in
1. Remote monitoring is a generic term most. often representing supervisory

ng
control, data acquisition and automation of industrial assets.
2. RFID isa data-collection technology that uses electronic tags for storing data.
fE
3. A sensor network monitors physical or environmental conditions, with sensor
nodes acting cooperatively to form/maintain the network.
O
4. The term smart service refers to the process of networking equipment and
e

monitoring it at 'a customer's site so that it can be maintained and serviced


g

more effectively.
le

5. Telematics to the integration of telecommunications and infomatics, but most


often it refers to tracking, navigation and entertainment applications
in
ol
C

vehicles.
wildlife-tracking
6. Telemnetry is usually associated with industrial, medical and
amounts of vehicles data.
u

applications that transmit small


ad

M2M
Y.6.1 Architecture and Components of
iln

architecture.
Fig. 9.6.1 shows M2M
m

an M2M solution are as follows :


• The system components of
M2M capabilities and
A device that runs application(s) using
Ta

:
1. M2M Device to an
functions. An M2M device is either connected straight
network domain
gateways via an M2M area network.
access network or interfaced to M2M
M2M area network
A
provides connectivity between M2M
2. M2M area
network: M2M area betworks include : Personal
M2M gateways. Examples of
devices and SRD, UWB, Zigbee, Bluetooth, etc
such as IEEE 802.15,
area network technologies M-BUS.
as PLC, M-BUS, Wireless
OF local networks such
using M2M capabilities to ensure M2M devices
3. M2M gateways : Equipments network and application domain. The
interconnection to the
interworking and
run M2M applications.
M2M gateway may also

PUBLICA TIONSe
- an up-thrust for knowledge
TECHNICAL
<br>

Page 372 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-32

M2M Gateway

Satelite
XDSL
LAN

g
in
interface M2M
"eNBs
Core

er
Machine eNBs

e
devices

in
Appiication Domain

ng
M2M Domain Network Domain
Fig. 9.6.1 M2M architecture
4. M2M fE
applications server : Applications that run the service logic and use service
capabilities accessible via open interfaces.
O
5. M2M application The application component of the solution is a realization of the
:

highly specific monitor and control process. The application is further integrated
e

into the overall business process system of the enterprise.


g

• Fig. 9.6.2 shows generic M2M solution.


le
ol

Backend
C

(Datacentre, cloud)
u
ad

Network core
iln
m

M2M gateways
Ta

M2M devices

TECHNICAL PUBLICATIONS®
an up-thrust for knowledge
<br>

Page 373 of 446

Enmbedded. Systems and loT Design


9-33 loT Architecture and Protocols

Light
Wireless
bulb network
Light
switch

Manufacturer A Bluetooth, Z-wave, Zigbee


Manufacturer B
Fig. 9.6.2 Generic M2M solution

g
in
.A number of sub-sets of users
M2M services can be identified : Consumers in
of

er
the home, business users and facility managers,
city governments, logistics
energy

e
businesses, providers and more.

in
9.6.2 Difference between M2M and loT

ng
Machine-to-Machine Internet of Things
It support single application with single device. It
fE
support multiple application with multiple
device.
O
It is communication and device centric. It is information and service centric.
e

It support closed business operations. It support open market place.


g

M2M uses vertical system solution approach. IoT uses horizontal enabler approach.
le

If requires specialized device solutions. It ...........


requires generic commodity devices.
ol

****

Used in B2B and B2C.


Used in B2B.
C

easeoeercoee

Management with NETCONF - YANG


System
u

loT
B
ad

:
Need for loT Systems Management :

loT system management is


required for following
iln

a. Automating Configuration
Statistical Data
m

D. Monitoring Operational and


Ta

C.
Improved Reliability
d. System Wide Configurations
e. Multiple System
Configurations
Configurations
I. Retrieving and Reusing
(SNMP)
9.7.1 Simple Network Management Protocol
used network management protocol that
SNMP is a well-known and widelynetwork devices such as routers,
con?guring switches,
allows monitoring and
servers, printers, etc.
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 374 of 446

9-34 loT Architecture and Protocols


Embedded Systems and loT Design

SNMP component include Network Management Station (NMS), Managed Device,


Management Information Base (MIB) and SNMP Agent that runs on the device
Simple Network Management Protocol (SNMP) is an application-layer protocol
used to manage and monitor network devices and their functions.
SNMP provides a common language for network devices to relay management
information in a Local Area Network (LAN) or Wide Area Network (WAN).

g
in
SNMP has a simple architecture based on a client-server model. The servers, called
managers, collect and process information about devices on the network.

er
The clients, called agents, are any type of device or device component connected

e
to the network. They can include not just computers but also network switches,

in
phones, printers, and so on.

ng
Some devices may have multiple device components. For example, a laptop
typically contains a wired as well as a wireless network interface.
fE
Strength of SNMP :
O
1. It is simple to implement.

2. Agents are widely implement.


e

3. Agent level overhead is minimal.


g
le

4. It is robust and extensible.


5. Polling approach is good for LAN based managed object.
ol

6. It offers the best direct manager agent interface.


C

7. SNMP meet a critical need.


u

Limitation of SNMP :
ad

1. It is too simple and does not scale well.


iln

2. There is no object orietned data view.

has no standard control definition.


m

3. It
4. It has many implementation specific (private MIB)
Ta

extensions.
5. It has high communication overhead
due to polling.
9.7.2 Network Operator Requirements
Ease of use
• Distinction between configuration
and state data
. Fetch
configuration and state data separately
Configuration of the network as a whole
TECHNICAL PUBLICATIONS® -
an up-thrust for
knowledge
<br>

Page 375 of 446

Enbodded Systems and loT Design


9-35
loT Architecture and Protocols
Configuration transactions across
devices
Dump and rèstore configurations
Cesnnortfor both data-oriented and
task oriented access control
NETCONF
9.7.3
. Network
Configuration

g
Protocol (NETCONE) is a-
session-based network
management protocol. NETCONF allows retrieving state or

in
configuration data and
manipulating contiguration data on network devices.

er
NETCONF is the standard for installing, manipulating and
deleting configuration

e
of network devices.

in
Fig 9.7.1 shows NEFCONF protocol layers.

ng
NETCONF Protocol
YANG Defined Content
(Config data,notif)
fE
O
Operations
Client (methods) Server

RPC or
e

Notification
g

NETCONE
le

Configuration
Transport Datastore
ol
C

YANG Defined

Fig. 9.7.1 NEFCONF protocol layers


u
ad

means that
for transaction-safe configuration of devices. This
NETCONF is defined changing
configuration for a range of devices,
Scenarios like setting up initial
iln

automatically, while keeping flexibility


ACLs and adding VPNS, can be performed
m

and vendor independence. encoding for the


Markup Language (ML) based data
Ta

It uses an Extensible messages.


as well as the protocol
Configuration data
Remote Procedure Call (RPC) based mechanism to
simple a server.
The server is
a
network
NETCONF uses a a client and
between
facilitate communication
a
or application running
as part of network
can be a script
device and client
manager.
layer across network devices.
as the transport
Shell(SSH)
t uses Secure to retrieve and edit configuration data
operations
NETCONF provides various
from network devices.
PUBLJCATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 376 of 446

9-36 loT Architecture and Protocols


Embedded Systems and loT Design

The Content Layer consists of configuration and state data which is XML-encoded.
The schema of the configuration and state data is defined in .a data modeling
language called YANG.
NETCONF provides a clear separation of the configuration and state data. The
configuration data resides within a NETCONF configuration datastore on the

g
server.

in
All NETCONF devices must allow the configuration data to be locked, edited,
saved, and unlocked. In addition, all modifications to the configuration data must

er
be saved across a reboot in non-volatile storage

e
in
9.7.4 YANG

ng
• YANG is a data modeling language used to model configuration and state data
manipulated by the NETCONF protocol. fE
YANG is used to model both configuration and state data of network elements.
YANG structures the data definitions into tree structures and provides many
O
modeling features, including an extensible type system, formal separation of state
e

and configuration data and a variety of syntactic and semantic constraints.


g

• YANG data definitions are contained in


modules and provide a strong set of
le

features for extensibility and reuse.


ol

YANG modules defines the data exchanged between the NETCONF


client and
server. A module comprises of a number of are
C

leaf nodes which organized into a


hierarchical tree structure.
u

9.8 loT Platform Design Methodology


ad

The rise of the Internet of Things has led to an


explosion of new sensor computing
iln

plat-forms. The complexity and application domains


of IoT devices range from
simple self-monitoring devices in vending machines to
complex interactive devices
m

with artificial intelligence in smart vehicles and drones.


Ta

As IoT developers wish to meet more


aggressive platform objectives and protect
market share through feature differentiation,
they must choose between low-cost,
and low-performance CPU-based Commercial-Off-The-Shelf
high-performance custom platforms (COTS) systems, and
with hardware accelerators such as GPU
FPGA. and
An loT platform facilitates communication,
data flow, device management, and the
functionalityof applications. The goal is to
build IoT applications within an
platform framework. The loT platform allows lo
applications to connect machines,
devices, applications, and people to data
and control centers.
TECHNICAL PUBLICATIONS®
an up-thrust for
knowledge
<br>

Page 377 of 446

Embedded Systems and loT Design


9-37 loT Architecture and Protocols
Home automation can be described as
introduction of technology within the Purpose and requirement
home environment to provide
convenience, comfort, security and Specification for process model
energy efficiency to its occupants.
Specification for domain model
• A home automation system can

g
switching

in
involve off electrical Specification. for information model
appliances like air-conditioners

er
refrigerators when a desired Service specification

e
temperature has been reached, then

in
switching on again when the loT level specification
temperature has crossed

ng
certain
value Functional view specification

Fig. 9.8.1 shows design methodology


steps.
fE Operational view specification
O
Sensors : Sensors are the eyes of a Device and components integration
home automation system. They "see"
e

the environment and convert what Application development


g

they find into an electrical quantity


le

Fig. 9.8.1 Design methodology steps


that can be measured by a
ol

microcontroller or system processor.


users
Remote connectivity Depending on need and various design considerations,
C

:

may need to be able .to control the system and appliances remotely.
u

9.8.1 Purpose and Requirement Specification


ad

can remotely control the home electronic


Using web application, user
:
iln

Purpose
devices (light and air conditioner)
two modes : manual and
m

Behavior : Home automation system will works in


system provides options of manually and
automatic mode. In manual mode, web
Ta

automatic mode, sensor is provided in


remotely switching ON/ OFF the light. ln
the room. System
measures the darkrness of the room and light is ON when
mneasured by another sensor. air
darkness increases. Room temperature
15

Conditioner is ON when
room temperature is increases.
: monitoring and control function is
System Management Requirement Remote
provided by system.
: Data analysis is based on local data.
Data Analysis Requirement

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 378 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-38

Application Deployment Requirement Application is installed on local device


:

but it support remote operation.


• Security Requirement : Basic authentication mechanism must be provided.

9.8.2 Process Specification

g
Process specification is defined after requirement step. Draw the use case based

in
upon first stage. Fig. 9.8.2 shows process specification diagram.

er
Start

e
in
ng
Operating modes

fE
Select
O
Manual mode Auto
Temp_state Temp_ level
g e
le
ol

ON state OFF state ON state OFF state


C

Fig. 9.8.2
Process specification diagram
• In auto mode, system monitors the room temperature
u

and light level and takes the


decision for switching ON / OFF.
ad

• In manual mode, user performs the


operation.
iln

9.8.3 Domain Model Specification


m

A domain model defines the


main concepts of a specific area of
interest.
Ta

The IoT is a support infrastructure for


enabling objects and places in the physical
world to have a corresponding representation
in the digital world. Fig. 9.8.3 shows
mapping Concept of physical world to virtual world.
As interaction with the physical
world is the key for the IoT: it
captured in the Domain Model (DM). needs to be
The DM defines the main concepts tne
Internet of Things and the relations of
between these concepts.
User and a physical entity are two concepts
User can be a human user, and the that belong to the domain model.
interaction can be physical.

TECHNICAL PUBLICATIONS® -
an up-thrust for
knowledge
<br>

Page 379 of 446

Embedded Systems and loT Design


9-39 loT Architecture and Protocols

Physical world Virtual entry-based


model modeis relevant Example
IoT system interactions
aspects of plhysical world
Give me the
indoor
temperature in
room 1.23

g
Set iight level
Virtuai in room 2.57

in
entity to 15
Association of loT services level

er
to modelled virtual entites

Give me the

e
Resources Sasensorsenisor value of

in
exposed as loT temperaturs
services measSure. sensor senso sensor 456
actuator IoT

ng
observe and
actuat on service
physical vorld levet Set actuator
967 to"on"
fE
Fig. 9.8.3 Mapping concept of physical world to virtual world
O
a.
The physical interaction is the result of the intention of the human to achieve
e

certain goal. Fig. 9.8.4 shows loT domain model.


g

• A Physical entity, as the model shows, can potentially contain other physical
le

exanmple, a building is made up of several floors, and each floor has


entities; for
ol

several rooms.
as a Virtual entity. A Virtual
entity is represented in the digital world an
C

• A Physical
can a entry, a geographical model, image or avatar, or any
entity be database
u

other Digital Artifact.


ad

User
iln
m

Invokes, Interacts
Association
Ta

Service
Virtual mddels Physical,
entity entity

exposes
Resource Device
hosts

Domain model
Fig. 9.8.4 loT
PUBLICATIONS -
an up-thrust for knowledge
TECHNICAL
<br>

Page 380 of 446

Embedded Systems and loT Design 9- 40 loT Architecture and Protocols

The relations between services and entities are modeled as associations. These
associations could be static, e.g. in case the device is embedded into the entih.
they could also be dynamic, e.g, if a devic from the environment is monitoring a
mobile entity. These identified concepts of the loT domain and the relations
between them are depicted in Fig. 9.8.5.

Entity

g
is associated
with

in
is attached to

er
Resource

e
Device

in
accesses

ng
Service

Fig. 9.8.5 Key concepts and interaction in loT model


fE
• One physical entity can be represented
O
by multiple virtual entities, each serving a
different purpose. For the IoT domain Model, three kinds of device types are the
most important :
e

1. Sensors : These are simple or complex devices and


g

contain a transducer that


converts physical properties such as temperature into electrical
le

signals. These
devices include the necessary conversion of analog electrical
signals into digital
ol

signals.
C

2. Actuators: These devices that involve a transducer that converts electrical


a
signals to change in a physical property.
u

3. Tags: Tags in general identify the Physical entity that they are
ad

. Home Automation System Example :


attached to.

1. Physical entity: Room


iln

in the home and room temperature


2. Device Single board muni computer
:
with sensor and relay switch
m

3. Resources Operating system


:
which runs on mini computer
Ta

4. Services : Mode selection,


controller service which runs services on
retrieve the room temp. the device,

9.8.4 Information Model Specification


An abstract description (UML diagram or
ontology) for explaining information
about elements or concepts defined in the IoT Domain
Model.

TECHNICAL PUBLICATIONS® an up-thrust


for knowledge
<br>

Page 38I of 446

Enbodded Systems and loTr Design


9-41 loT Architecture and Protocols
The information model models domain model concepts
represented and manipulated that are to be explicity
in the digital world. In addition
the information
model explicitly models
relations between these concepts.
Fig. 9.8.6 shows information
model. The information model is a meta
provides a model that
structure for the information. This structure
provides the basis for

g
defining the functional interfaces.

in
er
Value

e
in
ng
VirtualEntity ValueContainer
Attrlbute
entity Type
jdentifier
attributeName
attribute Type
fE
O
e

Association
g

service Type
le

0..
ol

Seryice MetaData
C

Description
metadataName
metadataType
u

metadata Vaiue
ad

0.."
Device
iln

Resource Description
Description
0..1
m

Model
Fig. 9.8.6 loT Information
Ta

using Unified Modeling Language (UML)


• IoT Information Model is represented necessary information about
diagram. The IoT Information Model maintains the
or attributes.
Virtual Entities and their properties
can contain information about the obiects
The information model for an object
to automatically be composed
structure and resource types. This can enable APls
consumed by application software.
by middleware and automatically
context, such as geographical .location, and
Additional metadata can indicate
protocols and event handlers, as well as access control
bindings, such as message
information.
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 382 of 446

Embedded Systems and loT Design 9-42 loT Architecture and Protocols

The IoT Information Model describes Virtual Entities and their attributes that have
one or more values annotated with meta-information or metadata. The attribute
values are updated as a result of the associated services to a Virtual Entity.

9.8.5 Service Specification

g
Service specification in IoT defines list of services provided by the system. It

in
includes service type, input / output, service endpoints, schedulers, service effects
and service preconditions.

er
State and attributes are defined in process specification and information model.

e
For example in home automation system, mode setting is an example of mode

in
service. User can set the auto or manual mode.

ng
Mode services sets mode to auto or manual or retrieves the current mode.
• In manual mode, the controller service,
fE
retrieves the current state from the
database and switches the air conditioner ON / OFF.
O
Service

Input Name: Controller


e

Type: Native Output


Mode': Auto/Manual
g

State : ON/OFF
le
ol

Schedule
C

|Interval : Every 7 minutes


u
ad

Fig. 9.8.7 Home automation


controler service
9.8.6 loT Level Specification
iln

IoT Development level are six types.


m

IoT Level 1 Single node, perform sensing,


perform analysis and hosts the
Ta

application
IoT Level 2 Single node, perform sensing,
perform local analysis
IoT Level 3 Single node, data is analyzed
in cloud and application is cloud
based
IoT Level 4 Multiple Node, perform local
analysis, application is cloud
based
IoT Level 5 Multiple end node and coordinator
.... node
ar***

IoT Level 6 Multiple independent node,


perform sensing, send data to
cloud

TECHNICAL PUBLICATIONS an up-thrust for


knowledge
<br>

Page 383 of 446

Enbedded Systems and loTT Design


9-43 loT Architecture and Protocols

9.8.7 Functional View Specification


Eunctional View describes the system's runtime Functional Componernts,
their
responsibilities, default functions, interfaces The
and primary interactions.
Functional View derives from the Functional Model and reflects the developer's
perspectives on the system.
. It

g
will need to be extended with all identified (and recommended) new

in
profile-specific Functional Components including their interfaces and a list of

er
Sequence Charts illustrating recommended usage of those components.
• Fig. 9.8.8 shows functional view.

e
in
Applications

ng
Management Service IoT process Virtual entity loT service Security

Configuraticn
organization
Service
management
Process
VE serVIcefE loT Broker Keyrock IDM

modeling VE SeViCe BackEnd Authorizaticn


composition
O
resoiution Device
ProcesS Identity
Fauit Service Manager
execution VE IoT management
orchestration
e

service Autherticatiorn
Reporting monitoring
ORION
g

Gontex broker
oT discovery Trust &
reputation
le

|KeyRock IDM ioT servIca


service resoiution
Menber choreography Key axchange
ol

Communkcatlon management
Stete
C

Gateway
Protocol adapter Data handling End to end
Commutication
u

Network
Hop to hop comImunicatio
communication
ad

Devices
iln

view
Fig. 9.8.8 Functional
m

Functional View are hence :


constructing the IoT
The viewpoints used for
Ta

1) The Unified Requirements;

2) The IoT Functional


Model
Components are defined, the default function set, system use
Once all Functional are made.
and interface definitions
cases, Sequence charts
functional group : Device functional components contains
• Device and Application components. Application
tag, processing and storage
the Sensing, actuation
standalone application.
functional group contains components for end-to-end
functional group : It contains the
Communication communication, and Hop-by-Hop communication.
communication, network
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>

Page 384 of 446

Embedded Systems and loT Design 9-44 loT Architecture and Protocols

Communication type Description


End-to-End Communication FC 1) Responsible for end-to-end transport of application layer
messages through diverse network and MAC/physical layers
2) Used with mesh radio networking technologies such as IEEE
802.15.4

g
3) The End-to-End FC interfaces the Network FC on the

in
"southbound" direction.
Hop-by-hop FC

er
1) Responsible for transmission and reception of physical and
MAC layer frames to/from other devices.

e
2) Two interfaces used : one "southbound" to/from the actual

in
radio on the device, and another for "northbound" to/from

ng
the Network FC in the Communication FG.
Network FC 1) Responsible for message routing and forwarding and the
fE
necessary translations of various identifiers
and addresses.
IoT Service Functional Group : It consists of IoT
Service FC and the IoT Service
O
Resolution FC. Various service implementations are
covered in service FC and
service resolution FC contains the necessary
functions to realize a directory of loT
e

Services that allows dynamic management


of loT service descriptions.
g

Virtual Entity Functional Group : The Virtual


le

Entity FG contains functions that


support the interactions between Users
and Physical Things through Virtual Entity
ol

services.
C

Process Management FG :
Provides the functional concepts necessary
conceptually integrate the IoT to
world into traditional (business) processes.
u

The Process Modeling FC


ad

which provides the tools


IoT-aware business processes required for modeling
that will be serialized and executed
Execution FC, which is responsible in the Process
iln

for deploying process models


environments. to the execution
• Service Organization
m

FG : Acts as a communication
Functional Groups by composing hub between several other
Ta

and orchestrating Services


abstraction. of different levels of
The Service Orchestration
FC resolves the IoT
service requests coming from Services that are suitable
the Process Execution FC or to fulfill
Service Composition FC from Users while the
is responsible for
functionality by composing IoT creating services with extended
. Service services with other services.
Choreography FC offers a
broker that handles Publish/Subscribe
communication between seryices.

TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>

Page 385 of 446

Embedded Systems and loT Design


9-45 loT Architecture and Protocols

Entity FG : Provides functionality for the


Virtual
interaction of VEs with the IoT
system, for VE look-up and discovery and for providing information concerrning
VEs. The VE Resolution
FCprovides discovery services for associations between.
VEs and IoT.
. VE
and IoT Service Monitoring FC is responsible for automatically finding new

g
associatiorns based on service descriptions and information about VE's. the VE

in
Service FC handles entity services.
.
Service FG : Provides IoT services as well as functionalities for discovery, look-uP,

er
and name resolution of IoT Services.

e
:
Security FG It is responsible for security and privacy matters in loT-A-compliant

in
IoT systems.

ng
1) The Authorization FC is used to apply access control and access Policy
-management while, the Authentication FC is used for user and service
fE
authentication.
secure communications
Key Exchange and Management (KEM) FC enables
O
2)
upon request in a
ensuring integrity and confidentiality by distributing keys
e

secure way.
and tracking of actions that
g

• Management FG:It is responsible for the composition


le

involve the other FGs.


1) Configuration FC is responsible for
initializing the system's configuration.
ol

occur in the
2) The Fault FC is used to identify,
isolate, correct and log faults that
C

IoT system. any


management of the membership of
u

3) The Member FC is responsible for the


ad

relevant entity and, finally, the State FC can


generates reports about the system
• The Reporting FC a sequence of
iln

a particular state on the system by issuing


change or enforce
Commands to the other FCs.
m

Specification
Ta

9.8.8 Operational View case and


depends on the specific actual use
View
Deployment and Operational IoT uses different methods for communication
requirements. Smart object in the
using different technology. very important to address how
Operation view is
Hence the Deployment and selecting technologies and making them
realized by
actual system can be way.
operate in a comprehensive
cOmmunicate and a of
set users.
guidelines to application
Model with
Reference face while designing the actual
Provides an IoT choices that they have to
The different design
nplementation of their services.
PUBLICATIONs.- an up-thrust for knowledge
TECHNICAL
<br>

Page 386 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-46

are the following :

The viewpoints used in the Deployment and Operation view


1) The IoT Domain Model diagram is used
as a guideline to describe the specifs
application domain.
2) The Functional Model is used as a reference to the system definition.
3) Network connectivity diagrams can be used to plan the connectivity topology

g
to enable the desired networking capability of the target application; at the

in
deployment level, the connectivity diagram will be used to define the
hierarchies and the type of the sub-networks composing the complete system

er
network;

e
4) Device Descriptions can be used to map actual hardware on the service and

in
resource requirements of the target system.

ng
9.8.9 Device and Component Integration
fE
• In this step we have to integrate the devices and components. The devices and
components used in home automation examples are Raspberry Pi, sensor, laser
O
pointer, light dependent resistor etc.
Now is a good time to become acquainted with Raspberry Pi
e

use in IoT projects. When developing an and its potential for


innovative use for this device, you will
g

need to come up with a software design solution that addresses your


le

end-user
requirements. You can accomplish this more easily
when you have a better sense
ol

of the Raspberry Pi capabilities being demonstrated


out in the field now.
• From controlling the room
C

lights with your smartphone to


occur automatically, home scheduling events to
automation has taken convenience to a
level. Instead of using mechanical whole new
u

switches, you can now conveniently


the devices in your home from your control all
ad

fingertips.
iln
m

Power
Ta

Supply

Fia. 9.8.9 Schematic


diagram for home automation

TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>

Page 387 of 446

Systems and loT Design Protocols


Embedded
9-47 loT Architecture and

9.8.10 Application Development


n web
Application development is final stage developing IoT application.
in
application, it display mode control : Auto and Manual
Two modes are provided auto mode and manual mode.
:

. auto mode is enabled the light control in the web application is disabled and if

g
f

in
reflects the current state of light.
If auto mode disabled, the light control is enabled and it is used for manually

er
controlling light and air conditioner.

e
in
Controller

ng
Light Air conditioner
o
fE
Auto mode Manual mode
O
o o
e

ON OFF ON OFF
g

Fig. 9.8.10
le

on followings :
Design smart irrigation system based
ol

Example 9.8:1
system
Define process specification for smart irrigation loT
C

) loT system
i) Domain model of smart irrigation
smart irrigation loT system
u

ti) Information model of


ad

iv) Controller service of smart


irrigation IoT system
iln

Solution:
:
) Process specification
m

with the help of


use cases
• Define the process on Purpose &
Ta

formally described based requirement


• The use cases are
specification
or an attribute
use case: Circle denotes a state
In this
i) Domain model:
main concepts,
entities and objects in the domain of IoT system to
Describes the
be designed between them
attributes of the objects and relationships
It defines the
Concepts include the following
: Physical entity, Virtual
• Entities, Objects and
Service
entity, Device, Resource,
TECHNICAL PUBLICA
TIONS,- an up-thrust for knowledge
<br>

Page 388 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-48

Physical entity :
• Discreet identifiable entity in physical environment
• For example : Pump, motor, LCD
• The loT System provides the information about the physical entity (using sensors)
or performs actuation upon the Physical entity (like switching a motor on etc.)

g
:

In smart irrigation example, there are three Physical entities involved

in
a. Soil (whose moisture content is to be monitored)

er
b. Motor ( to be controlled)

e
C. Pump (To be controlled)

in
In smart irrigation system there are three services
:

ng
1. service that sets the signal to low/ high depending upon the threshold value
A

2. A service that sets the motor state on / off


fE
3. A controller service that runs and monitors the threshold value of the moisture
and switches the state of motor on / off depernding upon it.
O
When threshold value is not crossed the controller retrieves the motor status from
database and switches the motor on/off.
g e

ii) Information model specification :


le

Defines the structure of all the information in the IoT system (such as
attributes,
ol

relations etc.)
• It does not describe the specifics of how the
C

information is represented or stored.


This adds more information to the Virtual entities by
defining their attributes and
u

relations
ad

:
iv) Controller service

Define the services in IoT System, service
iln

types, service inputs


endpoints, service schedules, service preconditions l outputs, service
and service effects.
m

Services can be controller service,


Threshold, service, state service for smart
irrigation system.
Ta

These services either change the


state/attribute values or retrieve the current
values.
• For eg :
a. Threshold
service sets signal to high or
low depending upon the soil moisture
value.
b. State service sets the motor state : on or off
C.
Controller service monitors
the threshold value as well as
switches the motor on 7 off and the motor state and
updates the status in the database.

TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>

Page 389 of 446

Embedded Systems and loT Design


9-49 loT Architecture and Protocols

Review Questions

1 Explain the steps involved in the loT system design


methodology.
2. Explain functional view specification step of loT system design methodology, consider smart
IoT-based home automation system as an example.

3. Explain service specification step of loT system, design methodology, consider smart loT - based

g
home automation system as an example.

in
-
4. Explain operational view specification step of loT system designmethodology, consider smart loT

er
based home automation sytemn as an example.

e
5. Explain purpose and requirement specification step of loT system design methodology, consider

in
smart loT-based automation system as an example.

ng
6. What is the importance of service specification in loT design methodology ?

7. Explain domain model specification step of IoT system design methodology, consider smart
IoT-based home automation system as an example.
fE
8. With the help of diagram list and briely explain the steps involved in the loT system design
O
methodology.
e

9. Explain process specification for home automation 10T system.


g

10. Explain the operational view specification step of loT system design.
le

9.9 loT Reference Model


ol
C

D.9.1 OneM2M Architecture


can be
u

Goal of this architecture is to create a common service layer, which readily


servers.
ad

embedded I field devices to allow communication with application


of
Fig. shows OneM2M architecture. OneM2M architecture consists
9.9.1
iln

network layer.
aPplication layer, services layer and
Comprises oneM2M application and related business and
m

:
1. Application layer
Ta

operational logic.
2. Services laver :
Consists of OneM2M service function that enables oneMM
applications.
connectivity and serviçes functions.
3. Network layer:It provides transport,

- an
TECHNICAL PUBLICATIONS up-thrust for knowledge
<br>

Page 390 of 446

9-50 loT Architecture and Protocols


Embedded Systems and loT Design

Autormotive
Home Energy Automotive Home Energy
application| application application application| applicationapplication

Common service layer


Communication technologies
and protocols

g
JCommunication networks

in
Communication devices

er
and hardware

e
in
ng
Fig. 9.9.1 OneM2M architecture
9.9.2 loT World Forum Standardized Architecture fE
Fig 9.9.2 shows IoT World Forum (IoTWF) Standardized Architecture.
O
Center
e

Collaboration and processes


(Involving people and business processes)
g
le

6 Appllcatlon
ol

(Reporting, Analytics, Control)


C

Query 6
IT Data abstraction Data at Non -real
based (Aggregation and access) rest time
u
ad

4 Data accumulation
(Storage)
iln

OT Event 3 Edge (Fog)


based (Data element analysiscomputing Data in Real
m

and transformation) motion time


Ta

2 Connectivity
(Communication and processing
a

units)

o Physical devices and controllers


(Sensors, Devices,
Intelligent edge Machines,
nodes of all types)

Edge
Fig. 9.9.2 loT reference
model of loTWF
Cisco, IBM, and Intel presented arn
IoT Reference Model at
The model is based on "Information Flow" the IoT World Forun

TECHNICAL PUBLICATIONS
- an
up-thrust for knowledge
<br>

Page 39 l of 446

Embedded Systems and loT Design


9-51 loT Architecture and Protocols
.
Devices send and receive data
interacting with the Network where
transmitted, normalized, and filtered using the data s
Edge Computing before landing n
Data storage / Databases accessible by Applications
which process it and provide
it to people who will Act and Collaborate.
The IWF is concerned with the broader issue of developing
the applications,
middleware, and support functions for an enterprise

g
based loT.
.

in
IoT reference model define a set of levels with control flowing from center
to-the
edge which includes sensors, device, machines and other type of an intelligent

er
nodes.

e
• Layer 1: Comprises physical devices and controllers that might control multiple

in
devices. This level enables devices to communicate with one another and to

ng
communicate, via the upper logical levels, with application platforms such as
computers, remote-control devices, and smart-phones.
fE
Layer 2: The IWF model includes gateways in level 2. Because the gateway is a
networking and connectivity device, its placement at level 2 seems to make more
O
sense.
Layer 3 : It performs data element analysis and transformation.
e

numerous
Layer 4: The data accumulation level, is where data coming from the
g

is placed in
devices, and filtered and processed by the edge computing level,
le

a clear distinction
storage that will be accessible by higher levels. This level marks
ol

of processing between lower-level


in the design issues, requirements, and method computing.
C

(fog) computing and upper-level


(typically cloud)
ensures
:
Reconciles multiple data formats and
Layer 5, Data abstraction layer
u

sources. Confirms that data set is complete and


consistent semantics from various
ad

or multiple data stores using virtualization.


consolidates data into one place
: Interprets data using software applications.
iln

Layer 6, Application layer


provide reports based on the analysis of
Applications may monitor, control and
m

the data.
processes layer: Consumes and shares the application
Ta

Layer 7, Collaboration and


information. :

following things are achieved


Using this reference model, smaller parts.
Z. Decompose the problem into
technologies at each layer.
2. Identify different can be provided by different vendors.
a in which different parts
3. Define system interoperability.
a process are defining interface that leads to
4. Have between
model that 1s entorced at one transition points
5. Define a tiered security
levels.
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>

Page 392 of 446

Embedded Systems and loT Design 9-52 loT Architecture and Protocols

Characteristics of loTWF model :


Simplifies : It helps break down complex systems so that each part is more
understandable.
Clarifies It provides additional information to precisely identify levels
: the of

IoT and to establish common terminology.


Identifies : It identifies where specific types of processing are optimized

g
across different parts of the system.

in
Standardizes : It provides a first step in enabling vendors to create loT

er
products that work with each other.

e
Organizes : It makes the IoT real and approachable, instead of simply

in
conceptual.

ng
9.9.3 Simplified loT Architecture

Fig 9.9.3 shows Simplified IoT Architecture.


fE
O
Core IoT functional stack IoT data management and compute
e

Applications Cloud
g
le

Security
Communication Fog
ol

Sensors and actuators


C

Edge
u

Fig. 9.9.3 Simplified loT architecture


ad

. It consists of Core IoT functional stack group and IoT data management and
iln

compute stack.
loT data management and compute stack :
m

Fog computing, or sometimes called edge computing, can


be thought of as an
Ta

extension of the cloud, with the infrastructure


distributed at the edge of the
network.
Fog computing facilitates the operation of end devices,
typically smart IoT devices,
with cloud computing data centres.
This helps in meeting the needs of high-speed mobile geographical
distribution scenarios and reduces the bandwidth scenarios and
load of the network core.

TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>

Page 393 of 446

Gmbedded Systems and loT Design 9-53 loT Architecture and Protocols

The IoT Cloud Platform represents the software


infrastructure and services
required to enable an IoT solution.t i:
An loT Cloud Platform typically operates on a cloud infrastructure or
inside an
lpst enterprise data center and is expected to scale both horizontally,
to'support the
large number of devices connected, as well as vertically to address
the' variety of
IoT solutions.

g
in
The IoT Cloud Platform will facilitate the interoperability of the IoT solution with

er
existing enterprise applications and other loT solutions.
Çore loT functional stack group :

e
• The loT gateway acts as the aggregation point for a group of sensors

in
and
actuators to coordinate the connectivity of these devices to each other and to an

ng
dguo: external network.
• An loT gateway can be a physical piece of hardware or functionality that is
fE
inng: incorporated into a larger "Thing" that is connected to the network.
• For example, an industrial machine might act like a gateway, and so might a
O
connected automobile or a home automation appliance.
e

• An loT gateway will often offer processing of the data "at the edge" and storage
g

E
t capabilities to deal with network latency and reliability.
le

For device to device connectivity, an IoT gateway deals with the interoperability
ol

issues between incompatible devices.


many loT gateways supporting masses of
C

i A typical IoT architecture would have


devices.
u
ad

9.10 loT Protocols


some kind of messaging protocol for each
Internet of Things solutions employ
iln

the system. These messaging protocols


individual IoT device to communicate inmessages IoT
or from the IoT devices to the
m

are used to transmit device telemetry


SSaging Hub.
Ta

messages sent
protocols are the rules, formats and functions for
Messaging to
Essentially, everyone has agreed on the types of information
between machines.
way of formatting that information so everyone
include with data packets and the
can read it.

9.10.1 MQTT
Mobile
Open Connectivity for
Message Queue Telemetry Transport (MQT) Is
M2M and IoT.

PUBLICATIONS - an
up-thrust for knowledge
TECHNICAL
<br>

Page 394 of 446

9-54 loT Architecture and Protocols


Embedded Systems and loT Design

MQTT is designed for high latency, low-bandwidth


or unreliable networks, The
design principle minimizes the network bandwidth and device resource
requirements.
• MQTT is a lightweight broker-based publish/subscribe messaging protocol
designed to be open, simple, lightweight and easy to implement.

g
MQTT characteristics

in
1. Lightweight message queueing and transport protocol

er
2. Asynchronous communication model with messages (events)

e
3. Low overhead (2 bytes header) for low network bandwidth applications

in
4. Publish / Subscribe (PubSub) model

ng
5. Decoupling of data producer (publisher) and data consumer (subscriber) through
topics (message queues)
6. Simple
fE
protocol, aimed at low complexity, low power and low footprint
implementations
O
7. Runs on connection-oriented transport (TCP).
e

8. MQTT caters for (wireless) network disruptions


g


The MQTT protocol works by exchanging a series of
MQTT Control packets in a
le

defined way. Each control packet has a specific purpose


and every bit in the
packet is carefully crafted to reduce the data transmitted over
ol

the network.
• A MQTT topology has a
MQTT server and a MQTT client. MQTT
C

headers are kept as small as possible. control packet


u

Having a small header overhead


makes this protocol appropriate
ad

lowering the amount of data transmitted over for loT by


constrained networks.
MOTT is the protocol built
for M2M and IoT which is
iln

revolutionary performance used to provide new and


. Fig.9.10.1
m

shows MQTT publish/subscribe


framework.
• A
producer publishes a message
Ta

(publication) on a
subscribes (makes a subscription) topic (subject). A consumer
for messages on a topic
A message server (called (subject).
BROKER)matches
publications to
subscriptions.
• If none of them match the message
is discarded
the message is delivered after modifying the topic. If
or more matches one

modifying the topic to


each matching consumer after
Publish / Subscribe has
three important characteristics :
1. It decouples message senders and
applications. receivers, allowing more flexible
for
TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>

Page 395 of 446

Embadded Systems and| loT Design


9-55 loT Architecture and Protocols

g
in
Message
Subscriber

e er
Message

in
MOTT
Broker

ng
Publisher
Message fE
O
g e
le

Subscriber
ol

Fig. 9.10.1 MQTT publish/subscribe framework


C

2. It can take a single message and distribute it to many consumers


u

3. This collection of consumers can change over time, and vary based on the
ad

nature of the message.


The MOTT messages are delivered asynchronously ('push") through publish
iln

subscribe architecture.
m

a series of MQTT control packets in a


• The MOTT protocol works by exchanging
Ta

defined way.
Each control packet has a specific purpOse and every bit in the packet is carefully
over the network.
Crafted to reduce the data transmitted
A MOTT topology has a MQTT
server and a MQTT client. MQTT client and
Server communicate through difterent control packets. Table below briefy
describes each of these control packets
as small as possible. Each MOTT contol
MQTT Control packet headers are kept
and pavload.
packet consist of three parts, a fixed header, variable header

- an up-thrust for knowledge


TECHNICAL PUBLICATIONS
<br>

Page 396 of 446

39-56 loT Architecture and Protocols


Embedded Systems and loT Design

Each MQTT control packet has a 2 byte Fixed header. Not all the control packet
have the variable headers and payload.

.A variable header contains the packet identifier if used by the control packet. A
payload up to 256 MB could be attached in the packets.
Having a small header overhead makes this protocol appropriate for loT by

g
lowering the amount of data transmitted over constrained networks.

in
:
MQTT Quality of Service

er
There are the three levels of MQTT QoS.

e
1. QoS 0: AT MOST ONCE

in
Guarantees that a particular message is only ever received by the subscriber
a maximum of one time. This does mean that the message may never arrive.

ng
The sender and the receiver will attempt to deliver the message, but if
fE
something fails and the message does not reach its destination the message
may be lost.
O
This QoS has the least network traffic overhead and the least burden on the
client and the broker and is often useful for telemetry data where it doesn't
e

matter if some of the data is lost.


g

2. QoS 1: AT LEAST ONCE


le

Guarantees that a message will reach its intended recipient one or more
ol

times. The sender will continue to send the message


until it receives an
acknowledgment from the recipient, confirming it has received
C

the message.
The result of this QoS is that the recipient may
receive the message multiple
u

times, and also increases the network overhead


. In addition more than OoS.
ad

burden is placed on the sender as it needs to store


message and retry should it the
fail to receive an ack in a reasonable time.
iln

3, OoS 2: EXACTLY ONCE


The most costly of the QoS,
m

this Q0S will ensure that the message


a is
received by recipient exactly one time.
Ta

This ensures that the receiver never


gets any duplicate copies
message and will eventually of the
get it, but at the extra cost
overhead and complexity required on of network
the sender and
eteverIS
9.10.2 XMPPt
Extensible Messaging and Presence
Protocol (XMPP) is an open XML
for real-time communication. It technology
is based on instant messaging presence.
and

TECHNICAL PUBLICATIONS® - an up-thrust


for knowledge
<br>

Page 397 of 446

Embedded Systems and loT Desian


9-57 loTArchitecture and Protocols

XMPP is an open-source popular language


which uses the markups. The markup
means marking by some signs and characters,or tags so
specify the contents
between the markups.
It allows the exchange of data between two or more
systems and supports
presence and contact list maintenance.

g
It uses client server architecture in which XMPP client communicates wit
with XMPP

in
server using TCP socket. It also works via HTTP using a websocket
implementation.

er
It also uses publish/subscribe mechanism for data 'sharing like MQTT protocol."

e
XMPP is based on a decentralized client-server architecture. In this' architecture,

in
clients don't communicate directly with each other; instead, there's a decentralized

ng
server acting as the intermediary between them.
XMPP allocates an XMPP address to every client on the XMPP network. This
fE
address works just like a standard email address with an IP address/domain
name, an optional node, and a usernamne for the resident server.
O
• Fig. 9.10.2 shows simple architecture of XMPP.
g e
le

XMPP client XMPP server XMPP client


ol
C

Fig. 9.10.2 XMPP simple architecture


a
consisting of a server and two clients, client with
u

• In a simple XMPP architecture


an associated XMPP server with another
ad

a unique name communicates through


a unique name.
siClent using on
iln

client form of the protocol with


• Each client the XMPP network implements the
The architecture may include
XMPP
server routing capablity.
m

L sl
the XMPP providing
between foreign messaging domains
gateways which are often used to translate
Ta

and IM protocols. of a as
The XMPP gateways permit the termination given client-to-server session
of a new client-t0-server session to the target endpoint
well the initiation
as
the essary protocol
protoco along with as its original and "native" transport
Control Protocol
XMPP uses the Transmission
applications and firewalls.
protocol for web applications.
protocol is used for all the following
XMPP
messaging apps (Google Talk, WhatsApp)
a) Instant
b) Presence status
PUBLICATIONs - an up-thrust
TECHNICAL for knowledge
<br>

Page 398 of 446

Embedded Systems and loT Design 9- 58 loT Architecture and Protocols

) Message delivery
d) Conferencing (Multi-party chat)
e) Roster management

) Voice and video calls


g) Online gaming

g
h) News websites

in
i) VolP apps

er
Advantages of XMPP protocol

e
1. Supports HTTP transport protocol.

in
2. It offers persistent connection.

ng
3. It is decentralized in nature as no central XMPP servers are needed.
4. It allows servers with different architectures to communicate.
fE
5. Utilizes a decentralized client-server architecture.
O
6. It uses TLS and SASL to provide secured
end to end connection.
Disadvantages of XMPP protocol
e

1. It does not have QoS mechanism as


used by MQTT protocol.
g

2. Streaming XML has overhead due to


le

text-based communication compare to


binary based communication.
ol

3. XML content transports asynchronously.


C

4. Server may overload with presence and instant


messaging.
u

9.10.3 Modbus
ad

. Modbus is a serial communication


protocol for use with programmable
iln

controllers. It is typically used to logic


transmit signals from instrumentation
control devices back to a main and
controller; or data gathering system,
m

system that measures temperature for example a


and humidity and communicates the
results to
Ta

a computer.
Modbus is an open protocol
developed by Modicon. Now
versions of Modbus; Modbus RTU, there are three main
Modbus ASCII and Modbus TCP.
Modbus RTU for communicating over
is serial using
binary representation of data.
Modbus ASCII is for communication
over serial
protocol communication and Modbus TCP using -ASCII characters for
Modhus is a data communication
is using TCP/IP for communication.
protocol that is based on a
model. request - response

TECHNICAL PUBLICATIONS®
an up-thust
for knowledge
<br>

Page 399 of 446


Embedded Systems and loT Design
9-59
loT Architecture
and Protocols
The most common use
case is
Interface (HMI) or the communication
Supervisory Control between a Human - Machine
a sensor,
Programmable and Data Acquisition (SCADA)
Logic Controller system and
provides a hardware -(PLC),
Controller (PAC). It or
Programmable Automation
the interoperability
of disparate automation agnostic, cost-effective way to enable
• equipment.
Modbus is an application -
OSI model. The layer messaging
protocol, positioned at level 7 of the

g
default port is 502 on a
Modbus Serial Architecture. Modbus server device.

in
Fig. 9.10.3 shows

er
Read / write
request

e
Modbus Modbus RTU

in
master

ng
Response Response Read / write
request

Slave 1
fE
Slave 2 Slave n
O
Fig. 9.10.3 Modbus serial architecture
e

Modbus devices communicate using a master - slave (client -


server) technique in
g

which only one device (the master/client) can initiate transactions (called queries).
le

The other devices (slaves/servers) respond by supplying the requested data to


the
master, or by taking the action requested in the query.
ol

A slave is any peripheral device which processes information and sends its output
C

to the master using Modbus. The I/0 Modules form slave/server devices, while a
u

typical master device is a host computer running appropriate application software.


ad

Other devices may function as both clients (masters) and servers (slaves).
iln

9.10.4 CANBUS
Contròl Area Network (CAN) bus is a serial communication protocol that allowe
m


way. CAN bus was oricin all
devices to exchange data in a reliable and efficient
Ta

a
designed for automotive applications by boSch in the 1980s. It is multi-master.
the
multi-slave, half-duplex and fault-tolerant protocol that fits well with
requirements of automotive applications.
so the separate
• In particular, CAN was developed to reduce cable wiring,
a communicate with only a
Electronic Control Units (ECUS) inside vehicle cold
single pair of wires.
computer components. called
Modern cars consist of a number o! airerent
car contains from 20- 100 ECUS. with
Electronic Control Units (ECUS). A typical
responsible for one
or more particular features of
the vehicle.
each ECU being
PUBLICATIONS - an
TECHNICAL up-thrust for knowledge
<br>

Page 400 of 446

loT Architecture and Protocols


Embedded Systems and loT Design 9-60

monitore
For example, DCU (Door Control Unit) is the ECU that controls and
DCU: offers features like automabe
various accessories in the car door. Driver
mirror
window movement, close-open door, mirror folding, child lock safety and
adjustment.
car
CAN bus is a set of 2 electrical wires (CAN_Low and CAN_High) in the
at network where infornmation can be sent to and from ECUs. The network inside the

g
car that allows ECUs to communicate with each other is called CAN. Fig. 9.10.4

in
shows the ECUs in a car connected to a CAN bus.

e er
Engine

in
Control

ng
ABS. conditionera
fE
Suspension Instrüment Sea Transmission
O
panelR position'
g e
le

Battery
ol

Fig. 9.10.4 The ECUs in a car connected to a CAN


C

bus
The CAN network is divided into subnetworks
connected together using a
u

Gateway Module ECU. Every ECUwith its CAN controller and CAN Transceiver
ad

is called a node.
ECUs need to pass data to one another so they can
make decisions on how to act.
iln

For example, If we open the door of our car, a message


would be sent on the
CComfort CAN to communicate that the car door is open. Then it would
m

get picked
lup by AHU-Audio System ECU and get displayed on the
Touch Screen.
Ta

The theoretical bit rate the CAN


bus could support goes up to 1
. CAN bus is a Mbps.
broadcasting bus. The sender send its
target specified. All nodes connected frame on the bus without any
to the bus can see the
finding it relevant for them will at frame. Only the ones
the end transmit it to their
else they,will simply ignore it. application ayer,
.But what if two nodes try to
transmit each one a frame at
Actually, each node verify if there a the same time,
is traffic on the bus, If not
sending its frame. then it will start

TECHNICAL PUBLICATIONS
-an up-thrust for knowledge
<br>

Page 401 of 446

Embedded Systems and | loT Design


9-61 loT Architecture and Protocols
. more nodes (at the same time) found no
Tf twO or
raffic on the bus and so start
sending their frarmes ? In this situation, each
node sending data on the bus 1s aso
at the same time listening to what is currently on the bus. As per
frame, the bit O
is the dominant one on the bus (since it is
the one to have the highest Differential
Voltage). This way, a node trying to send a 1 and listening toa 0 will
automatically stop sending Data. 3,

g
CAN is a CSMA/CD protocol, meaning each node on the bus can detect collisions

in
it, and back off for a certain amount of time before trying to retransmit. This collision

er
voi detection is achieved through a priority arbitration based on the message

e
identifiers.

in
CAN logic and arbitration

ng
1. CAN 2.0A messages begin with an 11-bit message ID which identifies the message
a/type and also establishes the message priority. fE
2. As with many computer interfaces, the CAN transceivers invert the microcontroller
a
signal. Thus, the dominant bus state occurs when logic "0" is transmitted and the
O
S

recessive state occurs when a logic "1" is transmitted.


e

access arbitration between nodes.


3. CAN uses the message ID to perform bus
g

to transmit its message ID.


4. Each node waits for an idle bus state then begins
le

see if the bus state match its transmission.


-5. Each node also listens to the bus to
ol

6. If a a
node detects dominant bus state while trarnsmitting a recessive a message ID
C

bit (logic "1"), it drops out of the


current arbitration round and will try again the
next time the bus is idle.
u

DE

CAN Bus is used extensively in


ad

etc.)
1. Transportation
systems (rail vehicle, aircraft, marine,
iln

systems
2. Industrial machine control
(e.g. HVAC, elevators)
Homne and building automation
m

3.
agriculture equipment)
4. Mobile machines (construction and
Ta

as well as in many other


5. Medical devices and laboratory automation,
embedded and deeply embedded appca ts
erl
Advantages of CAN: lt
which is
often built into microcontrollers.12
1. Low cost network infrastructure of
with broad availability hardware, software and systems
Large market segment
engineering tools.
deterministic design specifically for real-time
3. Light weight. low latency, highly
embedded applications.
PUBLICATIONS - an up-thrust
TECHNICAL for knowledge
<br>

Page 402 of 446

Embedded Systems and loT Design 9-62 loT Architecture and Protocols

4. Reliable with strong error detection, fault tolerant versions available.


5. Flexible and highly cofigurable with various higher level application protocols.
6. Foundation for next generation technology controller area networks.

9.10,5 BACNet

g
• BACNet stands for Data Communication

in
Protocol for Building Automation and
Control Networks. BACNet is designed specifically to meet the communication

er
needs of building automation and control systems for applications such as heating,

e
ventilating and air-conditioning control, lighting control, access control and fire

in
detection systems.

ng
This data communication protocol is both an ISO and ANSI standard used for
interoperability between cooperating building automation devices. BACNet
Protocol includes a set of rules for governing thefE data exchange on a computer
network that simply covers all from what type of cable to utilize, to form a
O
particular command or request in a normal way.
• BACNet uses an object-oriented
e

model for abstracting and representing


g

information. BACNet includes 54 standard objects


that cover many common and
le

generally useful applications. BACNet does not replace


the need for specifying
what a user wants or needs. It simply provides some
ol

standardized tools to help


enable the creation and specification of systems can
that
C

interoperate.
• A BACNet device is often
comprised of a microprocessor-based controller
and
u

software combination that is designed to


understand and use the BACNet
ad

protocol. BACNet device is typically a


controller, gateway, or user interface.
Every BACNet device contains a device
object that defines certain device
iln

information, including the device object


identifier or instance number.
• A BACNet device object instance
m

number must be field-configurable to


across the entire BACNet be unique
network where the device is installed.
Ta

device instance, each BACNet device In addition to the


contains a collection of information
device and any input and output about the
points that it monitors and controls.
collection of information frequently 1ne
includes control programs
data values. and logic as weu
BACNet divides the task of
device interoperability
Objects (information), Services into three distinct areas
(action requests)
(internetworking, electronic messages). and Transport systems

TECHNICAL PUBLICATIONS®
an up-thrust
for know!edge
<br>

Page 403 of 446

Embedded Systems and loT Design


9-63 loT Architecture and Protocols

1. Objects : All information within an interoperable BACNet device


is modeled n
terms of one or more information objects. Obiects may represent
single pieces
of information, or a collection of multiple pieces of information such as a
logical grouping Objects represent either physical or virtual information, such
as analog and binary inputs and outputs, control algorithms, specific

g
applications and calculations.

in
• Each object is iderntified with an object identifier. An object identifier is a 32-bit
binary number containing a code for the object type and the object instance

er
number.

e
2. Properties

in
a
• BACNet property conveys information about a BACNet object. Objects have

ng
collection of properties, based on the function and purpose of the object. Each
property contains two pieces of information A property identifier and the
:

property's value.
fE
O
Property Identifiers are numbers that uniquely identify given property in the
a
as read-only or read/write.
context of the Object type. Properties may be defined
e

BACnet devices to read information about


A property's purpose is to allow other
g

potentially write (change) a different value


the object containing the property and
le

to the property.
ol

3. Services
C

one BACNet device sends to another


• BACNet services are formal requests that
something.
u

BACNet device to ask it to do


ad

categories of functionality
Services are grouped into five
access (read, write, create, delete);
iln

a) Object
initialize, backup and
Device management (discover, time synchonization,
b)
m

restore database);
state);
(alarms and changes of
Ta

c) Alarm and event


data, program transfer);
d) File transfer (trend
menus),
terminal (human machine interface via prompts and
e) Virtual
parameters that need to be conveyed in
request and any
service defines each
The

the request and its reply.

PUBLICATIONS an up-thrust for knowledge


TECHNICAL
<br>

Page 404 of 446

UNIT IV: loT ARCHITECTURE AND PROTOCOLS

Two MARKS QUESTIONS WITH ANSWERS

g
Q.1 Define loT.

in
Ans. :• By embedding short-range mobile transceivers into a wide array of additional

er
gadgets and everyday items, enabling new forms of communication between people
and things, and between things.

e
The Internet of Things (IoT) is the network of physical objects i.e. devices,

in
3vehicles, buildings and other items embedded with electronics, software, sensors,

ng
and network connectivity that enables these objects to collect and exchange data.
Q.2 How loT. differ from traditional computing
? fE
Ans. : IoT data differs from traditional computing. The data can
be small in size and
frequent in transmission. The number of devices, or nodes, that are connecting to the
O
network are also greater in IoT than in traditional PC computing.
e

Q.3 List the characteristics of the Internet of Things.


g

Ans. : Characteristics of the Internet of Things are


Interconnectivity, Heterogeneity,
le

Things-related services and dynamic changes.


ol

Q.4 List the advantages of loT.


Ans. : Advantages :
C

1. Improved customer engagement and communication


u

2. Support for technology optimization


ad

3. Support wide range of data collection


4. Reduced waste
iln

Q.5 What do you mean autonomy in loT ?


m

Ans. : Autonomy in loT can


be realized by implementing self-managing
Ta

Self-marnagement is the property systems.


of a system to achieve management
of its resources intrinsically and internally. Management and maintenance
through many levels of decision and maintenance is realized
Q.6 What is M2M communication ?
making1 ss bsrti
ici: a.
Ans, : M2M communication
is a form of data communication
more entities that do not that involves one or
necessarly require human interaction or
process of communication. intervention in the

(9 - 64)
<br>

Page 405 of 446

Embedded Systems and loT Design


9-65 UNIT IV
What are the key features
0.7 of M2M communication ?
Ane :
Some of the key features of M2M communication system are given
1. Low mobility : M2M below:
devices do not move and if moves only
within a
certain area.
2. Time controlled Data can be send or receive only at certain
SVe tsipre-defined time periods.

g
in
3.
Time tolerant: Sometimes data transfer can be delayed.

er
4. Packet switched : Network operator to provide packet switched service.

e
0,8 What is M2M device ?

in
Ans. : A device that runs application(s) using M2M capabilities and network domain

ng
functions. An M2M device is either connected straight to an access network or
interfaced to M2M gateways via an M2M area network,

Q,9 What is the use of MQTT ?


fE
O
Ans. :

-
• MQTT is designed for high latency, low bandwidth or unreliable networks.
e

resource
The design principle minimizes the network bandwidth and device
g

requirements.
le

-
MQTT is a lightweight broker based publish/subscribe messaging protocol
ol

easy to implement.
designed to be open, simple, lightweight and
C

Q.10 What is need for loT systems management ?


are as follows :

Need for IoT systems management


u

:
Ans.
Automating configuration
ad


statistical data
Monitoring operational and
iln

Improved reliability
m

System wide configurations


Multiple system configurations
Ta

configurations
Retrieving and reusing
?
Q.11 NETcONF
What is management protocol. The NETCONE
Ans. :
NETCONE is a
session based network
procedure call,
a
client/server protocol that allows one
upon remote
another program without having to understand
protocol is based
program to request a service from
network details
Q.12 List the limitations of SNMP.
Ans. :
nature and each SNMP request contains all the information
SNMP is stateless in
to process the request.
TIONS an up-thrust for knowledge
TECHNICAL PUBLICA
<br>

Page 406 of 446

Embedded Systems and loT Design 9-66 UNIT IV

SNMP is a connectionless protocol which uses UDP as the transport protocol.


• MIBs often lack writable objects without which device configuration is not
possible sing SNMP.
• It is difficult to differentiate between configuration and state data in MIBs.
Retrieving the current configuration from a device can be difficult with SNMP.

g
Earlier versions of SNMP did not have strong security features

in
Q,13 Discuss requirement of network operator.

er
Ans. Requirements are as follows
: :

• Ease of use

e
in
Distinction between configuration and state data
Fetch configuration and state data separately

ng
Configuration of the network as a whole
Configuration transactions across devices
fE
Configuration deltas
O
Dump and restore configurations
e

Configuration database schemas


g

Comparing configurations
le

Q.14 Define modbus.


ol

Ans. : Modbus is a serial communication


protocol for use with programmable logic
C

controllers. It is typically used to transmit signals


from instrumentation and control
devices back to a main controller; or
data gathering system, for example a system
u

measures temperature
and humidity and communicates the results to a computer. that
ad

an open protocol developed by Modicon. It is

Q.15 What is CAN bus ?


iln

Ans. :
The Controlled Area Network (CAN)
runs at rates of 1 MB/s over a bus uses bit-serial transmission. CAN
m

twisted pair connection of 40 m.


also be used. The bus protocol supports An optical link can
multiple masters on the bus
Ta

Q.16 Define Ethernet.


Ans. :
Ethernet is a kind of local area
network for general purpose
of its low cost it is use as a computing. Because
network for embedded computing.
useful when PCs are used as platform. Ethernet is particularly

TECHNICAL PUBLICATIONS -
an up-thrust
for knowedge
<br>

Page 407 of 446

UNIT V

10 loT System Design

g
in
er
Syllabus

e
in
Basic building blocks ofan loT device - Raspberry Pi - Board - Linx on Raspberry Pi - Interfaces -
Programming with Python - Case Studies : Home Automation, Smart Cities, Environment and

ng
Agriculture.

Contents
fE
Blocks of an loT Device
O
10.1 Ba sic Building

10.2 Raspbery Pi
e

10.3 Raspberry Pi Interfaces


g
le

10.4 Raspberry Pi Programming with Python


ol

10.5 Home Automation


10.6 Smart Cities
C

10.7 Environment
u

10.8 Agriculture
ad
iln
m
Ta

(10- 1)
<br>

Page 408 of 446

loT System Design


Embedded Systems and loT Design 10-2

10.1 Basic Building Blocks of an loT Device


IoT devices are connected to the Internet and send information about themselves
or about their surroundings over a network.
The Internet of Things (IoT) is the network of physical objects i.e. devices, vehicles,
buildings and other items embeddedwith electronics, software, sensors and

g
network connectivity that enables these objects to collect and exchange data.

in
The Internet of Things refers to the capability of everyday devices to connect to

er
other devices and people through the existing Internet infrastructure. Devices
connect and communicate in many ways. Examples of this are smart phones that

e
interact with other smart phones vehicle - to - vehicle communication, connected

in
video cameras and connected medical devices. They are able to communicate with

ng
s consumers, collect and transmit data to companies and compile large amounts of
data for third parties.
fE
The Internet of Things refers to the set of devices and systems that interconnect
real - world sensors and actuators to the Internet. This includes many different
O
types of systems, such as :
1. Mobile devices
e

2. Smart meters and objects


g
le

3. Wearable devices including clothing, health care implants, smart watches and
fitness devices
ol

4. Internet - connected automobiles


C

5. Home automation systems, inchuding thermostats, lighting,


and home security
u

6. Other measuring sensors for weather, traffic, ocean


tides, road signals and
ad

more
Internet of Things applications require qiverse sensors and actuators. IoT
devices
iln

and services should be able to connect seamlessly and on a


plug-and-play basis.
How your device connects to the rest of the world is a
key consideration for
m

Internet of Things products.


. To work
Ta

with all features of Internet of Things, different types of


mIn on it. Devices used application must
in the IoT must support plug and play facility.
. The infrastructure
needs to support applications in finding the
things required. An
application may run anywhere, including on the things
themselves. Finding things
is not limited to the start-up time of an application.
.
IoT infrastructure has to support finding things
according to location.
The Internet of Things infrastructure allows
combinations of smart objects, sensor
network technologies and human beings, using different but interoperable
TECHNICAL PUBLICATIONS® -
an up-thrust for
knowledge
<br>

Page 409 of 446

Embedded Systems and loT Design


10-3 loT System Design

communication protocols and realises a dynamic multimodal/heterogeneous


network that can be deployed also in inaccessible or remote spaces or in cases
of
emergencies of hazardous situations.
• Network users will be humans, machines,
things and groups of them.

10.1.1 loT Device

g
in
IoT devices have unique identity and they are refer as "things" in loT. Device can
perform remote sensing, actuating and monitoring.

er
• IoT devices can exchange data between them and process
data or send to

e
centralized location for procesing and storage. Fig. 10.1.1 shows block diagram of

in
IoT device.

ng
Network Audio 7\Video Main memory
connectivity
Ethernet
Central
fEInterface
RCA video
interface
NAND / NOR
processing
O
unit HDMI
USB host DDR
AUDIO
g e
le

Interconnect bus
ol
C
u

|Input / Output Graphics


ad

Interface processing Storage interface


unit
CN
iln

MMC
SPI
SDIO
SD
m
Ta

UART

Fig. 10.1.1 Block diagram of loT device

wireless devices: Intorfs


IoT devices provide interface to various wire and
sensors, Internet connectivity
includes memory interface, 1/O intertace tor
interface, storage interface etc.

PUBLICATIONS an up-thrust for knowledge


TECHNICAL
<br>

Page 410 of 446

Embedded Systems and loT Design 10-4 loT System Design

Using sensors, loT collects various information like temperature, light intensity,
humidity, air pressure. Some application used cloud based storage. Collected
information is stored in, cloud and transmitted to other devices.
Various types of IoT devices are smart clothing, smart watch, wearable sensors,
LED lights, automobile industry etc. Fig. 10.1.2 shows loT devices.

g
Agriculture aravel
Personal and pet

in
monitoring Energy Everyday
use

er
things

e
in
Telemedicine
and Internet of Things

ng
healthcare
Building
Embedded management
mobile
M2M and
fE
wireless sensors
O
Seçurity
Smart homes and cities
e

Fig. 10.1.2 loT devices


g

:
Sensor Devices that can measure a physical quantity and convert
it into a signal,
le

which can be read and interpreted


b the microcontroller unit. These devices
consist of energy modules, power managemernt modules, RF
ol

modules and sensing


modules. Most sensors fall into 2 categories : Digital or
analog. An analog data is
C

converted to digital value that can be transmitted to the Internet.


Actuation : IoT devices can have various types of actuators
u

taking actions upon the physical entities in the vicinity


attached that allow
ad

. of the device.
Communication : Communication modules are
responsible for sending collected
data to other device or cloud based servers
iln

and receiving data from other devices.


Analysis and processing modules are
responsible for making sense of the collected
m

data.
Ta

loT Device Life Cycle :


IoT devices are generally more
like single - purpose computers.
for example, includes four steps: The first life cycle,
1. Boot up : The device loads the
firmware and starts to work as
defined.
2. Initialization : Once boot up is completed, the system
configuration, established connections, syncs reads the
up' data,
etc.
3. Operation : The device pertorms
its designed purpose continually.

TECHNICAL PUBLICATIONS® - an up-thrust


for knowledge
<br>

Page 41 I
of 446

Embedded Systems and loT Design


10- 5 loT System Design

4. Update : New firmware is installed, the device reboots and then starts to load
the new firmware.
The device should complete its previous life cycle before starting the next life cycle
every time the- firmware is updated. Eventually, the device
will be retired for
whatever reason. When it does, it reaches the end of the device life cycle called
termination.

g
in
Review Question

er
1. Explain lifecycle of an IoT device.

e
10:2 Raspberry

in
Pi

ng
A Raspberry Pi is a credit card-sized computer originally designed for education,
inspired by the 1981 BBC Micro.
fE
• Creator Eben Upton's goal was to create a low-cost device that would improve
programming skills and hardware understanding at the pre-university level.
O
The Raspberry Pi is slower than a modern laptop or desktop but is still a complete
Linux computer and can provide all the expected abilities that implies, at a
ge

low-power consumption level.


le

Versions Remarks
ol

**

Raspberry Pi l. Thea original Raspberry Pi had 256 Mb of RAM, which increased to 512 MB
C

in later revision.
• It has a 26-way GPIO connector
u
ad

Pi Zero .The Pi Zero includes the GPIO connector, but the header pins are not
soldered
iln

Raspberry Pi 2 The Raspberry Pi 2 swapped the single-core processor for a much faster
quad-core processor and increased the memory to 1 GB RAM
m
Ta

Raspberry Pi 3 The Raspberry Pi 3 changes the processor to an even more powerful 64-bit:
procesor.
t also adds Wi-Fi and bluetooth which previously needed to be added as a

USB device.
• The Raspberry Pi 3 Model B was launched in February 2016.

To get the Raspberry Pi working an SD card needs to be prepared with the Linux
operating system installed.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 412 of 446

loT System Design


Embedded Systems and loT Design 10-6

projects using this


Raspberry Pi users have made many creative and impressive
your network by
device. It can also be programmed to assist in 'housekeeping'
server, media server, DNS server etc.
functioning as NAS, LDAP server, web
• The Raspberry Pi Foundation recommends Python. Any language which will
on the Raspberry Pi : C,
compile for ARMv6 can be used. Installed by default
C++, Java, Scratch and Ruby.

g
in
10.2.1 About the Board

er
a
• Fig 10.2.1 shows the Raspberry Pi board. The Raspberry Pi does not have
separate CPU, RAM or GPU. Instead they are all squeezed into one component

e
in
called a system on Chip or SoC unit.

ng
JTAG
RCA headers
VIDEO

GPIO
OUT
fE AUDIO Status LEDS
headers OUT
O
DSIdisplay
e

connector
g
le
ol

SD card slot
C

(back of board) USB 2.0


u
ad

Micro USB power Broadcom ETHERNET OUT


(5 V1ADC) BCM 2835 only on 256 MB models
iln

ARM11 700 MHz


CSI connector
camera
m

HDMIOUT
Ta

Fig 10.2.1 (a) Raspberry Pi circuit board

Raspberry Pi is open hardware with the exception of its


primary chip, the
Broadcomm SoC which runs the main components of
the board - CPU, graphics,
memory, USB controller etc.

TECHNICAL PUBLICATIONS® - an up-thrust for


knowledge
<br>

Page 413 of 446

Embedded Systems and loT Design


10-7 loT System Design

R USB
LEDS
RCA video Audio
LAN

g
in
er
S GPIO 3

e
512 MB RAM
$ CPU and GPU

in
HDMI

ng
SD card
fE
Power
O

Fig 10.2.1 (b) Block diagram


g e

• All of these Raspberry Pi Models share the following features :


le

1. Operating systems : Raspbian RaspBMC, Arch Linux, Rise OS, OpenELEC


ol

Pidora
C

2. Video output : HDM Composite RCA


: 640x350 to 1920x1200, including 1080p, PAL and
u

3. Supported resolutions
ad

NISC standards
4. Power
source : Micro USB
iln

Description
Compornents
m

processor which is also installed in a wide


Processor •Raspberry Pi uses an ARM
Ta

variety of mobile phones.


. This a co-processor to perform
CPU is single core, however it does have
calculations
floating point
. (Synchronous Dynamic RAM).
Memory Model B Raspberry Pi has 512 MB SDRAM
programs that are currently being run in the CPU
• It store
port can provide a current upto 100mA
USB ports .Board has two USB ports. USB
possible to connect more
devices
• Using powered hub, it is

PUBLICATIONs - an up-thrust for knowledge


TECHNICAL
<br>

Page 414 of 446

10- 8 loT System Design


Embedded Systems and loT Design

HDMI •High Definition Multimedia Interface (HDMI) supports high-quality digital


Cutput
video & audio through a single cable.
• It is also possible to connect a computer monitor with a Dvi connection to
HDMI using a converter.
Composite • It support composite video output with RCA jack and also support PAL and

g
Video
Output NTSC.

in
• The TVDACpin can be used to output composite video.

er
Audio • Audio output jack is 3.5 mm.
Output

e
• This jack is used for providing audio output to old television along with the

in
RCA jack for video.

ng
GPIO Pins • Both models have a total of 26 GPIO pins,
organized into one pin header,
named the P1 header.
•The newer Raspberry Pi (model B
fE
revision 2) adds 8 more GPIO pins in a
new pin header called P5.
O
•Not all the GPIO pins are programmable. Some of them are 5.0 VDC or 3.3
VDC positive power pins, some of them are negative
e

ground pins and a few


of them are marked DNC (do not connect).
g

• The
le

Pi1
header has 17 programmable pins and the P5 header
adds 4 more.
• Fig 10.2.2 shows GPIO pin header.
ol

• Reading from various environmental sensors.


Writing output to dc motors,
C

LEDs for status.


Power Input Micro-USB connector is used for power
u

input.
ad

Status LED • It has five status LED.


CSI
.
Cafmera Serial Interface (CSI) can
be used to connect a camera
iln

Raspberry Pi. module to


SD Card Slot
m

This card is used for loading


operating system.
wwwwe
Ta

The Raspberry Pi comes with a set


of 26 exposed vertical pins on
pins are a General Purpose Input the board. These
any specific native function on /Output interface that is purposely not linked to
the Raspberry Pi board.
Instead, the GPIO pins are there
explicitly for the end user to
hardware access directly to the have low-level
board for the purposes of attaching
boards, peripherals, LCD display screens other hardware
and other hardware devices to the Pi.

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 415 of 446

Embedded Systems and loT Design 10-9 loT System Design

The status LEDs

Status Color Functions


LED

ACT Green Lights when the SD card is accessed (marked OK on earlier boards)
PWR Red Hooked up to 3.3 V power

g
in
FDX Green On if network adapter is full duplex

er
LNK Green Network activity light

100 Yellow On if the network connection is 100 Mbps

e
in
Raspberry PiP1 header
PIN # Name PIN #

ng
Name
3.3 VDC power N 5.0 VDC power
SDAO (12C)
8

SCLO (12c)
3

5
A
o
fEDNC
0V (Ground)
O
7 GPIO7 7 O
Oco TxD 15

DNC 11|9 RxD 16


e

0 GPIO 0 NGPIO1 1
g

13|
2 GPI0 2 DNC
le

3
GPIO3n 15 GPIO4 4
ol

1917
DNC GPIO5 5
C

12. MOSI DNC


21 B GPI06
u

13 MISO 6
ad

14 SCLK CEO 10
25 CE1
DNC 11
iln

Fig. 10.2.2 GPIO pin header


m

a, microUSB port and reauires a


The Raspberry Pi draws its power trom
Ta

a
microUSB-to-AC adapter. Because the Pi is a micro computer and not simply cell
use a high quality charger with
phone getting a battery topPped ort, you needto Z00 mA
a consistent 5V with at least
stable power delivery that provides
2.5 A for the Pi 3.
minimum output for older model units and

10.2.2 Linux on Raspberry Pi


systerms tor the kPl and there is an operating
There are several unix like operating
the first ARM chips.
system called RISC OS that has its orngin at tne developers of
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 416 of 446

Embedded Systems and loT Design 10- 10 loT System Design

The Raspberry Pi Foundation recommends the use of the following Linwx


Distributions
1. Debian 7 2. Raspbian 3. Arch Linux ARM 4. QtonPi
Raspbian is a free operating system based on Debian optimized for the Raspberry
Pi (RPI) hardware. working
username directory
The default command prompt on the Pi consists of

g
in
four components shown in Fig, 10.2.3.
pi@raspberrypi - $
Raspbian is the desired operating system for the

er
Raspberry Pi. In order to download and install the hostname type

e
operating system onto our Raspberry Pi; you will after

in
need Raspbian, Win32DiskImager and USB memory this
card reader. Fig. 10.2.3 Command

ng
1. Download both Raspbian
prompt
and Win32Disklmager
and save somewhere easily accessible fE
2. Plug the USB memory
card reader into your computer
O
3. Open Win32DiskImager
4. Find the location
of the image file and the memory card
g e

5. Click "Write"
le

Logging In
Now it is time to turn on our
ol

Raspberry Pi. When the memory


Ethernet cable, mouse and keyboard are card, HDMI lead,
C

plugged in, plug in the power


As soon as you do this. You screen lead.
This will be visible every should be black and filled
u

time you turn on your with white text.


raspberry pi.
ad

Wait until your screen reads


"raspberrypi login :
Username = pi (ENTERI
iln

Password = raspberry (ENTER]


m

Dcbian CHU/LinDx whcczy


sid raspberrypi tty1
COSherTUpi lng ini pi
Ta

Resssrd:
ast
Linux luin:
Tue Auy 21 21:24:50 EDT:
raspberrypi 2612 un
31.9+ 1168 PREZHPT
Ltul
The urorans included Sat Jul 14 18:56:31,
ISI,2012 armu6l
thes cxact distributionuith the Debjan GUZLinLx"sisten
terns for each progran
indiuidual filcs in 7usr/shorc/doc/×/copyright are free softuare:
arc dcscribediin
bebien GLLimx concs the:
wíth An:SOATELY NO UARRANTY,
ernilled by applicable lau. Ln
Type
the cxtrut
'tartx'to launch a
yraphical session'
birazpberrypi $

TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>

Page 417 of 446

Embedded Systems and loT Design


10- 11
loT System Design
starting the Raspbian GUI
• GUI stands for
Graphical User Interface and is a type
most common type of user interface as of operating system. It is the
it is a very 'friendly' way for people to
interact with the computer. It makes use of pictures,
graphics, icons and pointers,
hence the name 'Graphical' User Interface. Fig. 10.2.4
shows Rasbian Linux desktop

g
1. Type the line : "startx"

in
e er
in
i

ng
fE
O
.

Fig. 10.2.4 Rasbian Linus desktop


g e
le
ol
C
u

onT igurn elockin


ad

boot ieeoiAr
pdat:
iln
m
Ta

Fig. 10.2.5 First boot :


time to configure your Pi

10.2.3 Diference between Raspberry Pi is and Desktop Computers


on SD card whereas in deskto
In Raspberry Pi, operating system is installed
disk.
computer, operating system is installed in hard
own CPU and RAM.
Raspberry Pi does not have their
Processing power of Raspberry Pi is less as compared to desktop
computers.
computers
Raspberry Pi uses less power than desktop
TECHNICAL PUBLICATIONS- an up-thrust for knowledae
<br>

Page 418 of 446

Embedded Systems and loT Design 10- 12 loT System Design

10.3 Raspberry Pi Interfaces


Three types of interface is supported by Raspberry Pi.
1. Serial
• It uses serial peripherals for serial communication.

g
• Transmit (Tx) and Receive (Rx) pin is used for serial communication.

in
2. Serial Peripheral Interface (SPI)

er
SPI is a communication protocol used to transfer data between micro-computers
like the Raspberry Pi and peripheral devices. These peripheral devices may be

e
either sensors or actuators.

in
SPI uses 4 separate connections to communicate with the target device. These

ng
connections are the serial clock (CLK), Master Input Slave Output (MISO), Master
Output Slave Input (MOSI) and Chip Select (CS). fE
The clock pin sense pulses at a regular frequency, the
speed at which the
Raspberry Pi and SPI device agree to transfer data to each other.
O
For the ADC, clock pulses are sampled on their
rising edge, on the transition from
e

low to high.
g

The MISO pin is a data pin used for the master to


receive data from the ADC.
le

Data is read from the bus after every clock


pulse.
ol

The MOSI pin sends data from the Raspberry


Pi to the ADC. The ADC will take
the value of the bus on the rising edge of
C

the clock. This means the value must be


set before the clock is pulsed.
u


The Chip Select line chooses
which particular SPI device is
in use. If there are
ad

multiple SPI devices, they can all share same


the CLK, MOSI, and MISO.
The SPI has the following features :
iln

1. 16-bit shift register

2. 16-bit Receive
m

buffer register (SPIBUF) and


16-bit Receive buffer
alias register (SPIEMU) emulation
Ta

3. 16-bit Transmit
data register (SPIDATO)
selection register (SPIDAT1) and 16-bit Transmit data
and format
4. 8-bit baud clock generator
5. Serial clock (SPICLK) I/O pin
6. Slave in, master out (SPISIMO)
I/O pin
7. Slave out, master in (SPISOMI)
I/O pin
8. Multiple slave chip select (SPISCS[n])
I/O pins (4 pin mode only)

TECHNICAL PUBLICATIONS® an up-thrust


for knowledge
<br>

Page 419 of 446

Embedded Systems and loT Design


10-13 loT System Design
9. Programmable
SPI clock frequency range
10. Programmable character length (2 to
16 bits)
11. Programmable clock
phase (delay or no delay)
12. Programmable clock
polarity (high or low)
13. Interrupt capability

g
14. DMA support (read/write synchronization events)

in
15. Up to 66 MHz operation

er
Master-slave configuration of SPI :

e
in
Fig. 10.3.1 shows SPI system. SPI bus is compOsed by four signals,
namely the
Master Out Slave In (MOSI), Master In Slave Out (MISO); serial clock (SCK) and

ng
active low slave select ( \$S).
SCLK fE
MOSI
O
SPIMaster MISO SPISlave
e

SS
g
le

Fig. 10.3.1 SPI


ol

MOSI : This pin is used to transmit data out of the SPI module when it is
C

configured as a Master and receive data when it is configured as Slave.


u

MISO : This pin is used to transmit data out of the SPI module when it is
configured as a Slave and receive data when it is configured as Master.
ad

/Ss : This pin is used to output the select signal from the SPI module to another
iln

peripheral with which a data transfer is to take place when its configured as a
Master and its used as an input to receive the slave select signal when the SPI is
m

configured as Slave.
Ta

SCLK:This pin is used to output the clock with respect to which the SPI transfers
case of Slave.
data or receive clock in
SCK master device will generate a pulse and the data will be
synchronized in both
types to define sIp
master and slave devices. There are four different clock
phase may be. It must ensure
protocol, depending on what the SCK polarity and
devices compatible with each other.
these signals between the master and slave
a protocol. The clock signal is provided by the master to
SPI is Synchronous
controls when data can change and
provide synchronization. The clock signal
when it is valid for reading.
PUBLICATIONS - an up-thrust for knowledge
TECHNICAL
<br>

Page 420 of 446

loT System Design


Embedded Systems and loT Design 10-14
on the
SPI creates a data loop between two devices. Data leaving the master exits
SDO (serial data output) line. Data entering the master enters on the serial data
input, SDI line.
A clock (SCK), is generated by the master device. It controls when and how
quickly data is exchanged between the two devices.

g
SS allows a master device to control when a particular slave is being addressed.

in
This allows the possibility of having more than one slave and simplifies the

er
communications. When the SS signal goes low at a slave device, only that slave is
accessed by SPI.

e
For SPI, there are Serial Clocks (SCLK), Chip Select lines (CS), Serial Data In (SD)

in
and Serial Data Out( SDO). There is only one master, there number of slaves

ng
depend on the number of chip select lines of the master.
Synchronous operation, latch on rising or falling edge of clock, SDI on rising edge,
SDO on falling edge. It operates in 1 to 2 MHz range. fE
Master sends out clocks and chip selects. Activates the slaves
it wants to
O
communicate with.
Fig. 10.3.2 master with multiple slave interface.
g e

Master
le

Slave 1
Slave 2
MOSI
ol

MISO
C

Clock
u
ad
iln

Fig. 10.3.2 Multiple slave


interface
m

SPI data transmit


and data receive register are the main
the communication takes place elements of the SPI. When
Ta

the data on the transmit


into the shift register. register are transferred
The shift register in the master
are linked of width (8,16,32) and
by MOSI, and MISO pins to the shift register
form a distributed 16.32,64 in the slave
respectively. bit register
When the data transfer
operation needs to
registers are serially shifted be performed these 16,32,64-
eight, sixteen, thirty-two bit
clock generated by the master so that bit positions by the serial
the data can be exchanged
master and the selected slave. between the
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 42 of 446
1l

Embedded Systems and loT Design 10- 15 loT System Design

Data on the master SPI data transmit register becomes the input data for the
slave
read from the MOSI and the data read from the master SPI data receive register
was the data send from the slave from MISO.
Data on the shift registers are transferred into data receive register when the
transfer completes and this data may be read from the data receive register any
time before next transfer has completed.

g
in
3. 12C

12C is a communication protocol that the Raspberry Pi can use to speak to other

er
embedded devices (temperature sensors, displays, accelerometers, etc).

e
12C is a useful bus that allows data exchange between microcontrollers and

in
peripherals with a minimum of wiring.

ng
12C is a. two wire bus, the connections are called SDA (Serial Data) and SCL
(Serial Clock). Each 12C bus has one or more masters ( Raspberry Pi) and one or
more slave devices, like the I/O Expander. fE
As the same data and clock lines are shared between multiple slaves, we need
O
some way to choose which device to communicate with.
e

10.4 Raspberry Pi Programming with Python


g
le

General Purpose Input/Output (GPIO) is a generic pin on a chip whose behavior


can be controlled by the user at run time. The GPIO connector has a number of
ol

different types of connection :


C

1. True GPIO pins that you can use to turn LEDs on and off etc.

2. 12C interface pins that allow you to connect hardware modules with just two
u

control pins.
ad

3. SPI interface with SPI devices, a similar concept to I2C but uses a different
iln

standard.
4. Serial Rx and Tx pins for communication with serial peripherals.
m

LED with Raspberry Pi


Ta

10.4.1 Controlling
Fig 10.4.1 shows diagram of connecting LED to Raspberry Pi. The LED will
initially be off because the GPIO pins are initialized as inputs at power-on.
. Install Python 2 library Rpi.GPI0. A library that will let us control the GPIO pins.
:
Install commands
sudo apt?get update
sudo apt?get install python?dev
sudo apt?get install python?rpi.gpio
-
TECHNICAL PUBLICATIONS an up-thrust for knowiedge
<br>

Page 422 of 446

10-16 loT System Design


Embedded Systems and loT Design

g
214

in
Pi2014

Mode

er
GPIO 27 Raspherry

Pr

e
Raspbery

in
ng
GPIO 17

GPIO 4
fE GPD
O
Fig. 10.4.1 Diagram of connecting LED to Raspberry Pi
e

Simple LED Circuit is shows below :


g
le

GPIO pin
ol

Voc 3.3 V

Anode
Kw
C

200 2 Kw
200 2
u

Cathode
ad
iln

GPIO pin

(a) (b)
m

(c)

Fig. 10.4.2
Ta

Current flows from the anode (+) to


cathode (. Anode is longer
is shorter pin. pin and cathode
Open up IDLE, the Python programming
as led.py and input software and create a New file. Save
the code from the code listing. it
Pvthon to use the GPO module so we What the code does is first tell
can connect to
importing the module. the GPIO pins, by

TECHNICAL PUBLICATIONS -
an up-thrust
for knowledge
<br>

Page 423 of 446

Embedded Systems and loT Design 10- 17 loT System Design

We then import the time module so we can create a delay between commands.
We then tell the code to treat the GPIO pins as the number they are on the board
and to turn the seventh pin into an output.
We alternate between True and False so that it turns the pin on and off. Once it's
cycled a few times, it will print the message 'Done' into IDLE and finally turn off
the GPIO pins.

g
in
Pin 10... 6 Common anode
|3,8

er
A

B B C E DP

e
in
MDP

ng
D
1 7 6 4 2 10
Pin ...5

Fig. 10.4.3
fE
Import RPi.GPIO as GPIO
O
Import time
e

GPIO.setmode(GPIO.BOARD)
g

GPIO.setup(7, GPIO.0UT)
le

GPIO.output(7, True)
ol

time.sleep(1)
C

GPIO.output(7,False)
time.sleep(1)
u

GPIO.output(7,True)
ad

time.sleep(1)
GPIO.output(7,False)
iln

print'Done"
m

GPIO.cleanup()
Task 1 :
Turn LED on for 2
seconds and off for 1 second, loop forever. Code is given
Ta

below :
(In this example, we use diagram (b), ie. controlling the LED by controlling the
voltage at the anode (+)).
-import RPi.GPIO as GPIO
import time
def main( ):
)
GPIO.cleanup( numbers
GPIO.setmode(GPIO.BOARD) # to use Raspberry Pi board pin
up GPIO output channel
GPIO.setup(11, GPIO.OUT) # set
knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>

Page 424 of 446

10- 18
Design
Embedded Systemns and loT

off LED.
while True
:
11 low. Turn
#set RPi board pin
GPIO.output(11, GPIO.LOW)
high. Turn on
LED.
time.sleep(1) pin 11
GPIO.output(11, GPIO.HIGH) # set RPi board
time.sleep(2) :

main( ) way to control display


on 7-segment LED. It is most direct

g
Example : Display digit
7-seg-LED to Vcc

in
1. Connect pin 3/8 of

2. Connect the other 8 pins


to 8 GPIO pins

er
as out
3. Configure the 8 GPIO pins segments

e
: display "2". Turn on segments A, B, D, E, G and turn off
• For example 7, 6, 2, 1,

in
C, F, DP. Set A, B, D, E, G
to LOW and set C, F, DP to HIGH. Set Pin

ng
10 LOW and Set pin 4, 9, 5 HIGH (Refer
Fig. 10.4.3)

10.4.2 Interfacing an LED and Switch with fERaspberry Pi

When the switch is not pushed GPIO detects Vcc


:
(HIGH)
O
When the switch is pushed GPIO detects GND (LOW
:
e

GPIO Input Sample Code


g

import RPi. GPIO as GPIO


le

# Use the pin numbers from the ribbon cable board


GPIO.setmode (GPIO.BCM)
ol

# Set up this pin as input.


C

GPIO.setup (17, GPIO.IN)


# Check the value of the input pin
u

GPIO.input (17)
ad

# Hold down the button, run the command again. The output should be "true".
GPIO.input(17)
iln

Vçc 3.3 V
m

GPIO input S10 kQ


Ta

pin

pull up resistor

Fig. 10.4.4

TECHNICAL PUBLICATIONS® - an up-thrust


for knowledge
<br>

Page 425 of 446

Embedded Systems and loT Design


10- 19 loT System Design

10.4.3 Interfacing Light Sensor


• Unlike some other devices the Raspberry
Pi does not have any analogue inputs.
All 17 of its GPIO pins are digital. They can
output high and low levels or read
high and low levels.
For sensors that act as a variable resistor such as LDRS (Light Dependent

g
Resistors) or thermistors (temperature sensors) there is a simple solution. It allows

in
you to measure a number of levels using a single GPIO pin. In the case of a light

er
sensor this allows you to measure different light levels.
Fig. 10.4.5 shows diagram of connecting an LDR to Raspberry Pi.

e
in
ng
fE
O
UAV
ge
le
ol
C
u
ad

ETHERNET
iln
m
Ta

Fia, 10.4.5 Diagram of connecting an LDR to Raspberry PI

Following are steps


:

1. First connect pin number 1 (3v3) to the positive rail


on the breadboard.
on the breadboard.
2. Next connect pin number 6 (ground) to the ground rail
a wire go from one end to
3. Now place the LDR sensor onto the board and have
the positive rail.
- an up-thrust
TECHNICAL PUBLICATIONS for knowledge
<br>

Page 426 of 446

I01System Design
10- 20
Embedded Systems and loT Design
sensor place a wire leading back to
tho
LDR
4. On the other side of the
number 7.
Raspberry Pi. Hook this to pin
3.3 V(Pin 1)
5. Finally place the
capacitor from the wire
to the negative rail on
2.2 kS2
the breadboard. Make

g
you have the

in
SLure LDR
negative pin of the

er
capacitor in the negative -GPIO

e
rail.
C1

in
Fig. 10.4.6 shows circuit diagr 1uF
GND (Pin 6))
am for above configuration.

ng
The sequence of events :
Fig. 10.4.6 Circuit diagram for LDR
1. Set the GPIO pin as an
fE
output and set it Low. This discharges any charge in the capacitor and ensures that
O
both sides of the capacitor are 0V.
2. Set the GPIO pin as an input. This starts a flow of current through the resistors
e

and through the capacitor to ground. The voltage across the capacitor starts to rise.
g

The time it takes is proportional to the resistance of the LDR.


le

3. Monitor the GPIO pin and read its value. Increment a counter
while we wait.
ol

4. At some point the capacitor voltage will increase enough to be considered as a


C

High by the GPIO pin (approx 2v). The time taken is proportional to
the light level
seen by the LDR.
u

5. Set the GPIO pin as an output


ad

and repeat the process as required.


:
Python Code
iln

#/ust/local/bin/python
m

# Reading an analogue sensor with a single GPIO pin


Ta

import RPi.GPIO as GPIO, time

# Tell the GPIO library to use


# Broadcom GPIO references
GPIO.setmode (GPIO.BCM)

# Define function to measure charge time


:
def RCtime (PiPin)
measurement = 0

TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 427 of 446

Systems
andloT Design 10-21 loT System Design
Mted
capacitor
Discharge
# GPIO.OUT)
CPIO.Setup(PiPin,
GPIO.output(PiPin, GPIO.LOW)

time.slaep(0.1)

GPIO.setupP(PiPin,
GPIO.IN)

Count loops
until voltage across

g
high on GPIO
reads

in
# capacitor
le (GPIO.input(PiPin) == GPIO.LOW):

er
measurerment += 1

e
raturn
measurenment

in
ng
#Main program loop
while True:

print RCtime(4) # Measure timing using GPI04 fE


05 Home Automation
O
your home.
o Home automation is the automatic control of electronic devices in
e

to be controlled
These devices are connected to the Internet, which allows them
g

remotely.
le

smart homes in
O
Interconnected devices enable to intelligently monitor and control
ol

a future Internet of Things.


climate and electricity
C

Energy saving applications, for example, control indoor


Usage by employing context information
to switch off appliances (e.g., lights,
u

or stop warm water


Computers), reduce room temperature, close windows,
ad

circulation.
automation works on three levels
:
9
Home
iln

means that users can check in on their devices


Monitoring : Monitoring
app. example, someone could view their live feed
an For
m

emotely through
trom a smart security camera.
Ta

user can control these devices remotely, like


Lontrol : Control means that the
see more of a living space.
Planning a security camera to
one
: automation means setting up devices to trigger
Automation Finally, an armed security
camera
another, like having a smart siren go off whenever
detects motion.
051 Smart Lighting
save energy. Smart,
Smart coontrol
with automation signal system to
COnnected
the lights energy
- efficient LED products with
- generation
lighting is the next temperature.
additional as occupancy and
Sensors to sense things such
TECHNICAL PUBLICA TIONS-
an up-thrust for knowledge
<br>

Page 428 of 446

Embedded Systems and loT Design 10- 22 loT System Design

Smart home appliances


Smart lighting
Air conditioning
Window control
Thermostat

g
in
e er
in
Smart living

ng
Wearable devices

Fig. 10.5.1 Smart home


In automatic light control system, Light
fE
Dependent Resistor (LDR) sensor is used
to detect bright /medium
/dim /dark conditions.
O
• It is simple enough to
envision the sensors and communications
create that initial concept smarter, addition of to
e

of more adaptive lighting.


turn the lights on; if not, turn If people are present,
g

them off. Or use your smart


lighting system and tune it to phone to connect to the
le

the desired brightness level or to a


Smart lighting is considered particular color.
the one of the
ol

means of controlling main solutions for energy reduction


lighting level according to by
desired need with minimum
C

energy consumption.
Smart lighting systems utilize
u

motion and light sensors


control algorithms. for performing the
ad

The system uses


motion and light sensors
environment. There are for detecting
iln

lamps the surrounding


supply the adequate amountcontrolled with the specific lighting
of lighting required level in order to
visibility. without affecting
m

the user
Certainly the required
Ta

conditions. In clear lighting level is


strongly dependent on
weather at night
one, due to the reflection from might require more luminance the weather
the clouds. than cloudy
While during mist and
foggy weathers
as the
visibility reaches its lowest. require
On
the highest possible
lighting level,
intermediate level between clear and foggy.. Snowy weather it might
require an
During night it requires high lighting levels,
while at day
to provide guidance or turn off if the weather it needs just fade level
is clear. The
in the yard is affected by the above conditions. lighting concentration

TECHNICAL PUBLICATIONS - an up-thrust


for knowledge
<br>

Page 429 of 446

Embedded Systems and loT Design loT System Design


10-23

10.5.2 Smart Appliances


The role and scope of smart appliances in the home (Washer, dryer, refrigerato,
dishwasher, fridge, freezer, air conditioner, vacuum cleaner and so on) is on the
increase with the market being estimated to have a year on year compound
growth of slightly over 15 %.

g
Connecting everyday objects to the internet is an essential element of the
IoT.

in
to communicate over
Some appliance suppliers use a low power wireless network

er
such as bluetooth, whilst others utilise the existing higher powered Wi-Fi network
a is in place
used for a tablet or computer wireless connectivity. Once network

e
user and
objects can populate the home environment and communicate with the

in
each other.

ng
remote commands and change its behaviour
The ability of an object to respond to
new Hive heating thermostat or a Sky+ bOx.
makes it an active device, such as the fE
• Where the remote object has no ability to respond to remote control requests then
some fixed cameras, microphones or temperature
O
it is considered passive as with
sensors.
e

to detect person entering or


IR Sensor It will be activated in the automated mode
:
g

a counter based on that. If the counter show there


coming out of the room and set
le

is a person inside it will light


up the room automatically and turn on the AC
ol

reading.
depending upon the temperature
occupancy, glass breakage, door and window
C

Sensors provide data about motion,


water leaks, light intensity, temperature, energy consumption, camera,
openings,
u

insertion or removal.
and even appliance plug
ad

or adjust settings on appliances, furnaces, air


Controllers turn power on and off
pumps, water heaters, lighting, home
conditioners, space heaters, fans, pool
iln

door locks, and plug loads.


theatres, music, motorized blinds,
sensors and controllers should use
m

• To be deemed intelligent, an appliance's


communication.
internet protocol
Ta

can keep track of the items stored and send updates to the
Smart refrigerators
on stock.
users when an item is low on a local
allow user to search video and movies from the Internet
Smart TV
schedule, fetch news and other things from the Internet.
storage drive, search TV
is the professional open source middle-ware for an Internet of
OpenRemote own user interface and
Integrate any ddevice or protocol, and design your
Things. sync to the controller, and control with this
automation. Use our online designer,
app.

TECHNICAL PUBLICATIONS- an up-thrust for knowledge


<br>

Page 430 of 446

10- 24 loT System Design


Embedded Systems and loT Design

OpenRemote is a state of the art


open source software platform for building
control and automation.
OpenRemote allows for designing a fully customizable building
and home control
soiution without the need to actually write code.

g
10.5.3 Intrusion Detection

in
Intrusion Detection System (IDS) includes both hardware and software

er
mechanisms and IDS is responsible for identifying malicious activities by
monitoring network environment and system.

e
in
• The purpose of home intrusion detection system is to detect intrusions using
sensors and raise alerts, if necessary.

ng
With the help of Light dependent resistor and PIR motion sensor, it detect the
motions in the room. If a motion is detected, system capture the image with the
fE
help of a webCam and store locally. Now the alerts are sent to the user with the
captured image.
O
• Fig. 10.5.2 shows block diagram of intrusion detection.

-5e
g e
le
ol
C
u
ad
iln

Fig. 10.5.2 Block diagram of intrusion detection


m

• To detect any form of


intrusion in restricted areas -and report it immediately,
Ta

following concept is used.


1. A PIR sensor is
required to detect the presence of any humarn
room. being in the
2. An RFID is required to
validate the presence of the person in the room
tallying his identity with those in the database. by
3. A camera is required to click
the picture of the room and send it via email as
an alarm.
4. An internet connection is required to
register all these movements on a website
so that it can be accessed
from any place and any device.
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>

Page 43 l of 446

Embedded Systems and loT Design 10- 25 loT System Design

The different input / output devices are controlled using TCP/IP over the
IEEE 802.11 standard protocol. Data being gathered from sensors, such as PIR
sensors, temperature sensors, IR transmitter and receiver is being processed on
micro - controller as a server.
• Passive Infrared Sensor (PIR) Sensor : PIR sensor is an electronic sernsing device

g
that senses infrared (IR) light emitted from entities in its field of view and used to

in
detect motion in its range. It is activated only in the security mode to detect any

er
unwanted motion at the entrance. If any unwanted movement is detected then it
will signal the microcontroller to take necessary steps.

e
in
Alarm : It will only be activated in the security mode when some intruder is
detected by the PIR motion sensor.

ng
Cloud controlled intrusion detection is possible by using location aware services.
fE
Here geo- location of each node is independently detected and stored in the
cloud.
O
Some intrusion detection system uses UPnP technology. It is based on image
processing to recognize the intrusion.
g e

10.5.4: Smoke for Gas Detection


le

on the buzzer
Smoke or gas detector sensor which detects the smoke and turns
ol

page.
alarm and all these are update on the web
C

sense the presence


MO2 is a semiconductor type sensor, which can appropriately
propane and other hydrocarbon.
u

of smoke, LPG, methane, butane,


ad

resistance of
When it comes in contact with the gas to be monitored, the electrical
to to the situation.
the sensor decreases; enabling the, microcontroller respond
iln

gas in the air it outputs its


When it detects the concentration of combustible
sensor can measure concentrations of flammable
reading as an analog voltage. The
m

20 to 50 °C
gas of 300 to 10,000 ppm. The sensor can operate at temperatures from
Ta

150 mA at 5 V.
and consumes less than
voltage level as output. The more
The MO-2 smoke sensor reports smoke by the
MQ - 2 also has a built-in
smoke is there, the greater the voltage output. The
to smoke.
potentiometer to adjust the sensitivity
one can change how sensitive it is to snoke, so
By adjusting the potentiometer,
it will give in relation
there is a form of calibrating it to adjust how much voltage
to the smoke it is exposed to.

TECHNICAL PUBLICATIONs - an up-thrust for knowledge


<br>

Page 432 of 446

loT System Deslgn


Design 10- 26
Embedded Systems and loT

10.6 Smart Cities nearly 60 milion every year, In


number of urban residents is growing by be living in cities by
The population will
percent of the world's
addition, more than 60
2050. worlds land will consume
occupying just 2 percent of the
• As a result, people cities of 1 million
resources. Moreover, more than 100

g
about three-quarters of its
next 10 years.

in
people will be built in the Netherlands, has developed a
city of Amsterdam, the

er
Over the past decade, the developing, and testing numerous.connected
envisioning,
vision for collaborating,

e
could pave the way to a smarter, greener urban environment.
that

in
solutions
Fig. 10.6.1 shows concept of smart
city.

ng
Smart industry Smart grid
fE
O
Smart
e

health
g
le
ol

adoad
C

Internet of
uees Things Smart
u
ad

waste
iln

Smart parking management


m
Ta

Smart traffic
Fig. 10.6.1 Smart city
• Smart city includes :
1. Smarter management of city infrastructure
using big data analytics
2. Collaboration across multiple and disparate
agencies using cdoud technologe
-
3. Real time data collection, enabling
quick response
using mobile technologies.
TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>

Page 433 of 446

Embedded Systems and loT Design 10- 27 loT System Design

4. Enhanced security: Improved public safety and law enforcement, and


more efficient emergency response.
5. Better ity planning improved schematics, project management and delivery
6. Networked utilities smart metering and
grid management.
7. Building developments more automation, and better management and security.

g
• With smart city applications producing continuous large data from heterogeneous

in
sources, existing relational database technologies are inadequate to handle such

er
huge amounts of data given the limited processing speed and the significant

e
storage expansion cost.

in
To address this problem, big data processing technologies, which are based on
distributed data management and parallel processing., have provided enabling

ng
platforms for data repositories, distributed processing and interactive data
visualization. fE
10.6.1 Smart Parking
O
a space is a
Traffic congestion is major problem in big cities. Searching for parking
routine (and often frustrating) activity for many people in cities around the world.
e

• After finding parking space to the driver, he parks the vehicle, it maybe spend
g

to pay the
small amount of time to looking for a city council parking attendant
le

parking fees.
ol

use of some IOT supportable


The smart parking system is designed by making
C

boards etc.
hardware's such as raspberry pi, auridino
available parking
Smart parking systems typically obtains information about
u

- to place vehicles
spaces in a particular geographic area and process is real time
ad

at available positions.
low-cost sensors, real-time data
iln

collection, and
It involves using to reserve
mobile-phone-enabled automated payment Systems that allow people a
will likely find spot.
m

parking in advance or very accurately predict where they


car emissions in urban
• When deployed as a system, smart parking thus reduces
Ta

centers by reducing the need tor people to needlessly circle city blocks searching
for parking.
. It alsÓ permits cities to carefully manage their parkng supply smart parking helns
one on diving n urban areas; finding empty parking
of the biggest problems
illegal parking.
.Spaces and controlling
can be accessed by drivers from smart phones, tables.
Smart parking application
parking slot, to detect whether the slot is empty or
Sensor is used for each
occupied.
PUBLICATIONs® an up-thrust for knowledge
TECHNICAL
<br>

Page 434 of 446

Embedded Systems and loT Design 10-28 loT System Design

Local controller collect the information and send to server using Internet.
Fig. 10.6.2 shows process specification for smart parking IoT system.

Read sensor

g
in
er
Empty

e
Check slot

in
ng
Occupied Store empty slot

Store occupied slot fE


O
g e

Database
le

Fig. 10.6.2 Process specification for smart


parking loT system
ol

Each parking slot contains the sensor and it reads at


regular intervals. Sensor
C

sends the status information to local processing centre.


Fig. 10.6.2 includes four layers : a sensing,
u

networking, middleware and


application layer. (See Fig. 10.6.3 on next page).
ad

Sensing layer defines a platform where sensor


devices are embedded into the
parking lot to detect car presence/absence, and RFID
iln

devices located at the


parking gates and strategic points of the parking are
on a unique mapping between RFID tags
used to identify cars based
m

and car.
Networking Layer : TCP/P over Ethernet
Ta

for connecting the gateway to


parking server and database and Internet access the
for remote access to the smart
parking system from outside.
Middleware layer hosts different databases
and associated servers and manages all
of the software intelligence provided
by the smart parking system to
smart services to users by enabling provide
communication between the application
where services are requested and the layer
lower layers where smart devices are
embedded into the parking lot to provide smart
services..

TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>

Page 435 of 446

Design 10- 29 loT System Design


Embedded Systems and loT

Client Devices

Application

g
in
er
Micro
cloud

e
in
Web server

ng
Middleware

Database
fE
O
g e
le

Networking
ol

Wireless
C
u
ad

Free spot Occupied spot


iln
m

Sensing
Ta

Parking lot

Fig. 10.6.3
The application layer is the layer where the different services are defined and
provided to different users. Client devices have been connected via the TCP/IP
Protocol to a parking database.

TECHNICAL PUBLICATIONS - an up-thrust for knowledge


<br>

Page 436 of 446

loT System Design


10- 30
Embedded Systems and loT Design

integrating into the car detection system sources f


Parking availability status by status of
on parking spots, which are controlled by actuators to inform of the
light
e.g, for occupied, green for empty, yellow for reserved and
a parking spot
:
red
blue for out of service.
• Remote availability checking using the Internet and/or
the GSM network to check

g
system.
in real time the availability of the smart parking

in
are able to provide profits for both customers and
The data of smart parking lots
on road sensors
merchant's daily lives in the smart cities. This service works based

er
and intelligent displays which lead drivers to the best path for parking
in the city.

e
in
10.6.2 Smart Lighting

ng
The street lighting is one of the largest energy expenses for a city. The street light
section comprises of all the light lamps in an area with current sensors and RF
fE
module. N street lights of this section communicates with 1local controller unit
wirelessly through RF module (Zigbee). N local controller unit communicates
with main server through IoT due to its global coverage area.
O
Smart light infrastructure is the backbone of the IoT in smart cities. Smart and
wireless street light luminaries can act as service gateways for other street level
g e

IoT devices.
le

Smart street lights are intelligent lights that gather dynamic data i.e. data that
keep changing dynamically by time, through some sensors and generate required
ol

information for the request claimed by a citizen on road.


C

• Smart street light saves energy by


sensing the surrounding through their sensors
expecting some other sensor in some other device.
u

10.6.3 Smart Roads


ad

Sensor is installed on road to


provides road traffic condition, travel
iln

estimation, congestion and accident. time


m

Reliability Safety
Ta

Freedom Smart Security


roads

Modernity
Comfort
Fig. 10.6.4 Smart
. Sensor collect this information
roads characteristics
and stored on the central database
This information helps for solving using cloud.
traffic congestion, making safe
road condition upto date. driving, keeping

TECHNICAL PUBLICATIONS - an up-thrust


for knowledge
<br>

Page 437 of 446

Embedded Systems and loT Design 10- 31 loT System Design

User can access the information from the cloud. User also get real time
information.
Real timne traffic maps can be obtained to enable smooth flow. Traffic can be
reduced with systems that detect alternate routes. User get timely information so
they can locate a traffic free road, saving time and fuel. This information can
reduce traffic jams and pollution improves the quality of life.

g
in
10.7 Environment

er
10:71 Weather Monitoring

e
Remote weather monitoring system which measures the following weather

in
parameters :

ng
1. Daylight Using a photodiode as a wired binary switch sensor
:

2. Humidity : Using a wired analog humidity sensor


fE sensor via wireless
3. Temperature: Using a digital bit-stream temperature
medium employing wireless RF modules.
O
• The sensors are the miniaturized electronic devices used to measure the physical
sensors for monitoring the weather
and environmental parameters. By using the
e

conditions, the results will be accurate and the entire system will be faster and less
g

power consuming.
le

to the
The system monitors the weather conditions and updates the information
ol

page is to maintain the


web page. The reason behind sernding the data to the web
a can be known anywhere in the world. The
C

weather conditions of particular place


weather condition is also displayed on the systems LCD.
u

10:7.2 Air Poilution Monitoring


ad

The rapid growth in infrastructure and industrial plants creating environmental


iln

issues like climate change, malfunctioning and pollution has greatly influenced for
the need of an efficient, cheap, operationally adaptable and smart monitoring
m

systems.
Ta

• Air monitoring sensor placed throughout the city. Sensor send periodic
measurement of air quality data to gateway.
a
the
Gatewav sends information to network where the data is analyzed by
can identify. zones of Concern and provide
application server which
recommendations.
Application server provides information regarding
air quality level throughout the
pattern via computer or mobile device.
city, including alert and pollution
monitoring system.
Fig. 10.7.1shows air pollution
- an up-thrust for knowledge
TECHNICAL PUBLICATIONS
<br>

Page 438 of 446

loT System Design


Embedded Systems and loT Design 10-32

Environmental parameters to be monitor

Sensor

g
in
Threshold Duration Alarm or

er
value (Time) LED

e
in
Sensor data acquisition and Decision making

ng
Intelligent environment
fE
O
g e

Internet
User end
le

system with
internet
ol

connection.
C

Cloud
u

Fig. 10.7.1
ad

"The MQ series of gas sensors


utilizes a small heater
iln

chemical sensor these sensors are inside with an electro


sensitive to a range
temperature. of gasses are used at room
m

MO135 alcohol sensor


is a Sno2 with a
lower conductivity of clean
Ta

target explosive gas exists, then air. When the


more along with the sensor's conductivity increases more
the gas concentration rising levels. increasing
By using simple
electronic circuits,
it convert the charge
correspond output signal of gas concerntration. of conductivity to
10.7.3 Noise Pollution Monitoring
Noisepollution is a major problem
behaviour, well-being, productivity in urban environments,
and health. affecting human

TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>

Page 439 of 446

Embedded Systems and loT Design 10- 33 loT System Design

• Environmental noise, caused by traffic, industrial and recreational activities is one


of the main local environmental problems in world and the source of an increasing
number of complaints from the public.
Experts estimated that 80 million people suffer from noise levels considered as
unacceptable and 170 million people experience serious annoyance during daytime

g
in the European Union.

in
Nowadays assessments of environmental noise in urban areas are mainly carried

er
out by officials who collect data at a sparse set of locations, e.g. close to roads,
railways, airports and industrial estates, by setting up sound level meters during a

e
in
short period of time.
Propagation models are then used to generate noise maps by extrapolating local

ng
measurements to wider areas.
Recent years have seen an increasing interest in wireless sensor networks for
fE
environmental monitoring and urban sensing. A wireless sensor network (WSN)
is a wireless network consisting of spatially distributed autonomous devices using
O
sensors to cooperatively monitor environmental conditions, such as temperature,
sound, air pressure or air quality, at different locations.
e

The sensors interact with microcontroller which processes this data and transmits
g

it over internet. This allows authorities to monitor air pollution in different areas
le

and take action against it. Also authorities can keep a watch on the noise pollution
ol

near schools, hospitals and no honking areas, and if system detects air quality and
noise issues it alerts authorities so they can take measures to control the issue.
C

10.74 Forest Fire Detection


u
ad

Forest fires cost millions of dollars in damages and claim many human lives every
year. Apart from preventive measures, early detection and suppression of fires is
iln

the only way to minimize the damages and casualties.


The forecast forest fires cannot be detected by the satellites fire spreads
m

uncontrollable. The wireless sensor network can detect and forecast forest fire
more perfectly and accurately than the traditional satellite-based detection
Ta

approach. This method is used to minimize the loss of forests, wild animals and
people in the forest fire.
response in
The most critical issue in a forest fire detection system is immediate
of
order to minimize the scale of the disaster. This requires constant surveillance
the forest area.
Current medium and large-scale fire surveillance systems scan.
do nt
accomplish
Therefore, there is
timely detection due to low resolution and long period of
high.
a need for a scalable solution that can provide real time fire detection with
(WSN) can
accuracy. We believe that Wireless Sensor Networks potentially
provide such solution.
TECHNICAL PUBLICATIONS- an up-thrust for knowledge
<br>

Page 440 of 446

Embedded Systems and loT Design 10-34 loT System Design

Network is composed of numerous and ubiquitous micro sensor nodes which have
the ability to communicate and calculate. These nodes can monitor sense and
collect information of different environments and various monitoring objects
cooperatively.
A large number of sensor nodes are deployed in a forest to detect fire. Those are
mainly cluster heads, sink, wind sensor and managing node.

g
A few wind sensor nodes are manually connected to the sink via wired networks

in
to detect wind speed. Sensor nodes collect measured data for example,

er
environment temperature, relative humidity and smoke.
A sensor node is commonly composed of a sensor module, a processing module, a

e
wireless communication module and a power module. The Temperature Sensor

in
used is Thermostat.

ng
The main need for thermostat is to detect forest fire. The advantage of using
thermostat is that it helps in knowing the temperature variations in several areas

temperature variations of those areas.


fE
of the forest, whereas the fire sensor will detect only fire and will not give
the
O
10:7.5River Floods Detection
River flood causes damage to the natural and human resources. If there
e

is heavy
rainfall, then river level is increases and flow of water rate is also
g

increases.
Floods ends with the loss of numerous lives and leaves the flooded area
le

with
huge destruction of property every year, especially the rage of flood. in the poor
ol

and developing countries is most noticeable, where people are the


victim of the
natural clemency.
C

During the rainy season floods are a constant problem.


This is becoming
u

particularly critical in towns or cities surrounded by large rivers.


Before the effects
ad

of flooding can be alleviated, there is a need for precise


and complete information
in advance, about the current level of the rivers.
iln

Early warning of the floods can be given by monitoring water


level and flow rate.
IoT based river monitoring uses sensor to
monitor water level and flow rate.
m

Depending upon river area, number of sensor is installed.


• Various sensors collect
Ta

the information and send to the local


processing center.
Processing sensor process the data and stored on the cloud.
Flood monitoring system send alerts when
sudden increases in water level and
flow rate of water.
• Local computation can
be used to provide timely warnings to local
and a combination of local and remote computation can stakeholders
sensor network to maintain optimal inform adaptation of the
performance.
The wireless sensor network for flood
warning is capable of integrating with
remote fixed-network grids for computationally-intensive
and performs on-site flood modeling by organizing itself as flood modeling purposes
a local grid.
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>

Page 44lof 446

Embedded Systems and loT Design 10- 35 loT System Design

10.8 Agriculture
10.8.1 Machine Diagnosis and Prognosis
• Machine fault diagnostic and prognostic techniques have been the considerable
subjects of condition-based maintenance system in the recent time due to the

g
potential advantages that could be gained from reducing downtime, decreasing

in
maintenance costs and increasing machine availability.

er
A failure in industrial equipment results in not only the loss of productivity but
also timely services to customers and may even lead to safety and environmental

e
in
problems.
IoT play an important role in both diagnosis and prognosis. Critical manufacturing

ng
processes and equipment must be continuously monitoring for any variations or
malfunctions. A slight shift in performance can affect overall product quality or
fE
manufacturing equipment health.
With group of sensing nodes monitoring various manufacturing equipments and
O
processes and transmitting data in periodic manner, situations may arise where the
engineer might want to query data from some specific nodes to estimate current
e

status of particular process or equipment.


g

. There can be situation of unforeseen malfunctioning or variations beyond


le

prescribed tolerance bands. A mechanism is hence required to define tolerance


ol

bands for each sensing module. When measurements at particular node exceed the
C

tolerance, the node must breach the periodic cycle to send an alarm about the
emergency.
u

new
Case Based Reasoning (CBR) is normally used method to find solution to
ad

problems based on previous experience.


CBR is an effective method for problem solving for quantitative mathematical
iln

model i.e. machine diagnostic and prognosis.


m

10.8:2 Indoor Air Quality Monitoring


Ta

. To work in healthy environment in factory, indoor air quality is monitored.


to workers.
Factory provides safety environment
creates problem for
Generating harmful gases (CO, NO and NO2) in the factory,
quality of room
workers, To avoid this, sensor is used to monitor/sense the air
air quality.
Various gas sensor are used by factory for controling
measured at different locations. Anything serious happen or
Air quality is
sensor send alert to authority and it also
threshold level of air quality is changed,
give the alarm.

TECHNICAL PUBLICATIONS- an up-thrust for knowiedae


<br>

Page 442 of 446

UNIT V: IoT SYSTEM DESIGN

Two MARKS QUESTIONS WITH ANSWERS

g
in
Q.1 List the typical loT device.

er
Ans. : Typical IoT devices are CPU, GPU, memory interface, USB host, Ethernet, I/o
interface like SPI, UART and CAN, storage interface like MMC and SD.

e
in
Q.2 List various loT communication model.
:
Ans. IoT communication models are request/response model,

ng
publish/subscribe
model, push/pull model and exclusive pair model.
Q.3 What is Python ? fE
Ans. : Python is an object oriented, high - level programming language with
O
integrated dynamic semantics primarily for web and app
development.
Q.4 List and explain features of Python.
e

Ans. : Features
g

:
le

1. Python is a simple and minimalistic language


2. Easy to learn
ol

3. Free and open source


C

4. Python supports procedure -


oriented programming as well as
object - oriented
u

programming
5. Extensive libraries :
ad

The Python standard library is


6. Embeddable : You can huge indeed
embed Python within your
C/C+t programs to give
iln

scripting capabilities for your program's users.


Q.5 List the benefits of Python.
m

:
Ans. Python can be used to develop prototypes:
Ta

Python allows for a more


productive coding environment
languages like C# and Java. than massive
Python powers Django, a
complete and open sorce
framework. web application
Most automation,
data mining and big
data platforms rely on
Python supports modules Python.
and packages, which encourages
modularity and code reuse. program

- 36)
(10
<br>

Page 443 of 446

Embedded Systems and loT Design 10- 37 UNIT V

Q.6 What is Raspberry pi ?


Ans. : Raspberry Pi is the name of a series of single board computers made by the
Raspberry Pi Foundation. The original Pi had a single - core 700 MHz CPU and just
256 MB RAM and the latest model has a quad - core 1.4 GHz CPU with 1 GB RAM.
What are the different Raspberry pi model types ?

g
Q.7

in
Ans. :
The raspberry Pi models are of two types :
1. Model A (Introduced later as a hardware - reduced model).

er
2. Model B (Introduced first and is the full hardware model).

e
in
Q.8 Explain difference between Model A and Model B of Raspberry Pi.

ng
Ans. :

Parameters Model A fE Model B

GPU type VideoCore IV VideoCore IV


O
USB port 1

Memory 256 MB 512 MB


e

Ethernet port No Ethernet port 10/100 Ethernet


g
le

SoC type Broadcom BCM2837BO


*****
Broadcom BCM2837B0
Number of cores 4
ol

Type It is hardware-reduced model It is full hardware model


C

Q.9 What is GND in GPIO ?


u

Ans. :
GND means ground pins. Ground GPIO pins are physical numbers 6, 9, 14, 20,
ad

25, 30, 34 and 39.


Define Raspberry Pi hardware.
iln

Q.10
Ans. :
Raspberry Pi hardware includes ARM processor, GPU, RAM and USB port.
m

Q.11 What is Raspbian s ?


Ta

Ans. :
Raspbian is a free operating system based on Debian optimized for the Raspberry
Pi hardware.
• An operating system is the set of basic programs and utilities that make vour
Raspberry Pi run.
However, Raspbian provides more than a pure OS It comes with over 35.000
:
- a easy installation
packages, pre compiled software bundled in nice format for
on your Raspberry Pi.

TECHNICAL PUBLICATIONS an up-thrust for knowledge


<br>

Page 444 of 446

Embedded Systems and loT Design 10-38 UNIT V

• As Raspbian is a Linux operating system it has good security features, has


excellent networking capabilities.
-
Raspbian is highly optimized for the Raspberry Pi line's low performance ARM
CPUs.
Q.12 What is smart parking ?

g
Ans. : Smart parking systems typically obtains information about available parking

in
spaces in a particular geographic area and process is real - time to place vehicles at

er
available positions. The smart parking system is designed by making use of some loT
supportable hardwares such as raspberry pi, uridino boards etc.

e
When urban centers are labeled as smart ?

in
Q.13

Ans. : Utban centers are labeled as smart when they leverage technologies to improve

ng
the management of common resources, such as street space or waste collection and
improve the quality of urban life for citizens. fE
Q.14 What are consequence for smart parking use cases ?
O
Ans. : Consequence are as follows :
Contributes to pollution
e

• Increases traffic incidents


g
le

Causes motorist frustration


What is smart irrigation system ?
ol

Q.15
:
Ans. The smart irrigation system was developed to
C

optimize water use for


agricultural crops. The system has a distributed wireless network of soil -
moisture and
temperature sensors placed in the root zone of the plants.
u

Wireless Transmitter Unit


(WTU) is comprised of a soil moisture sensor, a temperature sensor,
ad

a
a microcontroller,
RF transceiver and power source. Several can
WTUs be incorporated in field to form
a distributed network of sensors.
iln
m
Ta

TECHNICAL PUBLICATIONSs - an
up-thrust for knowledge
<br>

Page 445 of 446

QUESTION PAPER
SOLVED MODELNew Syllabus)

Embedded Systems
[As Per
and loT Design
Semester - VI (ECE)
:
[Maxinum Marks 100

g
Time : Three Hours]
Answer ALL Questions

in
=
PART A (10 x 2 20 Marks)
-

er
DPTR .of 8051 or what is
a. function of DPTR ?
Explain the 16-bit registers

e
Q.1 -
(Refer Two Marks Q.16 of Unit I)

in
mention its use.
Q.2 Define SBUF register in 8051 and -

ng
(Refer Two Marks Q.80 of Unit I)
processor.
Q.3 State the interrupts supported by ARM
-
fE
(Refer Two Marks Q.27 of Unit II)
O
techniques.
Q.4 State the principle of basic compilation
- II)
(Refer Two Marks Q.37 of Unit
e

-
an accelerator ? (Refer Two Marks Q.12 of Unit III)
g

Q.5 What is
le

element ?
Q.6 What is meant the by processing -
III)
(Refer Two Marks Q.7 of Unit
ol

-
? (Refer Two Marks Q.6 of Unit
IV)
What is M2M communication
C

Q.7 -
Q.11 of Unit IV)
a.8 What is NETCONF ? (Refer Two Marks -)
Unit
u

system ? (Refer Two Marks Q.15 of


Q.9 What is smart irrigation
ad

-
GPIO ? (Refer Two Marks Q.9 of Unit y)
Q.10 What is GND in
- = 65 Marks)
PART B (5 x 13
iln

1.3)
of program counter. (Refer section
Explain the function
[6]
Q.11 a) )
m

Explain interrupt structure of 8051 in detail. (Refer section 3.7)


i)
Ta

OR
detail.
Explain the different addressing modes in 8051 in
b) i) [8]
(Refer section 2.1)
Discuss the serial interface of 8051. (Refer section 3.6) [5]
i)
bottom-up design approaches. (Refer section 4.1) [6]
Q.12 a) ) Describe top-down and
using IVT.
ii) State the steps involbed in handling interrupts
(Refer section 6.2) [7]

(M - 1)
<br>

Page 446 of 446

Embedded Systems and loT Design Solved Model Question


M-2 PaDer

OR

b) )Explain ARM core data flow model with a neat diagram.


(Refer section 5.3) l6]
ii) Explain in detail about the compilation process in high-level languages.
(Refer section 7.3) I7]

g
Q.13 a) What is distributed embedded systems ? Explain software and hardware

in
architecture of distributed embedded systems. (Refer section 8.6) [13]

er
OR

e
b) i) Explain rate monotonic scheduling. (Refer section 8.4.2)

in
[6]
i) Define real-time system. Explain the classification
of real-time systems.

ng
(Refer section 8.1)
I7]
Q.14 a) fE
i) Define IoT. Explain characteristics, advantages and disadvantages
of IoT.
(Refer section 9.1)
[6]
O
i) Explain loT enabling technology. (Refer section 9.4)
e

OR
g

b) i) What is M2M ? Explain architecture


and comiponents of M2M.
le

(Refer section 9.6)


[6]
ol

ii) Write short note on IoT protocols.


(Refer section 9.10) [71
C

Q.15 a) i) What is home automation ? Explain three levels


of home automation.
(Refer section 10.5)
u

[6]
ti) Write short note on Raspberry
ad

Pi.(Refer section 10.2) 17]


OR
iln

b) i) Explain loT application in agriculture.


(Refer section 10.8)
[6]
m

i) Explain concept of smart parking. DiscusS process


specification for smart
parking oT system. (Refer section 10.6.1)
Ta

PART C - (1 x 15 = 15 (7]
Marks)
Q.16 a) Describe the different modes operatiom
of of timers in 8051.
(Refer section 3.4)
[15)
OR
b) Explain in detail the design steps
of modern tran controller with
diagrams. (Refer section 4.2) suitable
[15]

DO0
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge

You might also like