Embedded System and IOT Design Technical Book 1
Embedded System and IOT Design Technical Book 1
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
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
Accelerator. (Chapter - 8)
ad
iln
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)
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.3.1
1.3.1.1 and
A B Registers 1-10
u
.
1
- 11
1.3.1.4 8051 Flag Bits/PSW Registers
1-12
m
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...
Page 3 of 446
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.3.2
...2-7
ad
.2-9
2.4 Byte Level Logical Instructions
m
2-10
2.5 Arithmetic Instructions...
..2-13
Ta
Page 4 of 446
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
2- 27
C
of Bank2.
Program 2.10.10 Division of two 8-bit numbers. 2-27
:
u
.. 2-27
to its equivalent BCD.
m
Program 2.10.14
:
Implementing a BCD multiply using MUL and 2- 29
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
(vi)
<br>
Page 5 of 446
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 -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-50
3.6.1 Operating Modes for Serial Port.
3-52
iln
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
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.1 Requirements... 4- 13
le
4.2.3 DCCComponents 4- 15
C
-
Chapter -5 ARM Processor (5-1) to (5 60)
5.1 Introduction.. 5-2
5.2 Preliminaries. 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
Memory Organization
.. .5-22
5.3.5
m
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
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
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
(xi)
<br>
Page 9 of 446
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.1 .....
le
UNIT III
u
...
8.1
-
Structure of a Real time System 8-2
iln
(xii)
<br>
Page 10 of 446
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.1
Network Abstractions 8-32
ol
8.6.2
8.6.3 Hardware and Software Architectures... 8-34
C
UNIT IV
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.5.1
ad
(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.10.1 MQTT..
9 - 58
...
9.10.3 Modbus
ad
...
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)
(xv)
<br>
Page 13 of 446
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
10- 30
10.6.2 Smart Lighting
le
10- 31
10.7 Environment.
C
10.7.1 10 31
Weather Monitoring.
u
(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
Dec.-10,11,14,16,18, 19,
Marks 16
ol
May-11, Marks 16
u
(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
devices to
read/write memory (RAM), decoders, drivers, number of input/output
ad
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.
Page 16 of 446
Embedded Systems and loT Design 1-3 Microcontrollers for an Embedded System - 8051
Registers
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
Page 17 of 446
-
Embedded Systems and loT Design 1-4 Microcontrollers for an Embeddod System 8051
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
multifunctioned.
C
Table 1.1.1
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
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
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
instructions also
ol
4
Fixed forimat instructions Variable format instructions
u
Page 20 of 446
Embedded Systems and loT Design 1-7 Microcontrollers for an Embedded System - 8051
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.
of microcontrollers.
le
8051 microcontroller.
8751 microcontrollers. Let us see the features of
ad
1. 4096 bytes on
-
chip program memory.
128 bytes on chip data memory.
-
2.
m
Page 21 of 446
-
1-8 Microcontrollers for an Embedded System 8051
Embedded Systems and loT Design
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.
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
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
ReviewQestion
m
.....
e*****
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
are
Central Processor Unit (CPU) It monitors and controls all operations that
:
le
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
consisting of 8 registers
constitute 4 register banks (Bank 0-Bank 3) with each bank
the internal RAM.
Ta
Page 23 of 446
-
1-10 Microcontrollers for an Embedded System 8051
mbedded Systems and loT Design
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
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
PSW SP IP IE
Ta
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).
Page 24 of 446
Embedded Systems and loT Design 1-11 Microcontrollers for an Embedded System - 8051
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.
The 8051 has a 16-bit program counter. It is used to hold the address of memory
g
B B6 B B4 B B B, Bo
ad
CY AC FO RS1 RSO OV P
iln
Fig. 1.3.4
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
TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
<br>
Page 25 of 446
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
:
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
bits in PSW.
Ta
Page 26 of 446
Embedded Systems and loT Design 1-13 Microcontrollers for an Embedded System - 8051
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
Page 27 of 446
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
OB8H 8051
X
XX 00000
"IP Interrupt Priority Control
g
OA8H 8051
O
XX0 0000
"IE Interrupt Enable Control
ol
8052 0X000.000
C
TLO
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
Page 28 of 446
Embedded Systems and loT Design 1-15 Microcontrollers for an Embedded System - 8051
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
On-chip RAM
u
08 09
ad
09
07 08 Data
SP 07
08
06 SP SP SP+1 07
Stack pointer
iln
m
Data 2 09
Data 1
09
08
SP Data 2 08 Read 07
Data 3 07 SPSP-1
Stack pointer
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
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
DIP
P3.2 (INTO)
12 29 PSEN
C
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
GND 20 21
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.
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
Power-supply Pins Vcc (Pin 40) and Vss (Pin 20) 8051 operates on d.c. power
:
C
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
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.
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
13. Mention the size of DPTR and stack pointer in 8051 microcontroller. AU Máy-11, Marks 2
u
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
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
(SFRS)
FFFFH
le
FFH
Accessible by
ol
Accessible by
indirect direct
Upper addressing addressing
C
7FH rnemory
ad
Accessible by
Lower direct & indirect
128 addressing
iln
0000H
m
Fig. 14.1
Ta
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.
Page 34 of 446
Embedded Systems and loT Design 1-21 Microcontrollers for an Embedded System- 8051
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
For example, bit address 4EH refers bit 6 of the byte address 29H.
ol
The RAM area above bit addressable area from 30H to 7FH is called general purpose
u
program. It is accessed
altered after fabrication. This is used to store final version of the
Ta
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 :
Page 35 of 446
-
Embedded Systems and loT Design 1-22 Microcontrollers for an Embedded System 8051
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
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
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
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
ALE
ol
C
PSEN
u
ad
INSTR Ag -A7
Ao -Ay IN
PORT O
iln
Ag -A15 Ay -A15
PORT 2
m
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
The Table 1.5.1 explains the instructions to access external ROM/program memory.
g
le
Mnemonic Operation
ol
MOVC A, @
Page 38 of 446
Embedded Systems and loT Design 1-25 Microcontrollers for an Embedded System - 805:
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.
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
INSTR IN
FROM PCL
ad
FROM RI OR DPL
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 @DPTR, A
Copy data from A to the external address in DPTR.
Table 1.5.2
Page 40 of 446
Embedded Systems and loT Design 1-27 Microcontrollers for an Embedded System - 8051
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
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
08 09
09
ad
07 08
SP Data 08
06 SP 07
Stack pointer SP +SP+1 07
iln
m
09 09
Data 1
Data 2
08
SP Data 2 08 Read
07 SP+ SP-1 07
Data 3
Stack pointer
Fig. 1.6.1
Page 43 of 446
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
2.2
Dec.-07,08,11,16, 19,
g
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
(2- 1)
<br>
Page 45 of 446
Embedded Systems and loT Design 2-2 Addressing Modes and Instruction Set of 8051
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
Memory
C
u
ad
Destination register
iln
Address of memory
Data from within the instruction
selected memory
m
location
Ta
Page 46 of 446
Embedded Systems and loT Design 2-3 Addressing Modes and Instruction Set of 8051
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
addressing mode.
ol
iS
constant can be incorporated in the Data specified
Ta
inthe instruction
nstruction. Sign " indicates it is a
immediate addressing mode.
Page 47 of 446
Embedded Systems and loT Design 2-4 Addressing Modes and Instruction Set of 8051
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
;sixteen uses
bit Data pointer, and the sum as an address from which
;byte to be moved into accumulator
m
Page 48 of 446
Embedded Systems and loT Design 2-5 Addressing Modes and Instruction Set of 8051
Review Questions
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
Arithmetic Instructions.
C
Review Questions
ad
FAU May-10
1. List the different types of 8051 instructions.
set.
Give the classification of 8051 instruction
iln
2.
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.
Page 49 of 446
Embedded Systems and loT Design 2-6 Addressing Modes and Instruction Set of 8051
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
:
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
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
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
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:
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
:
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
The top of the internal RAM, ie. it's end address is 7FH. So next PUSHes after
m
Page 52 of 446
Embedded Systems and loT Design 2-9 Addressing Modes and Instruction Set of 8051
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
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
Table 2.3.4
Important Points to Remember in Exchange Instructions
iln
When XCHD A, @ Ri instruction is executed, the upper nibble of A and the upper
Ta
Review Questions
-AU: Dec.-07
3. Mention the I/O instructions of 8051 microcontroller. FAU Dec-11, Marks'2
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
Masked bits
u
+ 1 1 1 1
0000 Setting pattern
1. 1
11
m
XXX X Result
Set bits
Ta
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
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
ORL A, Rn
Example: ORL R2: Logically ORs the contents of A and R2
A,
Page 55 of 446
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
stores result in A.
le
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
:
CLR Bytes : 1 Cycles
A
Clear Accumulator :1
m
Description The Accumulator is cleared (all bits set on zero). No flags are affected.
Ta
Page 56 of 446
Embedded Systemns and loT Desian 2-13 Addressing Modes and Instruction Set of 8051
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
1 Byte 1 Cycle 2
INCDPTR Increment Data Pointer by
u
: 1/2 : 1
DEC <byte>: Decrement Bytes Cycles
ad
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
Page 57 of 446
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
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.
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
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
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
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
: =
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
Review Questions
Ta
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
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
PSW DO D0-D7
TCON 88 88-3F
SCON 98 98-9F
Page 61 of 446
Embedded Systems and loT Design 2- 18 Addressing Modes and Instruction Set of 8051
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
Bytes : 2 Cycles:2
Description : If the Boolean value of the source bit is a logical 0 then clear the carry flag;
ol
the addressed bit is used as the source value, but the source complement not of
affected. No flags are affected. bit itself is
u
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
Page 62 of 446
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
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
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.
Page 63 of 446
Embedded Systems and loT Design 2-20 Addressing Modes and Instruction Set of 8051
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
7 4 3
Higher nibble| Lower nibble
m
Ta
Table 2.7.1
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 :
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
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.
Page 65 of 446
Embedded Systems and loT Design 2- 22 Addressing Modes and Instruction Set of 8051
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
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
Description : If the carry flag is set branch to the address indicated; otherwise proceed with the
iln
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.
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
Table 2.8.1
ol
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
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
Page 67 of 446
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
Review Questions
C
AU Dec-09
2. Explain about the instruction DJNZ.
ad
AUSjJune-09
2.9 Time Delay for 8051
iln
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.
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
12 = 1.085 usec
le
T=
11.0592x106
ol
1
Delay :
MOV R1, #30
u
HERE :
DJNZ R1, HERE 2
ad
1
NOP
1
NOP
iln
1
RET
m
30 times.
Here, (2x 30) indicates that the instruction DJNZ R1, HERE is executed
- 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+
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)
MOVR3, #90H
g
MOV R3, R2
Program 2.10.4: Add two 8-bit numbers.
C
MOV A, RO -
:(A) (RO)
; 1's complement A
CPL A
ADD A, #01 ;Add 1 to it to get 2's complement
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
ese
:
Get the first number in A
ad
MOV A,#90
MOV B,#20 ;
Get the second number in B A
DIV AB
Program 2.10.11: Muutiply two &-bit numbers.
m
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.
Page 71 of 446
: 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
:
Flowchart :
Program
ol
Start
MOV DPTR, #1234H ;Load first number
C
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
Stop
Page 72 of 446
Embedded Systems and loT Design 2- 29 Addressing Modes and Instruction Set of 8051
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
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
Page 73 of 446
Embedded Systems and loT Design 2-30 Addressing Modes and Instruction Set of ans
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
Max. number
?
C
Max. number-Number
No
u
ad
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
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
memory
MOVX @DPTR, A ;
locations ] Decrement counter 2
u
;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
Page 75 of 446
80s
Embedded Systems and loT Design Addressing Modes and Instruction Set of
2-32
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
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.
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
2200H
End
2202H = 52H 2203H =89H 2204H = 3EH
9AH + 52H + 89H + 3EH = 1B3H
iln
Result
2300H B3H Lower byte 2301H = 01H Higher byte
m
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]
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
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
result No
Is
=
Count 0
le
ol
Yes
C
End
iln
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
Page 78 of 446
Embedded Systems and loT Design 2-35 Addressing Modes and Instruction Set of 8051
Start
Initiaize cOunter = 10
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
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
Page 80 of 446
UNIT I
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.4 8051 Timer Modes and Programming Dec.-07,11, 15,
le
.
May-10,11,12,14,17, Marks 16
ol
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
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
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
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
Page 83 of 446
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
A: May-18, Marks 13
ol
AU:May-13
Let us see important points for
u
W
oVco
ad
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.
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 :
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
Example 3.2.3 Write an ALP to receive input from port P1.5 and if it is high then an output
iln
Solution:
m
Page 85 of 446
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
Table 3.2.1 gives the information about the size of the data variable
and its value range.
g
Data type
le
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
unsigned int 16
20 to 65535
Ta
sfr 8 4 0 to 255
sfr16 16 0 to 65535
Page 86 of 446
Embedded Systems and loT Design 3-7 8051 VO Ports, Timers, Serial Ports and Interrupts
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.
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
NOT CPL A
ad
OR
RRA A = A >>n
Shift right by n-bits
Ta
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;
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
Pl=0xFF / hex] I
ad
Pl=0x00
NOP / [wait for some /
m
NOP / time)/
Ta
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)
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
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
LED++; /"increment P2 *
Page 90 of 446
Embedded Systems and loT Design 3-11 8051 VO Ports, Timers, Serial Ports and Interrupts
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
mybyte=PO;
if(mybyte<50)
C
msec and
200, wait for 250 msec and send the data to port P2. otherwise wait for 150
m
#inciude <reg51.h>
void Delay (unsigned int);
void main (void)
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
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
{
ol
while(1)
{
C
#include <reg51.h>.
sbit portbit = P0^5;
Ta
Page 92 of 446
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
void main(void)
u
PO=0x55;
P2=0x55;
iln
P2=0xAA;
Delay(250);
Ta
unsigned int i, j:
for (i=0; i<count; i++)
for (j=0; j<1200; j++)
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
else
tempbit=1;
u
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)
Page 94 of 446
Embedded Systems and loT Design 3-15 8051 VO Ports, Timers, Serial Ports and Interupts
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
Solution:
ol
#include <reg51.h>
void DELAY (unsigned int):
C
Wsensor = 1
while(Dsensor=1 Wsensor==1)
m
=~siren ;
/ invert the status of siren"/
siren
Ta
DELAY(150);
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
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)
Solution:
le
#include <reg51.h>
ol
while(1)
ad
Table 3.2.3
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
Solution:
Procedure
to unpacked BCD, and then
m
process :
Key pressed 5 6
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>
Page 97 of 446
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
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
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.
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
Program
le
#include <reg51.h>
ol
Abyte = 0XFB;
i=0;
iln
do
m
Q=Abyte/10; / divide by 10 */
R[i]=Abyte%10; * find remainder and save it */
Ta
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
Ignoring carry in the sum, result is not zero and hence we can say that data is
C
corrupted.
u
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*/
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
Solution:
#include <reg51.h>
sbit outbit = P2^0;
sbit AMSB = ACC^7;
void main (void)
outbit = AMSB;
TECHNICAL PUBLICATIONS- an up-thrust for
knowledge
<br>
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;
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
continuously with a 250 ms delay. Use SFR keyword to declare the port addresses.
ad
Solution:
#include reg51.h>
iln
{ while
(1)/* Repeat continuously */
Ta
-
TECHNICAL PUBLICA TIONS an up-thrust for knowledge
<br>
Embedded Systems and loT Design 3-24 8051 VO Ports, Timers, Serial Ports and Intemupts
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
unsigned int i, j:
for (i = 0; i < count; i++)
C
:
Solution
#include<reg51.h>
m
void main(void)
Ta
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
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
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
Embedded Systems and loT Design 3-26 8051 VO Ports, Timers, Serial Ports and Intemupts
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
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
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.
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
3. All these
There are four modes of timer, mode 0, mode 1, mode 2 and mode
Ta
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
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
in mode 1.
m
THO TLO
Ta
TRO
GATE(TMOD.3) Control
INTO PIN
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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 :
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
TRO
ol
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
TR1
GATE(TMOD.7) Control
INTT PIN
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
TLO
OSC +12 TFO Interrupt
(8 Bits)
cT=0
TRO
GATE(TMOD.3) THO
Control.
(8 Bits)
INTO PIN
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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 :
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
(8 Bits) TFO
CIT=0
g
le
TRO
ol
INTO =1
Timer0 control logic when GATE =0 and THO
C
(8 Bits)
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
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
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
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
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
seperate conters.
Mode 3 Establishes TL and TH as two
mnodes
iln
Review Questions
Ta
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>
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
TO(P3.4)
iln
THO TLO
c/T=1 (8 Bits) (8 Bits) TFO Interrupt
m
Ta
TRO
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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
TH1 TL1
T1(P3.5) TE1 Interrupt
cIT=1 (8 Bits) (8 Bits)
iln
m
TR1
=0 and INT1 =1
Ta
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
Embedded Systems and loT Design 3-36 8051 V/O Ports, Timers, Serial Ports and Interrupts
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
TRO
u
THO
(8 Bits)
iln
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>
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
DA A BCD conversion]
C
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
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
:Wait for
BACK: JNB TF1, BACK timer rolls over
CLR TR1 :Stop timer 1
C
Example 3.5:5 Explain the steps to program timers in model and write an 8051 program to
iln
Solution: Square
MOV TMOD, #01 ;Timer 0 mode 1
Ta
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
MOVTHO, #FFH :
Load THO = FFH
;toggle P1.5
ol
CPL P1.5
MOV RO, #21H ;Load count in RO
C
BACK :
ACALL Delay
; 1ms
DJNZ RO, BACK
u
SJMP HERE
ad
DELAY :
SETB TRO ; start tmer 0
CLR TEFO
; Return
RET
Ta
TECHNICAL PUBLICATIONs
- an up-thrust for knowledge
<br>
Embedded Systems and loT Design 3-40 8051 VO Ports, Timers, Serial Ports and Interrupts
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
1 MHz
ad
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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
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
CLR TFO
RET
m
wave of frequency
Write an assembly language program to generate square
a
Example 3.5.11
Ta
knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>
Embedded Systems and loT Design 3-42 8051 VO Ports, Timers, Serial Ports and Intemupts
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
Solution:
le
#include <reg51.h>
ol
{
ad
void DELAY)
unsigned char i;
for(i=0; i<20; i++)
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
Embedded Systems and loT Design 3-43 8051 I/O Ports, Tinmers, Serial Ports and InterTupts
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
void main(void)
le
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
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
TR1=1; /* turn on T1 *l
while(TF1==0); * wait for TF1 to roll over */
u
T= 12/12 MHz=1 us
m
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
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
TMOD=0x01;
do
Ta
TL0=0x78;
THO=0xXEC;
TRO=1;
while(TFO==0);
TRO=0;
TF0=0;
c=c-1;
while(cl=0);
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
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
sbit T1 = P3^5;
g
void main(void)
{
le
TMOD=0x60;
TH1=0; /* set count to 0 */
C
do
{
iln
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
Embedded Systems and loT Design 3-47 8051 WO Ports. Timers. Serial Ports and Interrupts
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
#include <reg51.h>
ol
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>
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 main(void)
le
TO=1;
TMOD=0x06; /* TO, mode 2,counter */
C
while(TF0==0);
Time(val);
iln
val+ +;
TRO=0; /* stop timer */
m
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.
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
#include <reg51.h>
sbit mnybit = P2 ^ 1;
C
while (1)
iln
Embedded Systems and loT Design 3-50 8051 WO Ports, Timers, Serial Ports and
Interrupts
else
{
TLO = 48H; /*Load FF48H*/
THO = FFH;
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
SBUF is RxD
(P3.0) SBUF
ol
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
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.
UART mode.
Embedded Systems and loT Design 3-52 8051 VO Ports, Timers, Serial Ports and Interrupts
7 6 5 4 3 2 1
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
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
(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
(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
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.
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
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
2 (Auto-Reload).
For this purpose, Timer is used in mode
1
m
Kx Oscillator frequency
Ta
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
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
For this purpose, Timer 2 must be used in the baud rate gernerating mode. If Timer 2
g
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
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>
Embedded Systems and loT.Design 3- 55 8051 VO Ports, Timers, Seial Ports and InteTupts
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
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
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
;Make SMOD =1
ORL PCON, #8OH
MOV TH1, #FDH
:Load count
- an up-thrust for knowedae
TECHNICAL PUBLICATIONS
<br>
Embedded Systems and loT Design 3-56 8051 VO Ports, Timers, Serial Ports and Intemun.
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
ACALL TRANS
MOV A, #"E"
ol
transfer "E"
ACALL TRANS
C
ACALL TRANS
MOVA,#"O" itransfer "O"
iln
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.
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
7.
le
SPECIAATI
Solution :
u
SETB TR1
HERE:
:
wait for character receive completely
m
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
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
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
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
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
T IN T2
g
connector
RS 2320C
ol
OUT
T, IN T,
C
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
TMOD= Ox20;
TH1 = 0XFD;
SCON = 0x50;
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
TMOD = 0x02;
THO = Ox72; * THO =-184 */
C
Embedded Systems and loT Design 8051 WO Ports, Timers, Serial Ports and Interrupts
3- 61
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
SCON = 0x50;
TRO = 1;
ol
{
Obit = Ibit: * send received bit to bit P2.0 */
ad
}
iln
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
Embedded Systems and loT Design 3-62 8051 VO Ports, Timers, Serial Ports and Interrunte
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
/* start timer 0 */
while(1)
le
ol
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
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;
Embedded Systems and loT Design 3- 63 8051 /O Ports, Timers, Serial Ports and Interrupts
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).
50 usec
=- 46
g
#inciude <reg51.h>
C
sbit SW = P1^2:
P2^1:
=
ST
sbit
u
1
void timer 0 (void) interrupt
{
/* toggle pin */
iln
Swave= Swave;
}
void serial 0( interrupt 4
m
if (TI =
Ta
=
1)
else
{
RI = 0; /* clear interrupt */
}
bedded Systems and loT Design 3-64 8051 /O Ports, Timers, Serial Ports and Intemupte
void main ()
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
:
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
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
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
software.
Fig. 3.7.1 MCS-51 interrupt structure
le
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
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
0 1 1 0 0 1
all interrupts.
CLR IE.7 Clear EA bit in the IE register
iln
Solution:
Ta
Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and nterrupts
3- 67
(MSB) (LSB)
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
timer/counter 0.
le
PX0 IP.0 Exterrnal interrupt 0 Priority control bit. Set/cleared by software to specify
interrupts for INTO.
ol
request is serviced.
simultaneously, an internal polling sequence determines which
ad
:
polling sequence, as follows
m
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.
Embedded Systems and loT Design 3-68 8051 I/O Ports, Timers, Serial Ports
and Inteupts
Review Questions
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
(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
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
nt 9600.
Assume that XTAL = 12 MHz. Set the baud rate
ol
Solution:
#include <reg51.h>
C
1
void timer0 () interrupt
ad
{
SWAVE =~SWAVE; /* toggle pin P0.1 */
iln
{
/* increment counter */
cnt++; count value on port P2 */
/* display
Ta
P2 = nt;
void main(void)
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
the interrupt.
Since the external interrupt pins are sampled once
each machine cycle, an input high
u
at least one machine cycle, and then hold it pin high tor
low for at least one machine cycle to ensure
iln
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
Embedded Systems and loT Design 8051 VO Ports, Timers, Serial Ports and Intemupts
3-71
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
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>
Embedded Systems and loT Design 3-72 8051 I/O Ports, Timers, Serial Ports and IInterrupts
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
Solution :
le
ORG 0000H
LJMP MAIN
ol
ORG 0023H
JNB TI, SKIP ; If TI
is low goto SKIP
u
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
TECHNICAL PUBLICATIONS
an up-thrust for
knowledge
<br>
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).
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
1.3.1)
details of PSW of 8051. (Refer section ÅU May-10, 14
ad
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>
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
:
Ans. EA : It stands for external access. When the EA pin is connected to Vcc,
ol
Accumulator B Register
Program Status Word.
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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
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
memory
Ans. : The 8051 has a 16-bit program counter. It is used to hold the address of
ad
Q.23
over microprocessor are
:
Ans. :
The advantages of microcontroller
m
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
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
section 1.3.1)
Q.30 Justify your choice AU : Dec.-10
ad
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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.
AU Déc.16
le
AU May-05
Q44 Give the PSW setting for making register bank 2 as default register bank in
C
Q45 What is the operation carried out when 8051 executes the instruction MOVC A,
ad
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>
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
Ans. :
Single instruction, which clears the most significant
bit of B register of 8051,
ol
MOV A, #3CH
ad
:
Ans A =3C
R4 = 66
m
A = 24
Ta
Ans. :
MOV PSw, #10
MOVA, RO
3-79
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
Q.65 What does the mnemonics "LCALL" and "ACALL" stand for ?
O
AUS Dec.12
(Refer section 2.8.3)
Q.66
AUDec12
g
2.10.24) AU péc-i2
to the accumulator 10 times. (Refer example :
AU May-11
XRL A, direct ? (Refer section 2.4)
ad
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.
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
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
Ans.:
The interrupts are:
C
000BH
External interrupt 1 IE1 0013H
iln
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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
UNIT II
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
Marks 16
le
April -14,
ol
C
u
ad
iln
m
Ta
(4 - 1)
<br>
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
TECHNICAL PUBLICATIONS -
an up-thrust for
knowledge
<br>
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
Specification : The specification outlines how the system should behave and
ad
to meet the
outlines how these components interact and work together
Ta
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
level.
le
2
Progression Designers break down the Individual components are
system into smaller gradually integrated to form
ol
components integrate
ad
seamlessly.
4
Advantage It offers structure and clarity, Allows for early testing and
iln
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.
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
to consider
When designing and specifying an embedded system, it's essential
ol
Nonfunctional requirements
ad
requirements.
Table 4.1.2 lists the typical nonfunctional
iln
Nonfunctional requirements
m
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
Input / output handling : Define how inputs are processed and what outputs
are generated.
u
systems.
. User interfaces:Detail user interface elements and interaction
workflows.
m
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>
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
Entries Requirements
C
Sr. No.
Purpose
map for driving use. description of the system
iln
-
TECHNICAL PUBLICATIONs an up-thrust for knowledge
<br>
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
requirement.
le
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
• Fig. 4.1.3 shows a block diagram of sample system architecture for the moving
C
receiver engine
m
Ta
User interface
Database
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
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
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
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>
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.
8. Analyse the requirements for designing a GPS moving map in the embedded system design proces.
g
AU Dec.-16,. Marks 8
le
13. Discuss the designing hardware and software components for embedded systems.
ad
• 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>
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
4.2.1 Requirements
ad
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
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
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
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
:
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
8: Bits are set at 01 to show that this instruction provides both speed
ad
-7
Bits
and direction information.
iln
frequently. Packets
DCC standard recommends that command units send packets
Ta
(Cab)
Command station
g
Motor
in
"Cab bus"
e er
Booster
Decoder
in
ng
fE
O
e
control and sound effects. Throttles transmit these commands to the command
le
:
Booster The booster receives commands
from the command station, amplifies
ad
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
These subsystems each have their own internal structure. The basic relationship
iln
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.
Pig. 4.2.5 UML COllaboration diagram for major subsystems of the train controller
system
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
console
u
ad
1
1
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>
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
a It
•
Train class : This class appears to represent the overall functionality of train.
ad
signals to
Motor interface class This class defines how to generate analog
:
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
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>
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
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
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
detected.
A " panel-active " behavior returns true
m
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>
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
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
-
As showWn in the Fig. 4.2.14, behaviour
Ta
Idle
panel _active( )
new settings()
send command()
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
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
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
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>
• 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
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>
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
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
ARM Assembly
5.5 Implementation of C Language Statements using
le
ol
C
CPFCIAAN
u
ad
COPY
iln
FOR
m
Ta
(5-1)
<br>
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
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>
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
Data
diagram for the computer with CPU
le
IR
Harvard Architecture. It has Address
PC
ol
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
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.
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
be used.
• In CISC, there are many
instructions that support memory
C
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
of 446
Page 192
:
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
can occur
• With fixed fields, opcode decoding and register operands addressing
ol
simultaneously.
unit.
C
etc.
RISCs are :
ARM, ATMEL, 8051 family, AVR, MIPS, PIC
Examples of
iln
Varies
1
Instruction size Fixed
1, 2,3 or 4
bytes
2 Instruction length 4 bytes
More
3
of 446
Page 193
ARM Processor
Embedded Systems and loT Design 5-6
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
Or less
pipelined.
le
Simple.
18. Examples ARM, 8051, ATMEL, AVR,
etc.
Intel X86, Motorola 68O00
u
series.
ad
Review Questions
iln
TECHNICAL PUBLICATIONS -
an up-thrust for
knowledge
<br>
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
are
Assembler directives They, often referred to simply as "directives,"
:
le
memory
assembly process. Directives are typically used to define data, specify
u
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
15 operand register
C
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
Bits 28 - 31These bits are put aside for the condition field.
:
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
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
-
The names used for should consist of
uppercase and lowercase,
Ta
-
TECHNICAL PUBLICATIONS an up-thrust for knowledge
<br>
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
TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>
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
DATA
instruction (machine instructions) can be placed in this
ol
area.
C
Table 5.2.2
Ta
Examples :
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
arbitrary.
DCW and DCWU Allocates one or more
halfwords of memory, aligned on
u
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
Example :
ol
CODE16 Directive
u
as Thumb instructions.
iln
Review: Questions
m
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
area.
With advances in modern VLSI technology,
it became possible to build additional
m
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
Data
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
• The ARM
implementation of the ARM.
ad
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>
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
B buses respectively,
performs the operation and stores
internal C bus in destination register, the computed result via
C
Address register
This holds the address generated
iln
Barrel
. Theshifter
contents of the Rm register
Ta
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>
The processor core continues the execution of instruction. Only when an exception
or interrupt occurs, the normal execution flow is changed.
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
system.
from an invalid memory location,
ol
an
: instruction or data is fetched
4. Abort If
an abort exception will be generated.
C
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
r15 pc
ol
C
cpsr
spsr fiq spsr irq spsrsvc spsr undef spsrabt
u
ad
TECHNICAL PUBLICATIONs
an up-thrust for knowledge
<br>
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
cases about its use. Usually, the instruction is unpredictable if r15 is used in
ad
- 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
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
information. mode,
Each exception mode also
has a saved program status
u
exception occurs.
Note User mode and system
mnode do not
exception modes. All have an SPSR, because
iln
2cv UNDEFINED
8 7 6 5 4
Condition
FT Mode
Functions
flags
Interrupt Processor
masks mode
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
• This bit gives the state of the core. The.state of the core determines which
ol
instruction set is active when the processor is in ARM state, Thumb state and
u
:
Bits and 7 (Interrupt Masks)
on the ARM processor core:
There are two interrupts available
iln
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
0 otherwise.
Bit 31 (Negative flag, N)
C
• 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
TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>
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
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
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
memory organization
Fig. 5.3.2 ARM memory with a "litle-endian'
Page 21 I of 446
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.
addressing mode)
In the register indirect addressing
g
Example :
ol
Review:Questions
u
ad
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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.
Example : Assume that R1 = 0x2000 0100 and locations Ox2000 0100 through
le
as
After execution of the above instruction, register R2 is loaded with OxB0122510,
u
Memory
Ta
Ox2000 0104
Ox2000 0103OxBO
Ox2000 0102 Ox12
Ox2000 0101 Ox25
Ox2000 0100 Ox10
PUBLICATIONS® - an
TECHNICAL up-thrust for knowledge
<br>
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
Ox25
Ox2000 0100
le
Ox10
ol
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
TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>
Memory
g
Ox2000 0104
in
Ox2000 0103 OxBO
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
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
R4 Ox10
Ox50 OXAC Ox20
m
Memory
Ta
Ox2000 0104
Ox2000 0103
0x2000 0102
Ox2000 0101 OXAC
Ox2000 0100 0x20
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
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
Ox2000 0106 contents 0x10, 0x25, 0x12, OxBO, Ox34, Ox58, OxA2, respectively.
u
Memory
Ta
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
Memory
Ox2000 0106 OXA2
iln
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
subtracted from the base register (Rx) to access data at an offset known at compile
le
=
Example : Assume that R3 = 0x200000FC and R4 0x1050AC20.
C
After execution of the above instruction, 4 bytes contents of R4 register are stored in
ad
Memory
Ta
Ox2000 0104
Ox2000 0103 Ox10
Ox2000
01000x20
Fig. 5.4.9 Executing the STR instruction with immediate offset
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 0102
Ox2000 0101
ol
Ox2000 0100
Ox2000 00FF
C
Memory
Ox2000 0106
m
Ox2000 0105
Ox2000 0104
Ta
Ox2000 0103
Ox2000 0102 Ox10
Ox2000 0101 Ox50
Ox2000 0100 OxAC
Ox2000 0OFF Ox20
(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] ;
at a
LDR R3, [R1, R2]:Load value
le
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
knowledge
PUBLICATIONS - an up-thrust for
TECHNICAL
<br>
Page 22 l of 446
• 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
ReviewO
Questions
u
instructions.
2. Explain. the load/store
instructions with immediate
3. Explain the load/store value as the offset.
iln
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
*****
respectively.
g
le
ADD instruction
C
immediate value.
ad
Examples:
ADD R1, R2, #0x35 ;R1 = R2 + 35 (in hex)
iln
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.
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
numbers
AREA P_2, CODE, READONLY
le
ENTRY
ol
R2 = 0x1000FFFF
ADC R4, R4, #0 =
:R4 1, increments and carry = 1
ad
R4 since carry
is 1,
END
iln
P 3, CODE, READONLY
ENTRY
Ta
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
• Examples :
- 35 (in hex)
C
SUBS instruction
; -
= Rn Op2 and update flags
Syntax : SUBS Rd, Rn, Op2 Rd are
iln
Examples :
Ta
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
AREA P
6, CODE, READONLY
ENTRY
ol
END
-1+ 0x34 - Ox12 - 1 +0 = 0x21
m
Ox80000000 Ox80000000
Ta
TECHNICAL PUBLICATIONs -
an up-thrust for knowledge
<br>
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
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
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>
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
and R4 = 0x FFFFFFFE
ad
:
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>
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
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
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.
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
instruction is usually
operand. used to mask certain
bits of the
C
Examples:
AND R1, R2, #0x65 ;R1 = R2 ANDed 65 (in hex)
u
;R2= R1
ANDed with 0x0F = 0000 1001
0x09 Ox09
ANDS instruction
m
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
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
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
Page 23 l of 446
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?
No | Result N
of positions before it enters the ALU.
iln
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>
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
:
LSR Logical Shift Right
C
u
Carry
00 0
ad
flag
iln
m
31
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
Example: Assume C = 0
ol
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
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>
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
Branches allow us to jump to another code segment. This is useful when we need
ad
• 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.
:
ARM Processor
Embedded Systems and loT Design 5-48
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
Table 5.4.4 shows the conditions under which the branch instructions are executed.
C
execution
ad
C
set
same
Ta
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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
Solution:
ol
ENTRY
Sum=0
LDR RO,=100
:
RO = 100, initialize counter
u
-
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
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
1 Z
If Rn = Op2 : C= 1 and Z
ad
=1
If Rrn <
Op2 : C= 0 and Z = 0
iln
Solution :
Ta
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
=
End
decision.
ad
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
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
INPORT EQU0x30000000
le
TECHNICAL PUBLICATIONs
- an
up-thrust for knowledge
<br>
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
address.
le
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
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
Sign or
directon bt
fE
O
e
Program counter
g
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>
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
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
ADR r4,a ;
Get address for 0
LDR r1,[r4] ;Load value of a
m
TECHNICAL PUBLICATIONS® -
an up-thrust for knowledge
<br>
else Z = 5;
. Two code blocks are used in the implementation :
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
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
:
has the following form
Solution:The switch statement in
C
Ta
switch (test)
{
case 0:
.. break;
...
case 1: break;
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
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
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>
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>
UNIT II
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>
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
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.
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
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
PUBLICATIONS® - an
TECHNICAL up-thrust for knowledge
<br>
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
;
location
of I/0 device
C
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
Page 25 of 4461l
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
status
commands, managing data registers and continuously checking the device's
ol
an
slower than the CPU. They might require many CPU cycles to complete
u
busy-wait I/0.
Solution:
m
:
The device has two registers
data to the device.
Ta
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:
has been
so that the device is after the character has been read
g
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>
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 acknowledge
C
Data
register
iln
IIO Device
m
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.
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
*******
increases. system.
u
Solution:
When an input interrupt occurs, it signifies that the input device is
ready with a
m
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.
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
request
• The CPU implements interrupts by continuously monitoring the interrupt
each instruction.
iln
• to
Counter (PC). Instead, it redirects the PC
instruction pointed to by the Program
of. the interrupt
Ta
TECHNICAL PUBLICATIONS
- an up-thrust for knowledage
<br>
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
TECHNICAL PUBLICATIONS®
- an up-thrust for
knowledge
<br>
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
inherently know which specific device triggered the interrupt. The handler checks
the status or conditions of the connected devices through polling to determine
iln
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
TECHNICAL
PUBLICATIONS - an up-thrust for knowledge
<br>
g
A
in
e er
in
ng
6 fE
O
8
e
g
9
le
ol
|10 B
C
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
TECHNICAL PUBLICATIONS
- an up-thrust for
knowledge
<br>
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
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
flexibility in
connecting hardware devices and software routines.
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.
is specific instruction
SWI instruction. that causes an exception
ad
Software interrupts :
These are typically
system routines. For reserved to call privileged
example - an SWI instruction. operating
m
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
current instruction.
Up to 20 cycles to complete the
le
handling state.
Twocycles to enter the interrupt
C
u
Review Questions
ad
?
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
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
-
• Like any
other ARM instruction, SWI can be
executed, it initiates the executed conditionally. When SWI is
transition of the CPU into
iln
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
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
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>
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>
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-1)
<br>
Embedded Systems and loT Design 7-2 Program Design and Analysis
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.
Fig. 7.1.1 shows a simple basic block in C. In this basic block, the variable x has
le
W = p+ q;
C
X = r- S;
u
W =p-I;
ad
y = X + s;
Z = y + t;
iln
Z = y + t;
Fig. 7.1.2 Basic block in single assignment form
Desian
Embedded Systems and loT 7-3 Program Design and Analysis
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
on the program.
ol
more
possible to represent variable by
are
iln
Embedded Systems and loT Design 7-4 Program Design and Analysis
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
C code
CDFG
Ta
Fig. 7.1.5
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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
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
TECHNICAL PUBLICATIONS-
an up-thrust for knowledge
<br>
Embedded Systems and loT Design 7-6 Program Design and Analysis
Compiler.
g
in
er
Assembly language program
e
in
Assembler
ng
Object code fE
O
Linker Object: library routine
g e
le
Loader
u
Execution
ad
Main memory
iln
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
addresses.
ol
7.21 Assembler
C
a
specific memory
allowing programmers to write code without worrying about
iln
locations. :
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
ORG 100
label1 SUB r3,A
C
LDR r0,[r3]
label2 ADR r3,B
u
LDR r1,(r4]
ad
Solution :
. The ORG tells us to
set the PLC value to 100. Because
the ORG statement is a
m
TECHNICAL PUBLICATIONs
- an
up-thrust for knowledge
<br>
Embedded Systems and loT Design 7-9 Program Design and Analysis
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
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>
Embedded Systems and loT Design 7-10 Program Design and Analysis
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
mathematical calculations.
After the assembly process, you
have multiple object files,
u
• The linker
combines these object files
references between different into a single, executable programn.
modules and ensures It resolves
iln
addresses to functions
locations in the final executable. and variables, determining
It calculates memory offsets their
Ta
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
various over
In embedded computing systems, you often need fine-grained control
aspects, such as handling interrupts, memory allocation and instruction
C
these aspects.
ad
optimization.
Compilation is not just about translation; it also involves
Ta
Embedded Systems and loT Design 7-12 Program Design and Analysis
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
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>
Embedded Systems and loT Desian 7-13 Program Design and Analysis
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
= * x = a; d = x *b+ 4;
Example: Before optimization : c a b;
ol
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
output.
iln
d =
a
After optimization :c = a * b; *b+4:
Ta
Embedded Systems and loT Design 7-14 Program Design and Analysis
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
processor.
ad
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
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
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
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>
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
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
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
Embedded SystemS and loT Desian 7-17 Program Design and Analysis
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
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
Embedded Systems and loT Design 7-18 Program Design and Analysis
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
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
Embedded Systems and loT Design 7-19 Program Design and Analysis
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
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
•
Fig. 7.3.6 shows the layout of
the two-dimensional
row-major order.
array in memory in the form of
iln
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
Embedded Systems and loT Design 7-20 Program Design and Analysis
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
the structure.
Review Questions
u
1. With a neat
ad
techniques.
4. State the basic
principle of the compilation
technique.
AU: Dec.-17, Marks. 8
5. Name any two techniques
Ta
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>
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
specific data values used by the program. Cache hits and misses'
can have a
ad
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 :
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
:
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
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
Embedded Systems and loT Design 7-24 Program Design and Analysis
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;
exit T
After determining the program's
|i=j+2:
C
path.
The most straightforward estimate
iln
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
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
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>
Embedded Systems and loT Design 7-26 Program Design and Analysis
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
segments.
ol
As an alternative to physically
measuring execution time, simulation
Ta
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
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
Ans. : AUApril-14, CE
Refer section 4.1.
le
Ans. :
Refer section 4.1.
C
Ans. :
Refer section 4.1.1.
Q.8 What is a digital
command
m
control?
Ans. : Refer section 6.2.2.
Ta
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.
ol
:
Ans. Refer section 5.3.5.
u
:
Ans. Refer section 5.3.5.
iln
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.
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
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>
g
Ans.: Various compilation techniques are Parsing, symbol table
generation, semantic
in
analysis, Machine-independent optimizations, instruction-level
optimizations, code
er
generation, etc.
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
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
8.1
le
Marks
&.5 Interprocess Communication Mechanisms. Dec.-12,13, May-13, 16
May-13, Dec.-13,14,
*
Marks 16
u
-
(8 1)
<br>
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.
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
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
TECHNICAL PUBLICATIONs - an
up-thrust for knowledge
<br>
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
Along with objects, most kernels provide services that help developers create
ol
1. Timers
2. Device
I/0 supervisor
u
5. Task management.
RTOS generally contains a real-time kernel and other higher-level services
such as
m
Embedded Systems and loT Design 8-4 Processes and Operating Systems
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
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
TECHNICAL PUBLICATIONS®
an up-thrust for knowledge
<br>
Ermbedded Systems and loT Design 8-5 Processes and Operating Systems
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
of the computer.
number of operations to be performed and the speed
Ta
to a particular event.
TECHNICAL
PUBLICATIONS an up-thrust for knowiedge
<br>
Embedded Systems and loT Design 8-6 Processes and Operating Systems
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
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>
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
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
Embedded Systems and loT Design 8-8 Processes and Operating Systems
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
field. in the
Real time database is updated
u
TECHNICAL PUBLICATIONSe -
an up-thrust for knowledge
<br>
Embedded Systems and loT Desian 8-9 Processes and Operating Systems
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
•
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
Bit Co
Uncompressed Compressor npressed
m
Conpression
table
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
but to obtain
better performance, the phase
relationship Engine
Ta
TECHNICAL PUBLICATIONS
an up-thrust for knowledge
<br>
The larger number of sensors and modes increases the number of discrete tasks
that must be performed.
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
Controlled by Controlled by
CPUscheduler job scheduler
C
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>
Embedded Systems and loT Design 8-12 Processes and Operating Systems
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
8.3.1 Preemption
• A computation or task is preemptable if can
u
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>
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
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
task. the
C
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
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>
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
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
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>
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
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
3. Returning to
the location indicated
Ta
TECHNICAL PUBLICATIONS
- an up-thrust for knowledge
<br>
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
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
is applied.
Many real time systems do not provide
hardware preemption, so other algorithm
must be employed.
iln
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
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
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.
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
TECHNICAL PUBLICATIONS -
an up-thrust for knowledge
<br>
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
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>
Embedded Systems and loT Design 8-22 Processes and Operating Systems
Advantages :
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
deadline
T1 20 10 20 20
u
T2 40 10 50
ad
50
T3 70 20 80 80
iln
arbitrary phasing.
Major cycle = LCM (20, 50, 80) = 400 ms
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
Priority inversion
u
J.
ad
J,
iln
Ja
6 8 10 12 14 16 18
m
4
0 2
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.
At any time, the wait-for graph contains an (ownership) edge with label x
from a
g
the time.
ol
with arrow
pointing towards the resource.
u
Review Questions
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
memory location.
writing to a specified
iln
computers.
knowledge
TECHNICAL PUBLICATIONS- an up-thrust for
<br>
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
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
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.
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
:
communication process. For examples
ad
connection.
a. Avoiding the costs of establishing and terminating
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
Embedded Systems and loT Design 8-28 Processes and Operating Systems
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
2. Addressing
C
4. Queueing discipline.
ad
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
can be
ad
Embedded Systems and loT Design 8-30 Processes and Operating Systems
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
shared-memory regions.
Once shared memory is
C
TECHNICAL PUBLICATIONs
an up-thrust for knowledge
<br>
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
• 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
TECHNICAL PUBLICATIONS
- an up-thrust for knowiedge
<br>
Embedded Systems and loT Design 8-32 Processes and Operating Systems
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.
7. Application layer
le
6. Presentation layer
ol
5. Session layer
C
4. Transport layer
u
3. Network layer
ad
1. Physical layer
m
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
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
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
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
through a second
point-to-point link to filter (F2). The results in turn are sernt to
the output device
C
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
output.
u
ad
switching
A
element
o
iln
m
2
Ta
Page 33 l of 446
Embedded Systems and loT Design 8-36 Processes and Operating Systems
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
• A message-passing system. a
is subsystem of
provides a set of message-based IPC protocols distributed operating system that
m
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>
Review Questions
1. Explain any one type of network used for embedded system design. AU: May-13, Marks 8
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
simultaneously.
le
Cluster is a set of computers connected over Local Area Network (LAN) that
a
ol
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
:
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>
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
memory-mapped hardware.
ad
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>
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
access
program because the programmer must keep in mind what processors can
ol
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 SD card
controller
le
MP3 decoder
ol
C
few years.
Ta
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
at ptot a
* In block baned mothos eetiata, hal i ofac
Ta
THONS
TECHINIAL PUBLICA
<br>
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
further predictions.
Accelerator requirements
ol
C
in PC.
Inputs
ad
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>
Address generator
g
in
Network Network
er
Network
control
e
in
|PE15 PEO
ng
fE
Comparator
O
e
Motion vector
g
le
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
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
:
Ans.
le
of user interface
Ta
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
C. Sharing of
resources.
in the design of embedded systems ?
C
It
performance for many applications with computational kernels.
If provides large
ad
Page 34 l of 446
UNIT IV
nosoavwee
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- 1)
<br>
Embedded Systems and loT Design 9-2 loT Architecture and Protocols
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
• A device is a piece of
equipment with the mandatory capabilities
ol
Internet of things
Ta
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
a wide
WSIS 2005 Definition By embedding short-range mobile transceivers into
:
•
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
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
TECHNICAL PUBLICATIONS - an
up-thrust for khowledge
<br>
Embedded Systems and loT Design 9-5 loT Architecture and Protocols
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
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
a
a physical quantity and convert it into signal,
2. Sensor : Devices that can measure devices
These
Ta
3. Communication modules These are the part of devices and responsible for
:
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
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>
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
1.
2.
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
Embedded Systemns and loT Design 9-8 loT Architecture and Protocols
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
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>
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
sensors.
Various types of IoT devices are smart clothing Smart watch, wearable
ad
Agriculture Travel
Personal and pet Energy Everyday
m
Embedded Systems and loT Design 9-10 loT Architecture and 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
1. Link layer
• Link layer protocols decide
ol
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>
Page 35 of 446
1l
. 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
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
c. 802.16 WiMax
are based on the IEEE 802.16
ol
:
The receiver and antenna could be a small box or Personal
WiMAX receiver a laptop the way WiFi access
built into
m
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
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
100 Mbps.
le
2. Network layer
ol
destination.
Network layer uses IP address to
choose one host among
u
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>
Embedded Systems and loT Design 9-13 loT Architecture and Protocols
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
packets.
protocol loses, garbles and duplicate
iln
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
response.
HTTP includes commands such as GET,
ol
• 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
TECHNICAL PUBLICATIONS® - an
up-thrust for
knowledge
<br>
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
resource requirements.
minimizes the network bandwidth and device
ol
a
A MQTT topology has MQTT
as possible.
headers are kept as small
m
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
TLS encryption.
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>
. 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
are generated by
loT Service, and Device FGs
iln
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
Flexibility.
The Security Functionality Group
is responsible for ensuring
a
iln
TECHNICAL PUBLICATIONS®
- an up-thrust
for knowledge
<br>
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
• 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
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
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
:
HTTP request methods and actions
ol
2. HEAD : Identical to GET except that the server must not return
a
message-body in the response, only the metadata.
u
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
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
be rapidly
provisioned and released with minimal management effort or
service-provider
ol
interaction.
C
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
collection execution
ol
Fig. 9.4.1
C
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
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
operating system.
Hardware parts includes power supply, processor, memory,
u
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>
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
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
TECHNICAL PUBLICATIONS®
- an
up-thrust for knowledge
<br>
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
is a standards-based wireless
Near Field Communication (NFC) technology
g
allows
functionality in many mobile phones and
• NFC is available as standard content, and
transactions, access digital
u
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
Embedded Systems and loT Design 9-28 loT Architecture and Protocols
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
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
•
time
sensors monitor load conditions in real
iln
environmental conditions
On-board sensors monitor
Fig. 9.5.2
PUBLICATIONS an up-thrust for knowledge
TECHNICAL
<br>
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
1. It supports multiple
application with multiple device.
iln
2. It is information
and service centric.
m
TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>
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
more effectively.
le
vehicles.
wildlife-tracking
6. Telemnetry is usually associated with industrial, medical and
amounts of vehicles data.
u
M2M
Y.6.1 Architecture and Components of
iln
architecture.
Fig. 9.6.1 shows M2M
m
:
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>
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
Backend
C
(Datacentre, cloud)
u
ad
Network core
iln
m
M2M gateways
Ta
M2M devices
TECHNICAL PUBLICATIONS®
an up-thrust for knowledge
<br>
Light
Wireless
bulb network
Light
switch
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
M2M uses vertical system solution approach. IoT uses horizontal enabler approach.
le
****
easeoeercoee
loT
B
ad
:
Need for loT Systems Management :
a. Automating Configuration
Statistical Data
m
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>
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.
Limitation of SNMP :
ad
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>
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
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
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
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
:
•
may need to be able .to control the system and appliances remotely.
u
Purpose
devices (light and air conditioner)
two modes : manual and
m
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
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
Fig. 9.8.2
Process specification diagram
• In auto mode, system monitors the room temperature
u
TECHNICAL PUBLICATIONS® -
an up-thrust for
knowledge
<br>
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
• A Physical entity, as the model shows, can potentially contain other physical
le
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
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>
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
signals. These
devices include the necessary conversion of analog electrical
signals into digital
ol
signals.
C
3. Tags: Tags in general identify the Physical entity that they are
ad
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
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.
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
State : ON/OFF
le
ol
Schedule
C
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***
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
service Autherticatiorn
Reporting monitoring
ORION
g
Gontex broker
oT discovery Trust &
reputation
le
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
Embedded Systems and loT Design 9-44 loT Architecture and Protocols
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.
C
Process Management FG :
Provides the functional concepts necessary
conceptually integrate the IoT to
world into traditional (business) processes.
u
FG : Acts as a communication
Functional Groups by composing hub between several other
Ta
TECHNICAL PUBLICATIONS
an up-thrust
for knowledge
<br>
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
occur in the
2) The Fault FC is used to identify,
isolate, correct and log faults that
C
Specification
Ta
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
end-user
requirements. You can accomplish this more easily
when you have a better sense
ol
fingertips.
iln
m
Power
Ta
Supply
TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>
. 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
Solution:
:
) Process specification
m
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
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
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
relations
ad
:
iv) Controller service
•
Define the services in IoT System, service
iln
TECHNICAL PUBLICATIONS®
an up-thrust
for knowledge
<br>
Review Questions
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
10. Explain the operational view specification step of loT system design.
le
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>
Autormotive
Home Energy Automotive Home Energy
application| application application application| applicationapplication
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
6 Appllcatlon
ol
Query 6
IT Data abstraction Data at Non -real
based (Aggregation and access) rest time
u
ad
4 Data accumulation
(Storage)
iln
2 Connectivity
(Communication and processing
a
units)
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
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
the data.
processes layer: Consumes and shares the application
Ta
Embedded Systems and loT Design 9-52 loT Architecture and Protocols
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
Applications Cloud
g
le
Security
Communication Fog
ol
Edge
u
. It consists of Core IoT functional stack group and IoT data management and
iln
compute stack.
loT data management and compute stack :
m
TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>
Gmbedded Systems and loT Design 9-53 loT Architecture and Protocols
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
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>
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
•
The MQTT protocol works by exchanging a series of
MQTT Control packets in a
le
the network.
• A MQTT topology has a
MQTT server and a MQTT client. MQTT
C
(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
g
in
Message
Subscriber
e er
Message
in
MOTT
Broker
ng
Publisher
Message fE
O
g e
le
Subscriber
ol
3. This collection of consumers can change over time, and vary based on the
ad
subscribe architecture.
m
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
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
Guarantees that a message will reach its intended recipient one or more
ol
the message.
The result of this QoS is that the recipient may
receive the message multiple
u
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
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>
) Message delivery
d) Conferencing (Multi-party chat)
e) Roster management
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
9.10.3 Modbus
ad
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>
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
which only one device (the master/client) can initiate transactions (called queries).
le
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
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>
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
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
get picked
lup by AHU-Audio System ECU and get displayed on the
Touch Screen.
Ta
TECHNICAL PUBLICATIONS
-an up-thrust for knowledge
<br>
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
6. If a a
node detects dominant bus state while trarnsmitting a recessive a message ID
C
DE
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
Embedded Systems and loT Design 9-62 loT Architecture and Protocols
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
interoperate.
• A BACNet device is often
comprised of a microprocessor-based controller
and
u
TECHNICAL PUBLICATIONS®
an up-thrust
for know!edge
<br>
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
to the property.
ol
3. Services
C
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
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
(9 - 64)
<br>
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,
-
• 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
:
Ans.
Automating configuration
ad
•
statistical data
Monitoring operational and
iln
Improved reliability
m
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>
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
Comparing configurations
le
measures temperature
and humidity and communicates the results to a computer. that
ad
Ans. :
The Controlled Area Network (CAN)
runs at rates of 1 MB/s over a bus uses bit-serial transmission. CAN
m
TECHNICAL PUBLICATIONS -
an up-thrust
for knowedge
<br>
UNIT V
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.7 Environment
u
10.8 Agriculture
ad
iln
m
Ta
(10- 1)
<br>
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
3. Wearable devices including clothing, health care implants, smart watches and
fitness devices
ol
more
Internet of Things applications require qiverse sensors and actuators. IoT
devices
iln
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
MMC
SPI
SDIO
SD
m
Ta
UART
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
:
Sensor Devices that can measure a physical quantity and convert
it into a signal,
le
. of the device.
Communication : Communication modules are
responsible for sending collected
data to other device or cloud based servers
iln
data.
Ta
Page 41 I
of 446
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
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.
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
HDMIOUT
Ta
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
Pidora
C
3. Supported resolutions
ad
NISC standards
4. Power
source : Micro USB
iln
Description
Compornents
m
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
• The
le
Pi1
header has 17 programmable pins and the P5 header
adds 4 more.
• Fig 10.2.2 shows GPIO pin header.
ol
input.
ad
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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
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
0 GPIO 0 NGPIO1 1
g
13|
2 GPI0 2 DNC
le
3
GPIO3n 15 GPIO4 4
ol
1917
DNC GPIO5 5
C
13 MISO 6
ad
14 SCLK CEO 10
25 CE1
DNC 11
iln
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
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
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>
g
1. Type the line : "startx"
in
e er
in
i
ng
fE
O
.
boot ieeoiAr
pdat:
iln
m
Ta
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 Chip Select line chooses
which particular SPI device is
in use. If there are
ad
2. 16-bit Receive
m
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)
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
MOSI : This pin is used to transmit data out of the SPI module when it is
C
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>
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
Page 42 of 446
1l
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
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
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>
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
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
TECHNICAL PUBLICATIONS -
an up-thrust
for knowledge
<br>
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>
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) :
g
Example : Display digit
7-seg-LED to Vcc
in
1. Connect pin 3/8 of
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)
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
pin
pull up resistor
Fig. 10.4.4
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
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
3. Monitor the GPIO pin and read its value. Increment a counter
while we wait.
ol
High by the GPIO pin (approx 2v). The time taken is proportional to
the light level
seen by the LDR.
u
#/ust/local/bin/python
m
TECHNICAL PUBLICATIONS - an
up-thrust for knowledge
<br>
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:
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
circulation.
automation works on three levels
:
9
Home
iln
emotely through
trom a smart security camera.
Ta
g
in
e er
in
Smart living
ng
Wearable devices
energy consumption.
Smart lighting systems utilize
u
the user
Certainly the required
Ta
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
reading.
depending upon the temperature
occupancy, glass breakage, door and window
C
insertion or removal.
and even appliance plug
ad
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.
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
Page 43 l of 446
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
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
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
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.
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 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>
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
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
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>
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
Database
le
and car.
Networking Layer : TCP/P over Ethernet
Ta
TECHNICAL PUBLICATIONS® - an
up-thrust for knowledge
<br>
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
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.
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
Reliability Safety
Ta
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
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
:
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
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>
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
TECHNICAL PUBLICATIONS® -
an up-thrust
for knowledge
<br>
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
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
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>
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
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
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
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
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
programming
5. Extensive libraries :
ad
:
Ans. Python can be used to develop prototypes:
Ta
- 36)
(10
<br>
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. :
Ans. :
GND means ground pins. Ground GPIO pins are physical numbers 6, 9, 14, 20,
ad
Q.10
Ans. :
Raspberry Pi hardware includes ARM processor, GPU, RAM and USB port.
m
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.
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
Q.15
:
Ans. The smart irrigation system was developed to
C
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>
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
-
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
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>
OR
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
[6]
ti) Write short note on Raspberry
ad
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