Embedded Systems Tutorial
Embedded Systems Tutorial
Embedded Systems
Audience
This tutorial has been designed to help the students of electronics learn the basic-to-advanced
concepts of Embedded System and 8051 Microcontroller.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of the concepts of
basic electronics such as circuits, logic gates, etc.
Embedded Systems
Table of Contents
About the Tutorial............................................................................................................................................... i
Audience ............................................................................................................................................................. i
Prerequisites ....................................................................................................................................................... i
Disclaimer & Copyright ....................................................................................................................................... i
Table of Contents ............................................................................................................................................... ii
1.
ES OVERVIEW ............................................................................................................................. 1
System ............................................................................................................................................................... 1
Embedded System ............................................................................................................................................. 1
Characteristics of an Embedded System ............................................................................................................. 1
Basic Structure of an Embedded System ............................................................................................................ 3
2.
ES PROCESSORS .......................................................................................................................... 4
Processors in a System ....................................................................................................................................... 4
Types of Processors ............................................................................................................................................ 4
Microprocessor .................................................................................................................................................. 4
Microcontroller .................................................................................................................................................. 5
Microprocessor vs Microcontroller .................................................................................................................... 6
3.
ES ARCHITECTURE....................................................................................................................... 7
Von Neumann Architecture ............................................................................................................................... 7
Harvard Architecture ......................................................................................................................................... 8
Von-Neumann Architecture vs Harvard Architecture ......................................................................................... 8
CISC and RISC ..................................................................................................................................................... 9
4.
Embedded Systems
Simulators .........................................................................................................................................................11
Microcontroller Starter Kit ................................................................................................................................11
Emulators..........................................................................................................................................................12
Peripheral Devices in Embedded Systems .........................................................................................................12
Criteria for Choosing Microcontroller ................................................................................................................12
5.
6.
7.
ES TERMS.................................................................................................................................. 23
Program Counter ..............................................................................................................................................23
Reset Vector .....................................................................................................................................................23
Stack Pointer .....................................................................................................................................................23
Infinite Loop ......................................................................................................................................................23
Interrupts ..........................................................................................................................................................24
Little Endian Vs Big Endian ................................................................................................................................24
8.
Embedded Systems
9.
ES REGISTERS ............................................................................................................................ 29
Storage Registers in 8051 ..................................................................................................................................29
ROM Space in 8051 ...........................................................................................................................................31
iv
Embedded Systems
1. ES Overview
Embedded Systems
System
A system is an arrangement in which all its unit assemble work together according to a set of
rules. It can also be defined as a way of working, organizing or doing one or many tasks
according to a fixed plan. For example, a watch is a time displaying system. Its components
follow a set of rules to show time. If one of its parts fails, the watch will stop working. So we can
say, in a system, all its subcomponents depend on each other.
Embedded System
As its name suggests, Embedded means something that is attached to another thing. An
embedded system can be thought of as a computer hardware system having software embedded
in it. An embedded system can be an independent system or it can be a part of a large system.
An embedded system is a microcontroller or microprocessor based system which is designed to
perform a specific task. For example, a fire alarm is an embedded system; it will sense only
smoke.
An embedded system has three components:
It has hardware.
It has Real Time Operating system (RTOS) that supervises the application software and
provide mechanism to let the processor run a process as per scheduling by following a
plan to control the latencies. RTOS defines the way the system works. It sets the rules
during the execution of application program. A small scale embedded system may not
have RTOS.
Tightly constrained All computing systems have constraints on design metrics, but
those on an embedded system can be especially tight. Design metrics is a measure of an
implementation's features such as its cost, size, power, and performance. It must be of
a size to fit on a single chip, must perform fast enough to process data in real time and
consume minimum power to extend battery life.
Reactive and Real time Many embedded systems must continually react to changes
in the system's environment and must compute certain results in real time without any
delay. Consider an example of a car cruise controller; it continually monitors and reacts
to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly
within a limited time; a delayed computation can result in failure to control of the car.
1
Embedded Systems
Memory It must have a memory, as its software usually embeds in ROM. It does not
need any secondary memories in the computer.
Connected It must have connected peripherals to connect input and output devices.
HW-SW systems Software is used for more features and flexibility. Hardware is used
for performance and security.
Advantages
Easily Customizable
Low cost
Enhanced performance
Disadvantages
Embedded Systems
Sensor It measures the physical quantity and converts it to an electrical signal which
can be read by an observer or by any electronic instrument like an A2D converter. A
sensor stores the measured quantity to the memory.
A-D Converter An analog-to-digital converter converts the analog signal sent by the
sensor into a digital signal.
Processor & ASICs Processors process the data to measure the output and store it to
the memory.
D-A Converter A digital-to-analog converter converts the digital data fed by the
processor to analog data.
Actuator An actuator compares the output given by the D-A Converter to the actual
(expected) output stored in it and stores the approved output.
2. ES Processors
Embedded Systems
Processor is the heart of an embedded system. It is the basic unit that takes inputs and produces
an output after processing the data. For an embedded system designer, it is necessary to have
the knowledge of both microprocessors and microcontrollers.
Processors in a System
A processor has two essential units:
The CU includes a fetch unit for fetching instructions from the memory. The EU has circuits that
implement the instructions pertaining to data transfer operation and data conversion from one
form to another.
The EU includes the Arithmetic and Logical Unit (ALU) and also the circuits that execute
instructions for a program control task such as interrupt, or jump to another set of instructions.
A processor runs the cycles of fetch and executes the instructions in the same sequence as they
are fetched from memory.
Types of Processors
Processors can be of the following categories:
Microprocessor
Microcontroller
Embedded Processor
Media Processor
GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or
a Very Large Scale Integration (VLSI) circuit
Microprocessor
A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units
such as coaches, floating point processing arithmetic unit, and pipelining units that help in faster
processing of instructions.
4
Embedded Systems
Microcontroller
A microcontroller is a single-chip VLSI unit (also called microcomputer) which, although having
limited computational capabilities, possesses enhanced input/output capability and a number of
on-chip functional units.
CPU
RAM
ROM
I/O Port
Timer
Microcontroller Chip
Microcontrollers are particularly used in embedded systems for real-time control applications
with on-chip program memory and devices.
Embedded Systems
Microprocessor vs Microcontroller
Let us now take a look at the most notable differences between a microprocessor and a
microcontroller.
Microprocessor
Microcontroller
3. ES Architecture
Embedded Systems
The 8051 microcontrollers work with 8-bit data bus. So they can support external data memory
up to 64K and external program memory of 64k at best. Collectively, 8051 microcontrollers can
address 128k of external memory.
When data and code lie in different memory blocks, then the architecture is referred as Harvard
architecture. In case data and code lie in the same memory block, then the architecture is
referred as Von Neumann architecture.
Embedded Systems
Harvard Architecture
The Harvard architecture offers separate storage and signal buses for instructions and data. This
architecture has data storage entirely contained within the CPU, and there is no access to the
instruction storage as data. Computers have separate memory areas for program instructions
and data using internal data buses, allowing simultaneous access to both instructions and data.
Programs needed to be loaded by an operator; the processor could not boot itself. In a Harvard
architecture, there is no need to make the two memories share properties.
Harvard Architecture
Embedded Systems
Simple in design.
Complex in design.
CISC vs RISC
The following points differentiate a CISC from a RISC
CISC
RISC
Emphasis is on hardware.
Emphasis is on software.
Embedded Systems
Cross-Compiler
If the compiled program can run on a computer having different CPU or operating system than
the computer on which the compiler compiled the program, then that compiler is known as a
cross-compiler.
Decompiler
A program that can translate a program from a low-level language to a high-level language is
called a decompiler.
Language Converter
A program that translates programs written in different high-level languages is normally called
a language translator, source to source translator, or language converter.
A compiler is likely to perform the following operations
Preprocessing
Parsing
Code generation
Code optimization
Assemblers
An assembler is a program that takes basic computer instructions (called as assembly language)
and converts them into a pattern of bits that the computer's processor can use to perform its
basic operations. An assembler creates object code by translating assembly instruction
mnemonics into opcodes, resolving symbolic names to memory locations. Assembly language
uses a mnemonic to represent each low-level machine operation (opcode).
10
Embedded Systems
Simulators
Emulator
Simulators
Code is tested for the MCU / system by simulating it on the host computer used for code
development. Simulators try to model the behavior of the complete microcontroller in software.
Functions of Simulators
A simulator performs the following functions
Defines the processor or processing device family as well as its various versions for the
target system.
Monitors the detailed information of a source code part with labels and symbolic
arguments as the execution goes on for each single step.
Provides the status of RAM and simulated ports of the target system for each single step
execution.
Provides trace of the output of contents of program counter versus the processor
registers.
Monitors the detailed information of the simulator commands as these are entered from
the keyboard or selected from the menu.
Provides breakpoints and the trace which are together the important testing and
debugging tool.
In-system programmer
11
Embedded Systems
A big advantage of these kits over simulators is that they work in real-time and thus allow for
easy input/output functionality verification. Starter kits, however, are completely sufficient and
the cheapest option to develop simple microcontroller projects.
Emulators
An emulator is a hardware kit or a software program or can be both which emulates the functions
of one computer system (the guest) in another computer system (the host), different from the
first one, so that the emulated behavior closely resembles the behavior of the real system (the
guest).
Emulation refers to the ability of a computer program in an electronic device to emulate (imitate)
another program or device. Emulation focuses on recreating an original computer environment.
Emulators have the ability to maintain a closer connection to the authenticity of the digital object.
An emulator helps the user to work on any kind of application or operating system on a platform
in a similar way as the software runs as in its original environment.
Synchronous Serial Communication Interface like I2C, SPI, SSC, and ESSI
Debugging like JTAG, ISP, ICSP, BDM Port, BITP, and DP9 ports
Embedded Systems
Cost per Unit This is important in terms of final cost of the product in which the
microcontroller is to be used.
Further, make sure you have tools such as compilers, debuggers, and assemblers, available with
the microcontroller. The most important of all, you should purchase a microcontroller from a
reliable source.
13
5. ES 8051 Microcontroller
Embedded Systems
8052 microcontroller 8052 has all the standard features of the 8051 microcontroller
as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip
program ROM instead of 4K bytes.
8031 microcontroller It is another member of the 8051 family. This chip is often
referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add
external ROM to it in order to use it, which contains the program to be fetched and
executed. This program can be as large as 64K bytes. But in the process of adding
external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can
add an external I/O to the 8031.
8051
8052
8031
ROM(bytes)
4K
8K
0K
RAM(bytes)
128
256
128
Timers
I/O pins
32
32
32
Serial port
Interrupt sources
14
Embedded Systems
8051 may also have a number of special features such as UARTs, ADC, Op-amp, etc.
15
6. ES I/O Programming
Embedded Systems
In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows
the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The
other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and
PSEN (bar).
It is a 40 Pin PDIP (Plastic Dual Inline Package).
Note: In a DIP package, you can recognize the first pin and the last pin by the cut at the middle
of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this
case) is to the right of the cut mark.
Embedded Systems
MOV A,#0FFH
;(comments: A=FFH(Hexadecimal
MOV P0,A
A,#55
BACK:
MOV
P2,A
ACALL
DELAY
CPL
SJMP
BACK
;complement(invert) reg. A
17
Embedded Systems
If Port 1 is configured to be used as an output port, then to use it as an input port again, program
it by writing 1 to all of its bits as in the following code.
;Toggle all bits of continuously
MOV
A ,#0FFH
MOV
P1,A
;A=FF hex
;Make P1 an input port
MOV
A,P1
MOV
R7,A
;save it in Reg R7
ACALL DELAY
;wait
MOV
A,P1
MOV
R6,A
;save it in R6
ACALL DELAY
;wait
MOV
A,P1
MOV
R5,A
;save it in R5
A,#55
BACK:
MOV
P2,A
ACALL
DELAY
CPL
SJMP
BACK
; complement(invert) reg. A
If Port 2 is configured to be used as an output port, then to use it as an input port again, program
it by writing 1 to all of its bits as in the following code.
;Get a byte from P2 and send it to P1
MOV
A,#0FFH
;A=FF hex
MOV
P2,A
MOV
A,P2
MOV
P1,A
;send it to Port 1
18
Embedded Systems
SJMP
BACK
Function
Pin
P3.0
RxD
10
P3.1<
TxD
11
P3.2<
Complement of INT0
12
P3.3<
INT1
13
P3.4<
T0
14
P3.5<
T1
15
P3.6<
WR
16
P3.7<
Complement of RD
17
Dual role of Port 0 Port 0 is also designated as AD0AD7, as it can be used for both
data and address handling. While connecting an 8051 to external memory, Port 0 can
provide both address and data. The 8051 microcontroller then multiplexes the input as
address or data in order to save pins.
Dual role of Port 2 Besides working as I/O, Port P2 is also used to provide 16-bit
address bus for external memory along with Port 0. Port P2 is also designated as (A8
A15), while Port 0 provides the lower 8-bits via A0A7. In other words, we can say that
when an 8051 is connected to an external memory (ROM) which can be maximum up to
64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is
used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is
the way any Program code of external ROM is addressed.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) 8051 has on-chip oscillator but requires
external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of
the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired
19
Embedded Systems
RST (Pin No. 9) It is an Input pin and active High pin. Upon applying a high pulse on
this pin, that is 1, the microcontroller will reset and terminate all activities. This process
is known as Power-On Reset. Activating a power-on reset will cause all values in the
register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset,
the high pulse must be high for a minimum of two machine cycles before it is allowed to
go low, which depends on the capacitor value and the rate at which it charges. (Machine
Cycle is the minimum amount of frequency a single instruction requires in execution).
EA or External Access (Pin No. 31) It is an input pin. This pin is an active low pin;
upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having
on-chip ROM, the EA (bar) pin is connected to V cc. But in an 8031 microcontroller which
does not have an on-chip ROM, the code is stored in an external ROM and then fetched
by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate
that the program code is stored externally.
20
Embedded Systems
PSEN or Program store Enable (Pin No 29) This is also an active low pin, i.e., it
gets activated after applying a low pulse. It is an output pin and used along with the EA
pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external
ROM.
ALE or (Address Latch Enable) This is an Output Pin and is active high. It is especially
used for 8031 IC to connect it to the external memory. It can be used while deciding
whether P0 pins will be used as Address bus or Data bus. When ALE=1, then the P0 pins
work as Data bus and when ALE=0, then the P0 pins act as Address bus.
P1.2
21
Embedded Systems
ACALL
CLR
DELAY
P1.2
ACALL
DELAY
SJMP
AGAIN
Single-Bit Instructions
Instructions
SETB bit
Function
Set the bit (bit=1)
CLR bit
CPL bit
JB bit , target
22
7. ES Terms
Embedded Systems
Program Counter
The Program Counter is a 16- or 32-bit register which contains the address of the next instruction
to be executed. The PC automatically increments to the next sequential memory location every
time an instruction is fetched. Branch, jump, and interrupt operations load the Program Counter
with an address other than the next sequential location.
Activating a power-on reset will cause all values in the register to be lost. It means the value of
the PC (program counter) is 0 upon reset, forcing the CPU to fetch the first opcode from the
ROM memory location 0000. It means we must place the first byte of upcode in ROM location
0000 because that is where the CPU expects to find the first instruction.
Reset Vector
The significance of the reset vector is that it points the processor to the memory address which
contains the firmware's first instruction. Without the Reset Vector, the processor would not know
where to begin execution. Upon reset, the processor loads the Program Counter (PC) with the
reset vector value from a predefined memory location. On CPU08 architecture, this is at location
$FFFE:$FFFF.
When the reset vector is not necessary, developers normally take it for granted and dont
program into the final image. As a result, the processor doesn't start up on the final product. It
is a common mistake that takes place during the debug phase.
Stack Pointer
Stack is implemented in RAM and a CPU register is used to access it called SP (Stack Pointer)
register. SP register is an 8-bit register and can address memory addresses of range 00h to FFh.
Initially, the SP register contains value 07 to point to location 08 as the first location being used
for the stack by the 8051.
When the content of a CPU register is stored in a stack, it is called a PUSH operation. When the
content of a stack is stored in a CPU register, it is called a POP operation. In other words, a
register is pushed onto the stack to save it and popped off the stack to retrieve it.
Infinite Loop
An infinite loop or an endless loop can be identified as a sequence of instructions in a computer
program that executes endlessly in a loop, because of the following reasons:
loop with a terminating condition that causes the loop to start over.
23
Embedded Systems
Such infinite loops normally caused older operating systems to become unresponsive, as an
infinite loop consumes all the available processor time. I/O operations waiting for user inputs
are also called "infinite loops". One possible cause of a computer "freezing" is an infinite loop;
other causes include deadlock and access violations.
Embedded systems, unlike a PC, never "exit" an application. They idle through an Infinite Loop
waiting for an event to take place in the form of an interrupt, or a pre-scheduled task. In order
to save power, some processors enter special sleep or wait modes instead of idling through
an Infinite Loop, but they will come out of this mode upon either a timer or an External Interrupt.
Interrupts
Interrupts are mostly hardware mechanisms that instruct the program that an event has
occurred. They may occur at any time, and are therefore asynchronous to the program flow.
They require special handling by the processor, and are ultimately handled by a corresponding
Interrupt Service Routine (ISR). Interrupts need to be handled quickly. If you take too much
time servicing an interrupt, then you may miss another interrupt.
24
8. ES Assembly Language
Embedded Systems
Assembly languages were developed to provide mnemonics or symbols for the machine level
code instructions. Assembly language programs consist of mnemonics, thus they should be
translated into machine code. A program that is responsible for this conversion is known as
assembler. Assembly language is often termed as a low-level language because it directly works
with the internal structure of the CPU. To program in assembly language, a programmer must
know all the registers of the CPU.
Different programming languages such as C, C++, Java and various other languages are called
high-level languages because they do not deal with the internal details of a CPU. In contrast, an
assembler is used to translate an assembly language program into machine code (sometimes
also called object code or opcode). Similarly, a compiler translates a high-level language into
machine code. For example, to write a program in C language, one must use a C compiler to
translate the program into machine language.
mnemonics
[ operands ]
[;comment ]
The label field allows the program to refer to a line of code by name. The label fields
cannot exceed a certain number of characters.
The mnemonics and operands fields together perform the real work of the program
and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV
are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These
two fields could contain directives. Directives do not generate machine code and are used
only by the assembler, whereas instructions are translated into machine code for the CPU
to execute.
1.0000
ORG
0H
2 0000 7D25
MOV
R5,#25H
3.0002 7F34
MOV
R7,#34H
4.0004 7400
MOV
A,#0
;load 0 into A
5.0006 2D
ADD
A,R5
;add contents of R5 to A
6.0007 2F
ADD
A,R7
;add contents of R7 to A
R7
25
Embedded Systems
7.0008 2412
ADD
8.000A 80FE
9.000C END
A,#12H
;add to A value 12 H
;stay in this loop
;end of asm source file
Notice the Label "HERE" in the program. Any label which refers to an instruction should
be followed by a colon.
First, we use an editor to type in a program similar to the above program. Editors like
MS-DOS EDIT program that comes with all Microsoft operating systems can be used to
create or edit a program. The Editor must be able to produce an ASCII file. The "asm"
extension for the source file is used by an assembler in the next step.
The "asm" source file contains the program code created in Step 1. It is fed to an 8051
assembler. The assembler then converts the assembly language instructions into machine
code instructions and produces an .obj file (object file) and a .lst file (list file). It is also
called as a source file, that's why some assemblers require that this file have the "src"
extensions. The "lst" file is optional. It is very useful to the program because it lists all
the opcodes and addresses as well as errors that the assemblers detected.
Assemblers require a third step called linking. The link program takes one or more object
files and produces an absolute object file with the extension "abs".
Next, the "abs" file is fed to a program called "OH" (object to hex converter), which
creates a file with the extension "hex" that is ready to burn in to the ROM.
26
Embedded Systems
Data Type
The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits
size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal)
so that it can be processed by the CPU.
DB (Define Byte)
The DB directive is the most widely used data directive in the assembler. It is used to define the
8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal,
the "D" after the decimal number is optional, but it is required for "B" (binary) and "Hl"
(hexadecimal).
To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler
generates ASCII code for the numbers/characters automatically. The DB directive is the only
directive that can be used to define ASCII strings larger than two characters; therefore, it should
be used for all the ASCII data definitions. Some examples of DB are given below:
ORG
500H
DATA1:
DB
28
DATA2:
DB
00110101B
;BINARY
DATA3:
DB
39H
;HEX
ORG
510H
(35 in hex)
27
Embedded Systems
DATA4:
DATA6:
DB
"2591"
ORG
520H
DA
;ASCII
NUMBERS
;ASCII CHARACTERS
Either single or double quotes can be used around ASCII strings. DB is also used to allocate
memory in byte-sized chunks.
Assembler Directives
Some of the directives of 8051 are as follows:
ORG (origin) The origin directive is used to indicate the beginning of the address. It
takes the numbers in hexa or decimal format. If H is provided after the number, the
number is treated as hexa, otherwise decimal. The assembler converts the decimal
number to hexa.
END directive It indicates the end of the source (asm) file. The END directive is the
last line of the program; anything after the END directive is ignored by the assembler.
Each label name must be unique. The names used for labels in assembly language
programming consist of alphabetic letters in both uppercase and lowercase, number 0
through 9, and special characters such as question mark (?), period (.), at the rate @,
underscore (_), and dollar($).
Reserved words cannot be used as a label in the program. For example, ADD and MOV
words are the reserved words, since they are instruction mnemonics.
28
9. ES Registers
Embedded Systems
Registers are used in the CPU to store information on temporarily basis which could be data to
be processed, or an address pointing to the data which is to be fetched. In 8051, there is one
data type is of 8-bits, from the MSB (most significant bit) D7 to the LSB (least significant bit)
D0. With 8-bit data type, any data type larger than 8-bits must be broken into 8-bit chunks
before it is processed.
The most widely used registers of the 8051 are A (accumulator), B, R0-R7, DPTR (data pointer),
and PC (program counter). All these registers are of 8-bits, except DPTR and PC.
Accumulator
R register
B register
Accumulator
The accumulator, register A, is used for all arithmetic and logic operations. If the accumulator is
not present, then every result of each calculation (addition, multiplication, shift, etc.) is to be
stored into the main memory. Access to main memory is slower than access to a register like
the accumulator because the technology used for the large main memory is slower (but cheaper)
than that used for a register.
29
Embedded Systems
Let us take another example. We will add the values in R1 and R2 together and then subtract
the values of R3 and R4 from the result.
MOV A,R3
ADD A,R4
MOV R5,A
MOV A,R1
ADD A,R2
SUBB A,R5
As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this is not the
most efficient way to calculate (R1 + R2) (R3 + R4), but it does illustrate the use of the "R"
registers as a way to store values temporarily.
Embedded Systems
pointing to data. It is used by the 8051 to access external memory using the address indicated
by DPTR. DPTR is the only 16-bit register available and is often used to store 2-byte values.
31
Embedded Systems
AC
F0
RS1
RS0
OV
CY
PSW.7
Carry Flag
AC
PSW.6
F0
PSW.5
RS1
PSW.4
RS0
PSW.3
OV
PSW.2
Overflow Flag
PSW.1
PSW.0
32
Embedded Systems
We can select the corresponding Register Bank bit using RS0 and RS1 bits.
RS1
RS2
Register Bank
Address
00H-07H
08H-0FH
10H-17H
18H-1FH
CY, the carry flag This carry flag is set (1) whenever there is a carry out from the D7
bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1
or 0 directly by an instruction such as "SETB C" and "CLR C" where "SETB" stands for set
bit carry and "CLR" stands for clear carry.
AC, auxiliary carry flag If there is a carry from D3 and D4 during an ADD or SUB
operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform
binary coded decimal arithmetic.
P, the parity flag The parity flag represents the number of 1's in the accumulator
register only. If the A register contains odd number of 1's, then P = 1; and for even
number of 1's, P = 0.
OV, the overflow flag This flag is set whenever the result of a signed number operation
is too large causing the high-order bit to overflow into the sign bit. It is used only to detect
errors in signed arithmetic operations.
Example
Show the status of CY, AC, and P flags after the addition of 9CH and 64H in the following
instruction.
MOV A,
#9CH
ADD A,
# 64H
Solution:
9C
10011100
+64
01100100
100
00000000
33
Embedded Systems
The 8051 microcontroller has a total of 128 bytes of RAM. We will discuss about the allocation
of these 128 bytes of RAM and examine their usage as stack and register.
32 bytes from 00H to 1FH locations are set aside for register banks and the stack.
16 bytes from 20H to2FH locations are set aside for bit-addressable read/write memory.
80 bytes from 30H to 7FH locations are used for read and write storage; it is called as
scratch pad. These 80 locations RAM are widely used for the purpose of storing data
and parameters by 8051 programmers.
Embedded Systems
0 to 7 are set aside for bank 0 of R0R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is
location 2, and so on, until the memory location 7, which belongs to R7 of bank 0.
The second bank of registers R0R7 starts at RAM location 08 and goes to locations OFH. The
third bank of R0R7 starts at memory location 10H and goes to location to 17H. Finally, RAM
locations 18H to 1FH are set aside for the fourth bank of R0R7.
RS2
Bank Selected
Bank0
Bank1
Bank2
Bank3
35
Embedded Systems
36
11. ES Instructions
Embedded Systems
The flow of program proceeds in a sequential manner, from one instruction to the next
instruction, unless a control transfer instruction is executed. The various types of control transfer
instruction in assembly language include conditional or unconditional jumps and call instructions.
Example
Multiply 25 by 10 using the technique of repeated addition.
Solution: Multiplication can be achieved by adding the multiplicand repeatedly, as many times
as the multiplier. For example,
25 * 10 = 250(FAH)
25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 = 250
MOV A,#0
;A=0,clean ACC
MOV R2,#10
Add A,#25
AGAIN:DJNZ R2,
AGAIN:repeat
MOV R5 , A
Drawback in 8051: Looping action with the instruction DJNZ Reg label is limited to 256
iterations only. If a conditional jump is not taken, then the instruction following the jump is
executed.
Embedded Systems
Example
Write a program to:
Solution: Since 700 is greater than 255 (the maximum capacity of any register), two registers
are used to hold the count. The following code shows how to use two registers, R2 and R3, for
the count.
MOV A,#55H
;A=55H
AGAIN:MOV R2,#70
CPL A
;complement
Action
JZ
Jump if A = 0
JNZ
Jump if A 0
DJNZ
CJNE A,data
CJNE reg,#data
JC
Jump if CY = 1
JNC
Jump if CY 1
JB
Jump if bit = 1
JNB
Jump if bit = 0
JBC
JNZ (jump if A is not equal to 0) In this instruction, the content of the accumulator
is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.
JNC (Jump if no carry, jumps if CY = 0) The Carry flag bit in the flag (or PSW)
register is used to make the decision whether to jump or not "JNC label". The CPU looks
at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to
38
Embedded Systems
fetch and execute instructions from the address of the label. If CY = 1, it will not jump
but will execute the next instruction below JNC.
Note: It must be noted that all conditional jumps are short jumps, i.e., the address of the target
must be within 128 to +127 bytes of the contents of the program counter.
LJMP (long jump) LJMP is 3-byte instruction in which the first byte represents opcode,
and the second and third bytes represent the 16-bit address of the target location. The
2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.
SJMP (short jump) It is a 2-byte instruction where the first byte is the opcode and
the second byte is the relative address of the target location. The relative address ranges
from 00H to FFH which is divided into forward and backward jumps; that is, within 128
to +127 bytes of memory relative to the address of the current PC (program counter). In
case of forward jump, the target address can be within a space of 127 bytes from the
current PC. In case of backward jump, the target address can be within 128 bytes from
the current PC.
PC
0000
0000
Op-code
Mnemonic
Operand
ORG
0000
7800
MOV
R0,#003
0002
7455
MOV
A,#55H0
0004
6003
JZ
NEXT
0006
08
INC
R0
0007
04
INC
0008
04
INC
0009
2477 NEXT:
ADD
A, #77h
000B
5005
JNC
OVER
10
000D
E4
CLR
AGAIN:
39
Embedded Systems
11
000E
F8
MOV
R0, A
12
000F
F9
MOV
R1, A
13
0010
FA
MOV
R2, A
14
0011
FB
MOV
R3, A
15
0012
2B
ADD
A, R3
16
0013
50F2
JNC
AGAIN
17
0015
80FE HERE:
SJMP
HERE
18
0017
OVER:
END
CALL Instructions
CALL is used to call a subroutine or method. Subroutines are used to perform operations or tasks
that need to be performed frequently. This makes a program more structured and saves memory
space. There are two instructions: LCALL and ACALL.
40
Embedded Systems
An addressing mode refers to how you are addressing a given memory location. There are five
different ways or five addressing modes to execute this instruction which are as follows:
41
Embedded Systems
Note: The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of
'#', the hexadecimal number would be taken as an address.
42
Embedded Systems
As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete.
The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A,
address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active
and ready to receive data. Then the PC goes to the next address as 0203 and looks up the
address of the location of 04H where the source data (to be transferred to accumulator) is
located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the
execution is completed.
43
Embedded Systems
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is
executed, the control goes directly to R4 of the respected register bank (that is selected in PSW).
If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the
accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from
data memory location 0C H and is shown as dotted line. 0CH is the address location of Register
4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete
execution. What it means is, you can save program memory by using register direct addressing
mode.
44
Embedded Systems
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0
of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data
2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter
increments by 1 and moves to 0203 of the program memory.
Note: Only R0 and R1 are allowed to form a register indirect addressing instruction. In other
words, the programmer can create an instruction either using @R0 or @R1. All register banks
are allowed.
Embedded Systems
The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE
is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is
performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred
to the accumulator. The previous value inside the accumulator (02H) will be replaced with the
new data from 0200H. The new data in the accumulator is highlighted in the illustration.
This is a 1-byte instruction with 2 cycles needed for execution and the execution time required
for this instruction is high compared to previous instructions (which were all 1 cycle each).
The other example MOVC A, @A+PC works the same way as the above example. Instead of
adding DPTR with the accumulator, here the data inside the program counter (PC) is added with
the accumulator to obtain the target address.
46
Embedded Systems
A Special Function Register (or Special Purpose Register, or simply Special Register) is a register
within a microprocessor that controls or monitors the various functions of a microprocessor. As
the special registers are closely tied to some special function or status of the processor, they
might not be directly writable by normal instructions (like add, move, etc.). Instead, some
special registers in some processor architectures require special instructions to modify them.
In the 8051, register A, B, DPTR, and PSW are a part of the group of registers commonly referred
to as SFR (special function registers). An SFR can be accessed by its name or by its address.
The following table shows a list of SFRs and their addresses.
Byte
Address
FF
F0
F7
F6
F5
F4
F3
F2
F1
F0
E0
E7
E6
E5
E4
E3
E2
E1
E0
ACC
D0
B8
B0
D7
B7
D6
B6
D5
B5
D4
BC
B4
D3
BB
B3
D2
BA
B2
B9
B1
D0
B8
B0
PSW
IP
P3
A2
AF
AC
AB
AA
A9
A8
IE
A0
A7
A6
A5
A4
A3
A2
A1
A0
P2
99
98
9C
9B
9A
99
98
SBUF
SCON
90
97
94
93
92
91
90
P1
8D
8C
8B
8A
89
88
87
83
82
81
80
Bit Address
96
95
Not
Not
Not
Not
Not
8F
87
8E
87
bit
bit
bit
bit
bit
8D
8C
Not bit
Addressable
Addressable
Addressable
Addressable
Addressable
8B
8A
Addressable
89
81
88
80
TH1
TH0
TL1
TL0
TMOD
TCON
PCON
DPH
DPL
SP
P0
47
Embedded Systems
A special function register can have an address between 80H to FFH. These addresses
are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside
the 8051.
Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH,
are reserved and must not be used by the 8051 programmer.
CY
PSW.7
Carry Flag
AC
PSW.6
F0
PSW.5
RS1
PSW.4
RS0
PSW.3
OV
PSW.2
Overflow Flag
PSW.1
PSW.0
In the following example, the SFR registers names are replaced with their addresses.
CY
AC
F0
RS1
RS0
OV
We can select the corresponding Register Bank bit using RS0 and RS1 bits.
RS1
RS2
Register Bank
Address
00H-07H
08H-0FH
10H-17H
18H-1FH
The Program Status Word (PSW) contains status bits to reflect the current state of the CPU. The
8051 variants provide one special function register, PSW, with this status information. The 8251
provides two additional status flags, Z and N, which are available in a second special function
register called PSW1.
48
Embedded Systems
A timer is a specialized type of clock which is used to measure time intervals. A timer that
counts from zero upwards for measuring time elapsed is often called a stopwatch. It is a device
that counts down from a specified time interval and used to generate a time delay, for example,
an hourglass is a timer.
A counter is a device that stores (and sometimes displays) the number of times a particular
event or process occurred, with respect to a clock signal. It is used to count the events happening
outside the microcontroller. In electronics, counters can be implemented quite easily using
register-type circuits such as a flip-flop.
Counter
Timer 0 Register
The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called
TL0 (Timer 0 low byte) and the high-byte register is called TH0 (Timer 0 high byte). These
registers can be accessed like any other register. For example, the instruction MOV TL0, #4H
moves the value into the low-byte of Timer #0.
49
Embedded Systems
Timer 1 Register
The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called
TL1 (Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These
registers can be accessed like any other register. For example, the instruction MOV TL1, #4H
moves the value into the low-byte of Timer 1.
Gate : When set, the timer only runs while INT(0,1) is high.
C/T : Counter/Timer select bit.
M1 : Mode bit 1.
M0 : Mode bit 0.
GATE
Every timer has a means of starting and stopping. Some timers do this by software, some by
hardware, and some have both software and hardware controls. 8051 timers have both software
and hardware controls. The start and stop of a timer is controlled by software using the
instruction SETB TR1 and CLR TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0.
The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions
start and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and
stopped by an external source by making GATE = 1 in the TMOD register.
50
Embedded Systems
M1 / M2
M1
M2
Mode
Spilt mode.
Embedded Systems
nor do you have to worry about resetting the value because the microcontroller hardware will
do it all for you. The auto-reload mode is used for establishing a common baud rate.
Initializing a Timer
Decide the timer mode. Consider a 16-bit timer that runs continuously, and is independent of
any external pins.
Initialize the TMOD SFR. Use the lowest 4 bits of TMOD and consider Timer 0. Keep the two bits,
GATE 0 and C/T 0, as 0, since we want the timer to be independent of the external pins. As 16bit mode is timer mode 1, clear T0M1 and set T0M0. Effectively, the only bit to turn on is bit 0
of TMOD. Now execute the following instruction:
MOV TMOD,#01h
Now, Timer 0 is in 16-bit timer mode, but the timer is not running. To start the timer in running
mode, set the TR0 bit by executing the following instruction:
SETB TR0
Now, Timer 0 will immediately start counting, being incremented once every machine cycle.
Reading a Timer
A 16-bit timer can be read in two ways. Either read the actual value of the timer as a 16-bit
number, or you detect when the timer has overflowed.
52
15. ES Interrupts
Embedded Systems
Hardware Interrupt
A hardware interrupt is an electronic alerting signal sent to the processor from an external
device, like a disk controller or an external peripheral. For example, when we press a key on the
keyboard or move the mouse, they trigger hardware interrupts which cause the processor to
read the keystroke or mouse position.
Software Interrupt
A software interrupt is caused either by an exceptional condition or a special instruction in the
instruction set which causes an interrupt when it is executed by the processor. For example, if
the processor's arithmetic logic unit runs a command to divide a number by zero, to cause a
divide-by-zero exception, thus causing the computer to abandon the calculation or display an
error message. Software interrupt instructions work similar to subroutine calls.
What is Polling?
The state of continuous monitoring is known as polling. The microcontroller keeps checking the
status of other devices; and while doing so, it does no other operation and consumes all its
processing time for monitoring. This problem can be addressed by using interrupts.
In the interrupt method, the controller responds only when an interruption occurs. Thus, the
controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and
inbuilt devices.
Polling
The polling method is like a salesperson. The
salesman goes from door to door while
requesting to buy a product or service.
Similarly, the controller keeps monitoring the
flags or signals one by one for all devices and
provides service to whichever component that
needs its service.
53
Embedded Systems
Pin
Interrupts
0023
Timer 1 interrupts(TF1)
001B
0013
P3.3 (13)
0003
P3.2 (12)
Timer 0 (TF0)
000B
Reset
0000
54
Embedded Systems
1. When the reset pin is activated, the 8051 jumps to the address location 0000. This is
power-up reset.
2. Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory
locations are 000BH and 001BH respectively in the interrupt vector table.
3. Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13
in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory
locations are 0003H and 0013H respectively in the interrupt vector table.
4. Serial communication has a single interrupt that belongs to both receive and transmit.
Memory location 0023H belongs to this interrupt.
Edge Triggered
55
Embedded Systems
ET2
ES
EA Global enable/disable.
- Undefined.
ET1
EX1
ET0
EX0
56
Embedded Systems
PT1
PX1
IP.7
Not Implemented.
IP.6
Not Implemented.
IP.5
Not Implemented.
IP.4
Not Implemented.
PT1
IP.3
PX1
IP.2
PT0
IP.1
PX0
IP.0
PT0
PX0
57