8051 Notes 18-19
8051 Notes 18-19
1. 8051 Microcontroller
An embedded system can be defined as a system that does a specific task smartly.
Washing machines, ovens, elevators, traffic control systems are the some of the examples
of embedded systems. The smartness of the system is due to the presence of the electronic
device present in it called ‘Microcontrollers’.
The physical components of the entire system refer to ‘Hardware’ while the set of
instructions written for the system to perform a task is called ‘Program’ and further group
of programs refers to ‘Software’.
Devices like microprocessor communicate and operate using binary digits ‘0’ & ‘1’ and
are referred to as ‘bits’. Every microprocessor has its own set of instructions which are in
the form of binary patterns called ‘machine language’. It is very difficult for the
programmer to communicate in the language of 0’s and 1’s, hence representation of
binary instructions in terms of abbreviated names called ‘mnemonics’ came into existence
and this became the language of microprocessors and is called as ‘assembly language’.
Arithmetic & Logic Unit: The purpose of this unit is to perform arithmetic
operations such as addition and subtraction and logical operations such as
ANDing, ORing, XORing & complementing.
Register Array: The CPU uses registers to store information temporarily such as
values to be processed, address of value to be fetched from memory during the
execution of program and are accessible to the user through instructions. Registers
can be 8- bit, 16- bit, 32- bit, or 64-bit. In general, the more and bigger the
registers, the better the CPU. The disadvantage of more and bigger registers is the
increased cost of such a CPU.
Accumulator: It is the most versatile register that is used to hold the results of
many instructions particularly arithmetic and logical
Stack pointer: The word ‘stack’ refers to the set of memory locations in the R/W
memory which stores data byte temporarily during the execution of a program.
Stack pointer is a register that tracks the storage & retrieval of the information. An
address in the stack pointer indicates that the next two memory locations can be
used for storage.
Clock signals: clock signals control the generation of control signals. All actions
are initiated either by leading edge or by trailing edge of the clock and takes fixed
number of clock periods to complete the task. These provide the basic timing
signal for computer operations.
Microcontrollers: Figure 1.2 shows the block diagram of typical microcontroller, which
is a true computer on a chip. The design approach of the microcontroller mirrors that of
the microprocessor. The microcontroller also had other features needed to make a
complete computer: ROM, RAM, I/O capability, counters etc. Some of the benefits of
microcontrollers include the following:
Lesser power usage: Microcontrollers are generally built using a technology known as
Complementary Metal Oxide Semiconductor (CMOS). This technology is a competent
fabrication system that uses less power and is more immune to power spikes than other
techniques.
All-in-one: A microcontroller usually comprises of a CPU, ROM, RAM and I/O ports,
built within it to execute a single and dedicated task. On the other hand, a microprocessor
generally does not have a RAM, ROM or IO pins and generally uses its pins as a bus to
interface to peripherals such as RAM, ROM, serial ports, digital and analog IO.
It consists of
Timers/ Counters: Timers may be used to create time delay and counter may be
used to count the external events happening outside the microcontroller that
occurred within a time interval.
I/O Ports: This helps in transferring data and instructions in binary from the
outside world to the microcontroller and vice versa.
Internal RAM & ROM: The function of the memory is to store information, almost
as same as that of register. Programs and data are stored in memory. Memory
section usually a mixture of RAM(to store data) & ROM(to store code and may
be data) or in other words mixture of volatile & non volatile memory and it has
two important purposes
Microprocessors Microcontrollers
CPU is stand alone. RAM, ROM, timers are all CPU,RAM, ROM, timers are all
separate and are to be interfaced with CPU located on a single chip
They are Versatile & general purpose These are not very versatile
They have expansive applications These are used where cost, power &
space criteria are considered
Designer can decide the amount of RAM, ROM Fixed amount of ROM, RAM and I/O
that is required to be connected ports on chip
Access time for memory and I/O devices are Access time for memory and I/O
more devices are less
Very few instructions which have bit-handling Many instructions with bit-handling
capability. capability.
Figure below shows the general block diagram Figure below shows the general block
of microprocessor diagram of microcontroller
can be used for data storage and program instruction storage. For example, the Motorola
68HC11 microcontroller adopts Von- Neuman architecture.
The architectural block diagram of 8051 is shown in fig 1.5. The 8051 is a 40 – pin DIP
and most commonly used microcontroller. The specific features of 8051 are the
following:
A 16 – bit register called Program Counter (PC). It holds the address of the
location of the next instruction to be executed.
Sixteen bytes, which are bit addressable. The individual bits of these bytes
can be altered.
Four 8 – bit ports, P0 to P3. A port pins are used to send or to read data from
external devices.
Two 16 – bit timer/counter: Used as timers to generate delay between two events
with the help of internal clock pulses or used as a counter to count external pulses.
Full duplex serial data transmitter/receiver register, SBUF. This holds the byte to
be transmitted or the received byte, when serial communication is used.
Two external interrupts and three internal interrupts. Interrupts are events which
interrupt the normal sequence of execution of instructions.
Control registers: TCON, TMOD, SCON, PCON, IP and IE which control the
operations of the timers, serial ports and interrupts.
Each register, with the exception of the program counter, has an internal 1 – byte address
assigned to it. Some registers (marked with an asterisk ‘*‘ in fig 1.6) are both byte and bit
addressable. That is, the entire byte of data at such register addresses may be read or
altered, or individual bits may be read or altered. Software instructions are generally able
to specify a register by its address, its symbolic name, or both.
ALE/PROG (30): Address Latch Enable output pulse for latching the low byte of the
address during accesses to external memory. (ALE is emitted at a constant rate of 1/6 of
the oscillator frequency, for external timing or clocking purposes, even when there are no
accesses to external memory.) This pin is also the program pulse input (PROG) during
EPROM programming. PSEN (29): Program Store Enable is an active low output signal.
When 8051 wants access program code from external ROM, it is connected to enable pin
of ROM chip.
EA/VPP (31): When EA is held high the CPU access code from internal program
memory (unless the Program Counter exceeds 0FFFH in the 80C51). Holding EA pin
low, forces the CPU to access external program memory. This pin also receives the
programming supply voltage (VPP) during EPROM programming.
Ports: All ports are 8-bit bidirectional I/O ports. A port pins are used to send or to read
data from external devices. Each of these pins can be configured as an input or an output.
Port 0 (32 to 39) and Port 2 (21 to 28): P0 and P2 together provide the 16 – bit address
to access external memory i.e., AD0 to AD15. P0 provides the lower 8 – bit address (also
used as data lines) AD0 to AD7 and P2 provides the upper 8 – bit address A8 – A15.
Port 1 (1 to 8): Port 1 is an 8-bit bidirectional I/O port with internal pullups.
Port 3 (10 to 17): Port 3 is an 8-bit bidirectional I/O port with internal pullups. It also
serves the functions of various special features of the 8051 Family as follows:
VCC (40) and VSS (20): Supply voltage (+5v) and Circuit ground potential respectively.
Code memory (Internal ROM): It refers to the memory that holds the actual 8051
program that is to be run. This memory is limited to 64K and comes in many shapes and
sizes. Code memory may be found on-chip (4KB). Code may also be stored completely
off-chip in an external ROM (max of 64KB) or, more commonly, an external EPROM.
Flash RAM is also another popular method of storing a program.
Data memory (Internal RAM): The 8051 has 128 bytes of Internal RAM. This Internal
RAM is found on-chip on the 8051 so it is the fastest RAM available, and it is also the
most flexible in terms of reading, writing, and modifying its contents. Internal RAM is
volatile, so when the 8051 is reset this memory is cleared. The 128 bytes of internal RAM
is subdivided as shown on the memory map.
The 128 bytes of internal RAM is subdivided as shown on the memory map.
RAM location can be referred by their name (say R4) or by its address (04h)
Ex: ADD A, R4 or ADD A, 04H
Sixteen bytes, which are bit addressable (also byte addressable). The individual
bits of these bytes can be altered. Ex: SETB 07h
Eighty bytes of general purpose RAM memory from addresses 30h through
7Fh, may be used by user variables that need to be accessed frequently or at
high-speed. This area is also utilized by the microcontroller as a storage area for
the operating stack.
Special Function Registers (SFRs) are areas of memory that control specific functionality
of the 8051 processor. For example, four SFRs permit access to the 8051’s 32
input/output lines. Another SFR allows a program to read or write to the 8051’s serial
port. Other SFRs allow the user to set the serial baud rate, control and access timers, and
configure the 8051’s interrupt system. Fig 1.9 shows an organization of SFR in 8051. The
following two points should be noted about the SFR addresses.
✓ The SFR’s have addresses between 80h and ffh. These addresses are above 80h,
since the addresses 00h to 7fh are addresses of RAM memory inside the 8051.
✓ Not all the address space of 80h o ffh is used by the SFR. The unused locations
80h to ffh are reserved and must not be used by the 8051 programmer.
Carry Flag (CY): This flag is set whenever there is a carry (from bit D7) after an
addition or a borrow after subtraction. It can also be set to 0 or 1 using CLR C or SETB C
instruction respectively.
Auxiliary Carry Flag (AC): This flag is set whenever there is a carry from lower nibble
(bit D3) to higher nibble (bit D4) or a borrow from higher nibble (bit D4) to lower nibble
(bit D3).
Over Flow Flag (OV): This flag is set whenever the result of a signed arithmetic
operation is too large, causing the higher – order bit to overflow into sign bit. I t is used to
detect errors in signed arithmetic operations.
Parity Flag (P): This reflects the number of 1’s in the accumulator register. If it has odd
number of 1’s then P = 1 else P = 0.
RS1 & RS0: Select register bank as shown in figure 2.6. By default register bank 0 is
selected.
in the internal 4K ROM (0FFFh). The 8051 design can thus use internal and external
ROM automatically.
Figure 1.12 shows the timing diagram associated with external memory access cycle.
During any memory access cycle, port 0 is time multiplexed. That is, it first provides the
lower byte of the 16 – bit memory address, then act as a bidirectional data bus to write or
read a byte of memory data. Port 2 provides the higher byte of the memory address during
the entire memory read/write cycle.
The ALE clock pulse provides the correct timing for latch to save the lower byte address
of external memory.
PSEN (active low) pin will go low to enable the ROM to place a byte of program code
on data bus.
The WR (active low) and RD (active low) pins will go low, enabling data to flow
between the RAM and the data bus
The heart of the 8051 is the circuitry that generates the clock pulses by which all internal
operations are synchronized. Pins XTAL1 and XTAL2 are provided for connecting a
resonant network to form an oscillator. Typically a quartz crystal and capacitors are
employed, as shown in figure 1.13. The crystal frequency, typically 1MHz to 16MHz is
the basic internal clock frequency of microcontroller.
Serial data communication needs often dictate the frequency of the oscillator because of
the requirement that internal counters must divide the basic clock rate to yield standard
communication bit per second (baud) rates. If the basic clock frequency is not divisible
without a remainder, then the resulting communication frequency is not standard.
Ceramic resonator may be used as a low cost alternative to crystal resonators. However
decrease in frequency stability and accuracy make the ceramic resonator a poor choice if
the high speed data communication with other systems, or critical timing, is to be done.
A state is a basic time interval for discrete operation of microcontroller such as fetching
an opcode byte, decoding an opcode, executing an opcode, or writing a data byte.
Program instruction may require one, two, or four machine cycles to be executed,
depending on the type of instruction. The time required to execute an instruction is given
by,
Tinst = (C * 12) / crystal frequency, where C is the number of machine cycles
Example:
EXERCISE PROBLEMS:
Example A: Show the status of the CY, AC and P flag after the addition of 38H
and 2FH in the following instructions.
MOV A, #38H
ADD A, #2FH
Solution:
38 00111000
+ 2F 00101111
-------------------------
67 01100111
✓ ORG OriGinate, defines the starting address for the program in program (code)
memory
✓ EQU EQUate, assigns a numeric value to a symbol identifier so as to make the
program more readable.
✓ DB Define a Byte, puts a byte (8-bit number) number constant at this memory
location
✓ DW Define a Word, puts a word (16-bit number) number constant at this
memory location
✓ END This is the last statement in the source file to advise the assembler to stop
the assembly process.
Example:
Loop: MOV R1, #25H ; transfer 25H into R1
Note: Brackets indicates that a field is optional, and not all lines have them. The label
field allows the program to refer to a line of code by name. The label field cannot exceed
a certain number of characters.
Immediate Addressing
Register Addressing
Direct Addressing
Indirect Addressing
Relative Addressing
Absolute addressing
Long Addressing
Indexed Addressing
Immediate Addressing: Immediate addressing simply means that the operand (which
immediately follows the instruction opcode) is the data value to be used. For example the
instruction:
MOV A, #99d
Number 99d
Register Addressing: One of the eight general-registers, R0 to R7, can be specified as the
instruction operand. The assembly language documentation refers to a register generically
as Rn. Ex: ADD A, R5; Adds register R5 contents to A (accumulator)
Direct addressing: Means that the data value is obtained directly from the memory
location specified in the operand. For ex: MOV A, 47h. The instruction reads the data
from Internal RAM address 47h and stores this in the accumulator.
Direct addressing can be used to access Internal RAM , including the SFR registers.
MOV A, @R0
@ symbol indicates that it is indirect addressing mode. R0 contains a value, for example
54h, which is to be used as the address of the internal RAM location, which contains the
operand data. Indirect addressing refers to Internal RAM only and cannot be used to refer
to SFR registers.
Note: Only R0 or R1 can be used as register data pointers for indirect addressing when
using
MOV instructions.
Relative Addressing: This addressing mode is used only with certain jump instructions. A
relative address (or offset) is an 8-bit signed value, which is added to the program counter
to form the address of the next instruction executed. The range for such a jump instruction
is –128 to +127 locations. Although the range is rather limited, relative addressing does
offers the advantage of providing position-independent code (since absolute addresses are
not used). For example, the instruction
Absolute addressing: There are only two instructions that use this addressing: ACALL
(absolute call) and AJMP (absolute jump). These instructions perform branching within
the current 2K page of program memory. The branch address is obtained by successively
concatenating the five high-order bits of the program counter, bits 5 – 7 of the op-code,
and the second byte of the instruction. The diagram illustrates how this is done:
Note that the branch destination address is within the same 2K page of program memory
because the highest most five address bits are the same as those in the program counter
before the branch is taken.
Long Addressing: Only two instructions use this addressing mode. These instructions are
LCALL addr16 and LJMP addr16. Both of these are three byte instructions with the op-
code being the first byte and the following two bytes are the address high-byte and
address low-byte respectively. These instructions enable the program to branch to
anywhere within the full 64 K-bytes of program memory address space (216 = 64K).
An example instruction is: LJMP 5000h; full 16 bit address is specified in operand
Indexed Addressing: With indexed addressing a separate register, either the program
counter, PC, or the data pointer DTPR, is used as a base address and the accumulator is
used as an offset
address. The effective address is formed by adding the value from the base address to the
value from the offset address. Indexed addressing in the 8051 is used with the JMP or
MOVC instructions. Look up tables are easy to implement with the help of index
addressing.
MOVC is a move instruction, which moves data from the external code memory space.
The address operand in this example is formed by adding the content of the DPTR
register to the accumulator value. Here the DPTR value is referred to as the base address
and the accumulator value us referred to as the index address.
i. Data transfer
Many computer operations are concerned with moving data from one location to another.
The 8051 uses five different types of instruction to move data:
MOV MOVX MOVC PUSH and POP XCH
MOV
In the 8051 the MOV instruction is concerned with moving data internally, i.e. between
Internal RAM, SFR registers, general registers etc. MOVX and MOVC are used in
accessing external memory data. The MOV instruction has the following format:
The instruction copies (copy is a more accurate word than move) data from a defined
source location to a destination location. Example MOV instructions are:
MOVX
The 8051 the external memory can be addressed using indirect addressing only. The
DPTR register is used to hold the address of the external data (since DPTR is a 16-bit
register it can address 64KByte locations: 216 = 64K). The 8 bit registers R0 or R1 can
also be used for indirect addressing of external memory but the address range is limited to
the lower 256 bytes of memory (28 = 256 bytes).
The MOVX instruction is used to access the external memory (X indicates eXternal
memory access). All external moves must work through the A register (accumulator).
Examples of MOVX instructions are:
MOVC
MOVX instructions operate on RAM, which is (normally) a volatile memory. Program
tables often need to be stored in ROM since ROM is non-volatile memory. The MOVC
instruction is used to read data from the external code memory (ROM). Like the MOVX
instruction the DPTR register is used as the indirect address register. The indirect
addressing is enhanced to realize an indexed addressing mode where register A can be
used to provide an offset in the address specification. Like the MOVX instruction all
moves must be done through register A. The following sequence of instructions provides
an example:
MOV DPTR, # 2000h ; Copy the data value 2000h to the DPTR register
MOV A, #80h ; Copy the data value 80h to register A
MOVC A, @A+DPTR ; Copy the contents of the address 2080h (2000h + 80h) to register A
Note: for the MOVC the program counter can also be used to form the address.
XCH
The above move instructions copy data from a source location to a destination location,
leaving the source data unaffected. A special XCH (eXCHange) instruction will actually
swap the data between source and destination, effectively changing the source data.
Immediate addressing may not be used with XCH. XCH instructions must use register A.
XCHD is a special case of the exchange instruction where just the lower nibbles are
exchanged. Examples using the XCH instruction are:
ii. Arithmetic:
Some key flags within the PSW, i.e. C, AC, OV, P, are utilized in many of the arithmetic
instructions. The arithmetic instructions can be grouped as follows:
➢ Addition
➢ Subtraction
➢ Increment/decrement
➢ Multiply/divide
➢ Decimal adjust
Addition
Register A (the accumulator) is used to hold the result of any addition operation. Some
simple addition examples are:
The flags in the PSW register are affected by the various addition operations, as follows:
✓ The C (carry) flag is set to 1 if the addition resulted in a carry out of the
accumulator’s MSB bit, otherwise it is cleared.
✓ The AC (auxiliary) flag is set to 1 if there is a carry out of bit position 3 of the
accumulator, otherwise it is cleared.
✓ For signed numbers the OV flag is set to 1 if there is an arithmetic overflow
(described elsewhere in these notes)
Simple addition is done within the 8051 based on 8 bit numbers, but it is often required to
add 16 bit numbers, or 24 bit numbers etc. This leads to the use of multiple byte (multi-
precision) arithmetic. The least significant bytes are first added, and if a carry results, this
carry is carried over in the addition of the next significant byte etc. This addition process
is done at 8-bit precision steps to achieve multi precision arithmetic. The ADDC
instruction is used to include the carry bit in the addition process. Example instructions
using ADDC are:
ADDC A, #55h ; Add contents of A, the number 55h, the carry bit; and put the sum in A
ADDC A, R4 ; Add the contents of A, the register R4, the carry bit; and put the sum in A.
Subtraction
Computer subtraction can be achieved using 2’s complement arithmetic. Most computers
also provide instructions to directly subtract signed or unsigned numbers. The
accumulator, register A, will contain the result (difference) of the subtraction operation.
The C (carry) flag is treated as a borrow flag, which is always subtracted from the
minuend during a subtraction operation. Some examples of subtraction instructions are:
SUBB A, #55d ; Subtract the number 55 and the C flag from A; and put the result in A.
SUBB A, R6 ; Subtract R6 the C flag from A; and put the result in A.
SUBB A, 58h ; Subtract the number in RAM location 58h and the C flag From A; and
put the result in A.
Increment/Decrement
The increment (INC) instruction has the effect of simply adding a binary 1 to a number
while a decrement (DEC) instruction has the effect of subtracting a binary 1 from a
number. The increment and decrement instructions can use the addressing modes: direct,
indirect and register. The flags C, AC, and OV are not affected by the increment or
decrement instructions. If a value of FFh is increment it overflows to 00h. If a value of
00h is decrement it underflows to FFh. The DPTR can overflow from FFFFh to 0000h.
The DPTR register cannot be decremented using a DEC instruction (unfortunately!).
Some example INC and DEC instructions are as follows:
Multiply / Divide
The 8051 supports 8-bit multiplication and division. This is low precision (8 bit)
arithmetic but is useful for many simple control applications. The arithmetic is relatively
fast since multiplication and division are implemented as single instructions. If better
precision, or indeed, if floating point arithmetic is required then special software routines
need to be written. For the MUL or DIV instructions the A and B registers must be used
and only unsigned numbers are supported. Flags affected are OV and CY.
Multiplication
The MUL instruction is used as follows (note absence of a comma between the A and
B operands): MUL AB; Multiply A by B. The resulting product resides in registers A
and B, the low-order byte is in A and the high order byte is in B.
Division
The DIV instruction is used as follows:
DIV AB ; A is divided by B.
The remainder is put in register B and the integer part of the quotient is put in register
A.
Decimal Adjust (Special)
The 8051 performs all arithmetic in binary numbers (i.e. it does not support BCD
arithmetic). If two BCD numbers are added then the result can be adjusted by using the
DA, decimal adjust, instruction:
DA A ; Decimal adjust A following the addition of two BCD numbers.
The following Boolean operations can operate on byte level or bit level data:
The destination address of the operartion can be the accumulator (register A), a general
register, or a direct address. Status flags are not affected by these logical operations
(unless PSW is directly manipulated). Example instructions are:
ANL A, #55h ; AND each bit in A with corresponding bit in number 55h, leaving the
result in A.
ANL 42h, R4 ; AND each bit in RAM location 42h with corresponding bit in R4, leaving
the result in RAM location 42h.
ORL A,@R1 ; OR each bit in A with corresponding bit in the number whose address is
contained in R1 leaving the result in A.
XRL R4, 80h ; XOR each bit in R4 with corresponding bit in RAM location 80h (port 0),
leaving result in A.
CPL R0 ; Complement each bit in R0
Rotate Instructions
The ability to rotate the A register (accumulator) data is useful to allow examination of
individual bits. The options for such rotation are as follows:
RL A ; Rotate A one bit to the left. Bit 7 rotates to the bit 0 position
RLC A ; The Carry flag is used as a ninth bit in the rotation loop
Swap =
special
The Swap
instruction
swaps the accumulator’s high order nibble with the low-order nibble using the instruction:
LJMP
LJMP (long jump) causes the program to branch to a destination address defined by the
16-bit operand in the jump instruction. Because a 16-bit address is used the instruction
can cause a jump to any location within the 64KByte program space (216 = 64K). Some
example instructions are:
SJMP
SJMP (short jump) uses a single byte address. This address is a signed 8-bit number and
allows the program to branch to a distance –128 bytes back from the current PC address
or +127 bytes forward from the current PC address. The address mode used with this
form of jumping (or branching) is referred to as relative addressing, introduced earlier, as
the jump is calculated relative to the current PC address.
AJMP
This is a special 8051 jump instruction, which allows a jump with a 2KByte address
boundary (a 2K page) There is also a generic JMP instruction supported by many 8051
assemblers. The assembler will decide which type of jump instruction to use, LJMP,
SJMP or AJMP, so as to choose the most efficient instruction.
Note, jump instructions such as DJNZ and CJNE are very powerful as they carry out a
particular operation (e.g.: decrement, compare) and then make a decision based on the
result of this operation. Some example code later will help to explain the context in which
such instructions might be used.
v. Boolean Instructions:
The 8051 has a range of Boolean variable manipulating instructions which enable us to
set or reset individual bits within some of the locations in the internal RAM, and some of
the special function registers. We give some examples of these instructions in the table
below.
The following SFR registers are addressable in bit level operations: PSW, IE, IP, TCON,
SCON.
1. Write a program to add the values of locations 50H and 51H and store the result in
locations in 52h and 53H.
2. Write a program to store data FFH into RAM memory locations 50H to 58H using direct
addressing mode
END
3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-56H
and store the result in locations 40H and 41H. Assume that the least significant byte of data or
the result is stored in low address. If the result is positive, then store 00H, else store 01H in
42H.
END
4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H and
store the result in locations 40H, 41H and 42H. Assume that the least significant byte of data
and the result is stored in low address and the most significant byte of data or the result
is stored in high address.
END
5. Write a program to store data FFH into RAM memory locations 50H to 58H using indirect
addressing mode.
END
6. Write a program to add two Binary Coded Decimal (BCD) numbers stored at locations 60H
and 61H and store the result in BCD at memory locations 52H and 53H. Assume that the
least significant byte of the result is stored in low address.
END
END
8. Write a program to compute 1 + 2 + 3 + N (say N=15) and save the sum at70H
ORG 0000H ; Set program counter 0000H
N EQU 15
; Clear R0
MOV R0,#00
CLR A ; Clear A
again: INC R0 ; Increment R0
ADD A, R0 ; Add the contents of R0 with A
CJNE R0,#N,again ; Loop until counter, R0, N
9. Write a program to multiply two 8 bit numbers stored at locations 70H and 71H and store
the result at memory locations 52H and 53H. Assume that the least significant byte of the
result is stored in low address.
END
10. Ten 8 bit numbers are stored in internal data memory from location 5oH. Write a
program to increment the data.
Assume that ten 8 bit numbers are stored in internal data memory from location 50H, hence
R0 or R1 must be used as a pointer.
The program is as follows.
OPT 0000H
MOV R0,#50H
MOV R3,#0AH
Loopl: INC @R0
INC RO
DJNZ R3, loopl END
END
11. Write a program to find the average of five 8 bit numbers. Store the result in H.
(Assume that after adding five 8 bit numbers, the result is 8 bit only).
ORG 0000H
MOV 40H,#05H
MOV 41H,#55H
MOV 42H,#06H
MOV 43H,#1AH
MOV 44H,#09H
MOV R0,#40H
MOV R5,#05H
MOV B,R5
CLR A
Loop: ADD A,@RO
INC RO
DJNZ R5,Loop
DIV AB
MOV 55H,A
END
12. Write a program to find the cube of an 8 bit number program is as follows
ORG 0000H
MOV R1,#N
MOV A,R1 //SQUARE IS COMPUTED
MOV B,R1
MUL AB
MOV R2, B
MOV B, R1
MUL AB
MOV 50,A
MOV 51,B
MOV A,R2
MOV B, R1
//CUBE IS STORED IN 52H,51H,50H
MUL AB
ADD A, 51H
MOV 51H, A
MOV 52H, B
MOV A, # 00H
ADDC A, 52H
MOV 52H, A
END
13. Write a program to exchange the lower nibble of data present in external memory 6000H and
6001H
END
14. Write a program to count the number of and o's of 8 bit data stored in location 6000H.
END
16. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory. Write
a program to find the GCD of the numbers and store the result in 2000h.
ALGORITHM
• Step 1 :Initialize external data memory with data and DPTR with address
• Step 2 :Load A and TEMP with the operands
• Step 3 :Are the two operands equal? If yes, go to step 9
• Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
• Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
• Step 6 :Perform division operation (contents of A with contents of TEMP)
• Step 7 :If the remainder is zero, go to step 9
• Step 8 :Move the remainder into A and go to step 4
• Step 9 :Save the contents 'of TEMP in memory and terminate the program
END
• RAM locations from 08H to 1FH can be used as stack. Stack is used to store the data
temporarily. Stack is last in first out (LIFO)
• Stack pointer (SP)
✓ 8bit register
✓ It indicates current RAM address available for
stack or it points the top of stack.
✓ Initially by default at 07H because first location of
stack is 08H.
✓ After each PUSH instruction the SP is incremented
by one while in MC after PUSH instruction SP is
decremented.
✓ After each POP instruction the SP is decremented.
PUSH 4Ch ; Contents of RAM location 4Ch is saved to the stack. SP is incremented.
PUSH 00h ; The content of R0 (which is at 00h in RAM) is saved to the stack and SP is
incremented.
POP 80h ; The data from current SP address is copied to 80h and SP is decremented.
Example:
MOV R6,#25H;
MOV R1,#12H;
MOV R4,#OF3H;
PUSH 06H;
PUSH 01H;
POP 04H;
• If we want to use other than 24byte (08H to 1FH) of stack. We can change SP to point
RAM address 30H to 7FH by MOV SP, #XX ; Any value from 30 to 7FH
• We know locations from 08H to 1FH is used as stack and it is also used as register
bank.
• If in the program, we use the Register Bank 1 to 3 and also use the stack then
conflicts exist and error can be possible.
• For removing this situation we use the stack from location 30H to 7FH by shifting
SP to 2FH. MOV SP,#2FH;
Example A: Show the stack and stack pointer from the following. Assume the default
stack area.
Solution:
Example B: Examining the stack, show the contents of the register and SP after
execution of the following instructions. All value are in hex.
Solution:
LCALL
This instruction is used to call a subroutine at a specified address. The address is 16 bits
long so the call can be made to any location within the 64KByte memory space. When a
LCALL instruction is executed the current PC content is automatically pushed onto the
stack of the PC. When the program returns from the subroutine the PC contents is
returned from the stack so that the program can resume operation from the point where
the LCALL was made The return from subroutine is achieved using the RET instruction,
which simply pops the PC back from the stack.
The LCALL instruction works as follows.
a. During execution of LCALL, [PC] = [PC]+3; (if address where LCALL resides is say,
0x3254; during execution of this instruction [PC] = 3254h + 3h = 3257h
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and [SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie., 57 will be stored in memory location
08.
d.[SP]=[SP]+1; (SP increments again and [SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 32 will be stored in memory location
09. With these the address (0x3254) which was in PC is stored in stack.
f. [PC]= address (16 bit); the new address of subroutine is loaded to PC. No flags are
affected
ACALL
The ACALL instruction is logically similar to the LCALL but has a limited address range
similar to the AJMP instruction. CALL is a generic call instruction supported by many
8051 assemblers. The assembler will decide which type of call instruction, LCALL or
ACALL, to use so as to choose the most efficient instruction.
a. During execution of ACALL, [PC] = [PC]+2; (if address where LCALL resides is say,
0x8549; during execution of this instruction [PC] = 8549h + 2h = 854Bh
b. [SP]=[SP]+1; (if SP contains default value 07, then SP increments and [SP]=08
c. [[SP]] = [PC7-0]; (lower byte of PC content ie., 4B will be stored in memory location
08.
d. [SP]=[SP]+1; (SP increments again and [SP]=09)
e. [[SP]] = [PC15-8]; (higher byte of PC content ie., 85 will be stored in memory location
09. With these the address (0x854B) which was in PC is stored in stack
f. [PC10-0]= address (11 bit); the new address of subroutine is loaded to PC. No flags are
affected
RET instruction
RET instruction pops top two contents from the stack and load it to PC.
a. [PC15-8] = [[SP]] ;content of current top of the stack will be moved to higher byte of
PC.
b. [SP]=[SP]-1; (SP decrements)
c. [PC7-0] = [[SP]] ;content of bottom of the stack will be moved to lower byte of PC.
d. [SP]=[SP]-1; (SP decrements again)
✓ The length of machine cycle depends on the frequency of the crystal oscillator
connected to 8051
✓ In original 8051, one machine cycle lasts 12 oscillator periods
Example (3.5.1): Find the period of the machine cycle for 11.0592 MHz crystal
frequency and find how long it takes to execute each instruction.
(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target
(d) LJMP (e) SJMP (f) NOP (g) MUL AB
Solution:
11.0592/12 = 921.6 kHz;
machine cycle is 1/921.6 kHz = 1.085μs
MOV A,#55H
AGAIN: MOV P1,A
ACALL DELAY
CPL A
SJMP AGAIN
;---time delay-------
Solution:
Machine cycle
Example (3.5.3): Find the size of the delay in following program, if the crystal frequency
is 11.0592MHz.
Machine Cycle
DELAY: MOV R3,#250 1
HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2
RET 2
Solution:
Example (3.5.4): Find the size of the delay in following program, if the crystal frequency
is 11.0592MHz.
Machine Cycle
DELAY: MOV R2,#200 1
AGAIN: MOV R3,#250 1
HERE: NOP 1
NOP 1
DJNZ R3,HERE 2
DJNZ R2,AGAIN 2
RET 2
Solution:
Note: the time is approximate since we have ignored the first and last instructions in the
subroutine.
------------------------------------------------------------------------------------------------------------
3.5.3 DELAY CALCULATION FOR OTHER 8051:
Crystal frequency: The duration of the clock period of the machine cycle is a function of
this crystal frequency
8051 design: The original machine cycle duration was set at 12 clocks.
Advances in both IC technology and CPU design in recent years have made the 1-clock
machine cycle a common feature
AT89C51 Atmel 12
P89C54X2 Philips 6
DS5000 Dallas Semi 4
DS89C420/30/40/50 Dallas Semi 1
Example (3.5.5): Find the period of the machine cycle (MC) for various versions of
8051, if XTAL=11.0592 MHz. (a) AT89C51 (b) P89C54X2 (c) DS5000 (d) DS89C4x0
Solution:
(a) 11.0592MHz/12 = 921.6kHz;
MC period is 1/921.6kHz = 1.085μs = 1085ns
(b) 11.0592MHz/6 = 1.8432MHz;
MC period is 1/1.8432MHz = 0.5425μs = 542ns
(c) 11.0592MHz/4 = 2.7648MHz ;
MC period is 1/2.7648MHz = 0.36μs = 360ns
(d) 11.0592MHz/1 = 11.0592MHz;
MC period is 1/11.0592MHz = 0.0904μs = 90ns
------------------------------------------------------------------------------------------------------------
Example (3.5.6): For an AT8051 and DSC89C4x0 system of 11.0592 MHz, find how
long it takes to execute each instruction.
Solution:
AT8051 DS89C4x0
------------------------------------------------------------------------------------------------------------
4.3 TIMER PROGRAMMING
The 8051 has two timers/counters, they can be used either as
Both Timer 0 and Timer 1 are 16 bits wide. Since 8051 has an 8-bit architecture, each 16-
bits timer is accessed as two separate registers of low byte (TL0/TL1) and high byte
(TH0/TH1). Accessed like any other register. Ex: MOV TL0,#4FH
MOV R5,TH0
Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various
timer operation modes. TMOD is a 8-bit register.
Example 4.3.1: Indicate which mode and which timer are selected for each of the
following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H
Solution:
We convert the value from hex to binary. From Figure 9-3 we have:
(a) TMOD = 00000001, mode 1 of timer 0 is selected.
(b) TMOD = 00100000, mode 2 of timer 1 is selected.
(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected.
------------------------------------------------------------------------------------------------------------
Example 4.3.2: Find the timer’s clock frequency and its period for various 8051-based
system, with the crystal frequency 11.0592 MHz when C/T bit of TMOD is 0.
Solution:
1. Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be
used and which timer mode (0 or 1) is selected
2. Load registers TL and TH with initial count value
3. Start the timer
4. Keep monitoring the timer flag (TF) with the JNB TFx, target instruction to see if it is
raised. Get out of the loop when TF becomes high
5. Stop the timer
6. Clear the TF flag for the next round
7. Go back to Step 2 to load TH and TL again
Example 4.3.3: In the following program, we create a square wave of 50% duty cycle
(with equal portions high and low) on the P1.5 bit. Timer 0 is used to generate the
time delay. Analyze the program
Solution:
1. TMOD is loaded.
2. FFF2H is loaded into TH0-TL0.
3. P1.5 is toggled for the high and low portions of the pulse.
4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal
oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5,
FFF6,
FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more clock
rolls
it to 0, raising the timer flag (TF0=1).
7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends, and the
process is repeated.
Note: To repeat the process, we must reload the TL and TH registers, and the process is
Repeated
------------------------------------------------------------------------------------------------------------
Example 4.3.4: In Example 4.3.3, calculate the amount of time delay in the DELAY
subroutine generated by the timer and also calculate the frequency of the square wave.
Assume XTAL = 11.0592 MHz.
Solution:
Solution:
(a) (FFFFH – B83E + 1) = 47C2H = 18370 in decimal and 18370 × 1.085 us = 19.93 ms
(b) Since THTL = B83EH = 47166 (in decimal) we have 65536 – 47166 = 18370. This
means that the timer counts from B38EH to FFFF. This plus Rolling over to 0 goes
through a total of 18370 clock cycles, where each clock is 1.085 us in duration.
(a) In hex
Td = (FFFF – THTL + 1) × 1.085 us,
Notice that value THTL are in hex.
(b) In decimal
Convert values of the TH, TL register to decimal, then
Td = (65536 - NNNN) × 1.085 us
Where Td is time delay to be generated
Example 4.3.6: Assume that XTAL = 11.0592 MHz, write a program to generate a
square wave of 2 kHz frequency on pin P1.5.
Solution:
This is similar to Example 9-10, except that we must toggle the bit to generate the square
wave. Look at the following steps.
ORG 0000H
MOV TMOD,#01 ;Timer 0, 16-bitmode
AGAIN: MOV TL1,#1AH ;TL1=1A, low byte of timer
MOV TH1,#0FFH ;TH1=FF, the high byte
SETB TR1 ;Start timer 1
BACK: JNB TF1,BACK ;until timer rolls over
CLR TR1 ;Stop the timer 1
CLR P1.5 ;Clear timer flag 1
CLR TF1 ;Clear timer 1 flag
SJMP AGAIN ;Reload timer
END
------------------------------------------------------------------------------------------------------------
Example 4.3.7: Examine the following program and find the time delay in seconds.
Exclude the overhead due to the instructions in the loop.
Solution:
-----------------------------------------------------------------------------------------------------------
1. It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded into the
timer’s register TH
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then the
timer must be started. This is done by the instruction SETB TR0 for timer 0 and SETB
TR1 for timer 1
3. After the timer is started, it starts to count up by incrementing the TL register. It counts
up until it reaches its limit of FFH. When it rolls over from FFH to 00, it sets high the
TF (timer flag).
4. When the TL register rolls from FFH to 0 and TF is set to 1, TL is reloaded
automatically with the original value kept by the TH register
✓ To repeat the process, we must simply clear TF and let it go without any need by
the programmer to reload the original value
✓ This makes mode 2 an auto-reload, in contrast with mode 1 in which the
programmer has to reload TH and TL
1. Load the TMOD value register indicating which timer (timer 0 or timer 1) is to be
used, and the timer mode (mode 2) is selected
2. Load the TH registers with the initial count value
3. Start timer
4. Keep monitoring the timer flag (TF) with the JNB TFx, target instruction to see
whether it is raised
✓ Get out of the loop when TF goes high
5. Clear the TF flag
6. Go back to Step4, since mode 2 is autoreload
Example 4.3.8: Assume XTAL = 11.0592 MHz, find the frequency of the square wave
generated on pin P1.0 in the following program
ORG 0000H
MOV TMOD,#20H ;T1/8-bit/auto reload
MOV TH1,#5 ;TH1 = 5
Solution:
First notice the target address of SJMP. In mode 2 we do not need to reload TH since it is
auto-reload.
Now (256 - 05) × 1.085 us = 251 × 1.085 us = 272.33 us is the high portion of the pulse.
Since it is a 50% duty cycle square wave, the period T is twice of that.
Therefore, T = 2 × 272.33 us = 544.67 us and the frequency = 1.83597 kHz
------------------------------------------------------------------------------------------------------------
Example 4.3.9: Find the frequency of a square wave generated on pin P1.0 in the
following Code
Solution:
You can use the Windows scientific calculator to verify the result provided by the
assembler. In Windows calculator, select decimal and enter 200. Then select hex, then +/-
to get the TH value. Remember that we only use the right two digits and ignore the rest
since our data is an 8-bit data.
Note: The number 200 is the timer count till the TF is set to 1
The advantage of using negative values is that you don’t need to calculate the value
loaded to THx
------------------------------------------------------------------------------------------------------------
4.3.3 PROGRAMMING TIMERS IN C:
Example 4.3.11: Write an 8051 C program to toggle all the bits of port P1 continuously
with 50ms delay. Use Timer 0, 16-bit mode to generate the delay.
Solution:
#include <reg51.h>
void T0Delay(void);
void main(void)
{
while (1)
{
P1=~P1;
T0Delay();
}
}
void T0Delay(void)
{
TMOD=0x01;
TL0=0xfd;
TH0=0x4b;
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;
}
------------------------------------------------------------------------------------------------------------
Example 4.3.12: Write an 8051 C program to toggle all bits of P2 continuously every
500ms. Use Timer 1, mode 1 to create the delay.
Solution:
Hence we are generating a time delay of 25ms and repeating the same for 20 times.
#include <reg51.h>
void T1M1Delay(void);
void main(void)
{
unsigned char x;
P2=0x55;
while (1)
{
P2=~P2;
for (x=0;x<20;x++)
T1M1Delay();
}
}
void T1M1Delay(void)
{
TMOD=0x10;
TL1=0xFE;
TH1=0xA5;
TR1=1;
while (TF1==0);
TR1=0;
TF1=0;
}
------------------------------------------------------------------------------------------------------------
Example 4.3.13: A switch is connected to pin P1.2. Write an 8051 C program to monitor
SW and create the following frequencies on pin P1.7: SW=0: 500Hz, SW=1: 750Hz, use
Timer 0, mode 1 for both of them.
Solution:
#include <reg51.h>
sbit mybit=P1^5;
sbit SW=P1^7;
void T0M1Delay(unsigned char);
void main(void)
{
SW=1;
while (1)
{
mybit=~mybit;
if (SW==0)
T0M1Delay(0);
else
T0M1Delay(1);
}
}
Example 4.3.14: Write an 8051 C program to create a frequency of 2500 Hz on pin P2.7.
Use Timer 1, mode 2 to create delay.
Solution:
For, 2500Hz
Cycle period = 1/2500Hz = 400 μs
Half cycle period = 400 μs /2 = 200 μs
Time delay, Td = [FF – TH + 1] * 1.085μs = 200 μs
Therefore, TH0TL0 = 48h = -184d
Or
Timers can also be used as counters counting events happening outside the 8051
✓ When it is used as a counter, it is a pulse outside the 8051 that increments the
TH, TL registers
✓ TMOD and TH, TL registers are the same as for the timer discussed previously
✓ Programming the timer in the last section also applies to programming it as a
counter, except the source of the frequency
✓ The C/T bit in the TMOD registers decides the source of the clock for the timer
✓ When C/T = 1, the timer is used as a counter and gets its pulses from outside the
8051.The counter counts up as pulses are fed from pins 14 and 15, these pins are
called T0 (timer 0 input) and T1 (timer 1 input)
If GATE = 1, the start and stop of the timer are done externally through pins P3.2 and
P3.3 for timers 0 and 1, respectively. This hardware way allows start or stop the timer
externally at any time via a simple switch
THTL
------------------------------------------------------------------------------------------------------------
Example 4.4.1: Assuming that clock pulses are fed into pin T1, write a program for
counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2,
which connects to 8 LEDs.
Solution:
MOV TM0D,#01100000B ;counter 1, mode 2, C/T=1 external pulses
MOV TH1,#0 ;clear TH1
SETB P3.5 ;make T1 input
AGAIN: SETB TR1 ;start the counter
BACK: MOV A,TL1 ;get copy of TL
MOV P2,A ;display it on port 2
JNB TF1,Back ;keep doing, if TF = 0
CLR TR1 ;stop the counter 1
CLR TF1 ;make TF=0
SJMP AGAIN ;keep doing it
Notice in the above program the role of the instruction SETB P3.5. Since ports are set up
for output when the 8051 is powered up, we make P3.5 an input port by making it high.
In other words, we must configure (set high) the T1 pin (pin P3.5) to allow pulses to be
fed into it.
------------------------------------------------------------------------------------------------------------
4.4.1 C PROGRAMMING OF TIMERS AS COUNTERS:
Example 4.4.2: Assume that a 1-Hz external clock is being fed into pin T1 (P3.5). Write
a C program for counter 1 in mode 2 (8-bit auto reload) to count up and display the state
of the TL1 count on P1. Start the count at 0H.
Solution:
#include <reg51.h>
sbit T1=P3^5;
void main(void)
{
T1=1; Make P3^5 to act as an input port
TMOD=0x60;
TH1=0;
while (1)
{
do
{
TR1=1;
P1=TL1;
}
while (TF1==0);
TR1=0;
TF1=0;
}
}
-----------------------------------------------------------------------------------------------------------
Example 4.4.3: Assume that a 1-Hz external clock is being fed into pin T0 (P3.4). Write
a C program for counter 0 in mode 1 (16-bit) to count the pulses and display the state of
the TH0 and TL0 registers on P2 and P1, respectively.
Solution:
#include <reg51.h>
void main(void)
{
T0=1;
TMOD=0x05;
TL0=0
TH0=0;
while (1)
{
do
{
TR0=1;
P1=TL0;
P2=TH0;
}
while (TF0==0);
TR0=0;
TF0=0;
}
}
✓ Parallel
• Often 8 or more lines (wire conductors) are used to transfer data to a device
that is only a few feet away
✓ Serial
• To transfer to a device located many meters away, the serial method is used
• The data is sent one bit at a time
✓ At the transmitting end, the byte of data must be converted to serial bits using
parallel-in-serial-out shift register
✓ At the receiving end, there is a serial-in- parallel-out shift register to receive the
serial data and pack them into byte
✓ When the distance is short, the digital signal can be transferred as it is on a simple
wire and requires no modulation
✓ If data is to be transferred on the telephone line, it must be converted from 0s and
1s to audio tones. This conversion is performed by a device called a modem,
“Modulator/demodulator”
It is possible to write software to use either of these methods, but the programs can be
tedious and long. There are special IC chips made by many manufacturers for serial
communications
This is contrast to simplex transmission, such as printers, in which the computer only
sends data.
------------------------------------------------------------------------------------------------------------
5.1.2 START AND STOP BITS:
✓ Each character is placed in between start and stop bits, this is called framing
✓ The start bit is always one bit, but the stop bit can be one or two bits
✓ The start bit is always a 0 (low) and the stop bit(s) is 1 (high)
✓ Due to the extended ASCII characters, 8-bit ASCII data is common. In older
systems, ASCII characters were 7-bit.
✓ Assuming that we are transferring a text file of ASCII characters using 1 stop bit,
we have a total of 10 bits for each character
• This gives 25% overhead, i.e. each 8-bit character with an extra 2 bits
✓ In some systems in order to maintain data integrity, the parity bit of the character
byte is included in the data frame
• UART chips allow programming of the parity bit for odd-, even-, and no-parity
options
------------------------------------------------------------------------------------------------------------
5.1.3 DATA TRANSFER RATE:
✓ The rate of data transfer in serial data communication is stated in bps (bits per
second).
✓ Another widely used terminology for bps is baud rate
• It is modem terminology and is defined as the number of signal changes
per second
• In modems, there are occasions when a single change of signal transfers
several bits of data
✓ As far as the conductor wire is concerned, the baud rate and bps are the
Since not all pins are used in PC cables (i.e. DB-25), IBM introduced the DB-9 version of
the serial I/O standard.
------------------------------------------------------------------------------------------------------------
5.1.5 DATA COMMUNICATION CLASSIFICATION:
✓ DTE (data terminal equipment) refers to terminal and computers that send and
receive data
✓ DCE (data communication equipment) refers to communication equipment, such
as modems
✓ The simplest connection between a PC and microcontroller requires a minimum of
three pins, TxD, RxD, and ground
DTR (data terminal ready) : When terminal is turned on, it sends out signal DTR to
indicate that it is ready for communication
DSR (data set ready) : When DCE is turned on and has gone through the self-test,
it assert DSR to indicate that it is ready to communicate
RTS (request to send) : When the DTE device has byte to transmit, it assert RTS
to signal the modem that it has a byte of data to transmit
CTS (clear to send) : When the modem has room for storing the data it is to
receive, it sends out signal CTS to DTE to indicate that it
can receive the data now
DCD (data carrier detect) : The modem asserts signal DCD to inform the DTE that a
valid carrier has been detected and that contact between it
and the other modem is established
RI (ring indicator) : An output from the modem and an input to a PC indicates
that the telephone is ringing. It goes on and off in
synchronous with the ringing sound.
5.2 8051 CONNECTION TO RS232:
The 8051 has two pins that are used specifically for transferring and receiving data
serially.
✓ These two pins are called TxD and RxD and are part of the port 3 group (P3.0 and
P3.1)
✓ These pins are TTL compatible; therefore, they require a line driver(MAX232) to
make them RS232 compatible
✓ One advantage of the MAX232 chip is that it uses a +5V power source which, is
the same as the source voltage for the 8051.
✓ The MAX232 has two set of line drivers for transferring and receiving data, as
shown in figure.
✓ MAX2323 requires four capacitors ranging from 1uF to 22uF. The most widely
used value of these capacitors is 22uF.
To save board space, some designers use MAX233 chip from Maxim
✓ MAX233 performs the same job as MAX232 but eliminates the need for
capacitors
✓ Notice that MAX233 and MAX232 are not pin compatible
To allow data transfer between the PC and an 8051 system without any error, we must
make sure that the baud rate of 8051 system matches the baud rate of the PC’s COM port.
Hyper-terminal function supports baud rates much higher than listed below.
PC Baud Rates:
------------------------------------------------------------------------------------------------------------
Example 5.3.1: With XTAL = 11.0592 MHz, find the TH1 value needed to have the
following baud rates. (a) 9600 (b) 2400 (c) 1200
Solution:
The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz, and 921.6 kHz / 32 =
28,800 Hz is frequency by UART to timer 1 to set baud rate.
(a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
(b) 28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
(c) 28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1
Notice that dividing 1/12 of the crystal frequency by 32 is the default value upon
activation of the 8051 RESET pin.
------------------------------------------------------------------------------------------------------------
5.3.1 SBUF REGISTER:
✓ For a byte data to be transferred via the TxD line, it must be placed in the SBUF
register. The moment a byte is written into SBUF, it is framed with the start and
stop bits and transferred serially via the TxD line
✓ SBUF holds the byte of data when it is received by 8051 RxD line. When the bits
are received serially via RxD, the 8051 deframes it by eliminating the stop and
start bits, making a byte out of the data received, and then placing it in SBUF
SCON is an 8-bit register used to program the start bit, stop bit, and data bits of data
framing, among other things.
SM0, SM1: They determine the framing of data by specifying the number of bits Per
character, and the start and stop bits
In programming the 8051 to transfer character bytes serially the following steps must
be taken.
1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2
(8-bit auto- reload) to set baud rate
2. The TH1 is loaded with one of the values to set baud rate for serial data transfer
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is framed with start and stop bits
4. TR1 is set to 1 to start timer 1
Solution:
Importance of TI Flag:
The steps that 8051 goes through in transmitting a character via TxD
In programming the 8051 to receive character bytes serially, the following steps must be
taken
1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2
(8-bit auto-reload) to set baud rate
2. TH1 is loaded to set baud rate
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-
bit data is framed with start and stop bits
4. TR1 is set to 1 to start timer 1
5. RI is cleared by CLR RI instruction
6. The RI flag bit is monitored with the use of instruction JNB RI,xx to see if an entire
character has been received yet
7. When RI is raised, SBUF has the byte; its contents are moved into a safe place
8. To receive the next character, go to step 5
------------------------------------------------------------------------------------------------------------
Example 5.3.4: Write a program for the 8051 to receive bytes of data serially, and put
them in P1, set the baud rate at 4800, 8-bit data, and 1 stop bit
Solution:
Solution:
ORG 0
MOV P2,#0FFH ;make P2 an input port
MOV TMOD,#20H ;timer 1, mode 2
MOV TH1,#0FAH ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
MOV DPTR,#MYDATA ;load pointer for message
H_1: CLR A
MOV A,@A+DPTR ;get the character
JZ B_1 ;if last character get out
ACALL SEND ;otherwise call transfer
INC DPTR ;next one
SJMP H_1 ;stay in loop
B_1: MOV a,P2 ;read data on P2
ACALL SEND ;transfer it serially
ACALL RECV ;get the serial data
MOV P1,A ;display it on LEDs
SJMP B_1 ;stay in loop indefinitely
;-----The message---------------
------------------------------------------------------------------------------------------------------------
Importance of RI Flag:
In receiving bit via its RxD pin, 8051 goes through the following steps.
1. It receives the start bit. Indicating that the next bit is the first bit of the character byte it
is about to receive
2. The 8-bit character is received one bit at a time
3. The stop bit is received. When receiving the stop bit 8051 makes RI = 1, indicating that
an entire character byte has been received and must be picked up before it gets
overwritten by an incoming character
4. By checking the RI flag bit when it is raised, we know that a character has been
received and is sitting in the SBUF register. We copy the SBUF contents to a safe
place in some other register or memory before it is lost
5. After the SBUF contents are copied into a safe place, the RI flag bit must be forced to 0
by CLR RI in order to allow the next received character byte to be placed in SBUF.
Failure to do this causes loss of the received character
There are two ways to increase the baud rate of data transfer
PCON register is an 8-bit register. When 8051 is powered up, SMOD is zero. We can set
it to high by software and thereby double the baud rate.
------------------------------------------------------------------------------------------------------------
Example 5.3.6: Assume that XTAL = 11.0592 MHz for the following program, state (a)
what this program does, (b) compute the frequency used by timer 1 to set the baud rate,
and (c) find the baud rate of the data transfer.
H_1: JNB TI,H_1 ;stay here until the last bit is gone
SJMP A_1 ;keep sending “B” again
Solution:
(a) This program transfers ASCII letter B (01000010 binary) continuously
(b) With XTAL = 11.0592 MHz and SMOD = 1 in the above program, we have:
Solution:
With XTAL = 11.0592 and SMOD = 1, we have timer frequency = 57,600 Hz.
(a) 57600 / 9600 = 6; so TH1 = -6 or TH1 = FAH
(b) 57600 / 4800 = 12; so TH1 = -12 or TH1 = F4H
------------------------------------------------------------------------------------------------------------
Example 5.3.8: Find the baud rate if TH1 = -2, SMOD = 1, and XTAL = 11.0592 MHz.
Is this baud rate supported by IBM compatible PCs?
Solution:
With XTAL = 11.0592 and SMOD = 1, we have timer frequency = 57,600 Hz. The baud
rate is 57,600/2 = 28,800. This baud rate is not supported by the BIOS of the PCs;
however, the PC can be programmed to do data transfer at such a speed. Also,
HyperTerminal in Windows supports this and other baud rates.
Example 5.3.9: Write a program to send the message “The Earth is but One Country” to
serial port. Assume a SW is connected to pin P1.2. Monitor its status and set the baud rate
as follows:
SW = 0, 4800 baud rate
SW = 1, 9600 baud rate
Assume XTAL = 11.0592 MHz, 8-bit data, and 1 stop bit.
Solution:
SW BIT P1.2
ORG 0H ;starting position
MAIN: MOV TMOD,#20H
MOV TH1,#-6 ;4800 baud rate (default)
MOV SCON,#50H
SETB TR1
;------------
;------------
Example 5.4.1: Write a C program for 8051 to transfer the letter “A” serially at 4800
baud continuously. Use 8-bit data and 1 stop bit.
Solution:
#include <reg51.h>
void main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1;
while (1)
{
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mybyte;
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1; //start timer
while (1) //repeat forever
{
Solution:
#include <reg51.h>
sbit MYSW=P2^0; //input switch
void main(void)
{
unsigned char z;
unsigned char Mess1[]=“Normal Speed”;
unsigned char Mess2[]=“High Speed”;
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFF; //28800 for normal
SCON=0x50;
TR1=1; //start timer
if(MYSW==0)
{
for (z=0;z<12;z++)
{
SBUF=Mess1[z]; //place value in buffer
while(TI==0); //wait for transmit
TI=0;
}
}
else
{
PCON=PCON|0x80; //for high speed of 56K
for (z=0;z<10;z++)
{
4.1 INTERRUPTS
Polling:
Note: The polling method is not efficient, since it wastes much of the microcontroller’s
time by polling devices that do not need service
Interrupts:
✓ Whenever any device needs its service, the device notifies the microcontroller by
sending it an interrupt signal
✓ Upon receiving an interrupt signal, the microcontroller interrupts whatever it is
doing
and serves the device
✓ The program which is associated with the interrupt is called the interrupt service
routine (ISR) or interrupt handler
The advantage of interrupts is that the microcontroller can serve many devices (not all at
the same time)
✓ Each devices can get the attention of the microcontroller based on the assigned
priority
✓ For the polling method, it is not possible to assign priority since it checks all
devices in a round-robin fashion
✓ The microcontroller can also ignore (mask) a device request for service which is
not possible for the polling method.
For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler
Upon activation of an interrupt, the microcontroller goes through the following steps
1. It finishes the instruction it is executing and saves the address of the next instruction
(PC) on the stack
2. It also saves the current status of all the interrupts internally (i.e.: not on the stack)
3. It jumps to a fixed location in memory, called the interrupt vector table, that holds the
address of the ISR
4. The microcontroller gets the address of the ISR from the interrupt vector table and
jumps to it. It starts to execute the interrupt service subroutine until it reaches the last
instruction of the subroutine which is RETI (return from interrupt)
5. Upon executing the RETI instruction, the microcontroller returns to the place where it
was interrupted. First, it gets the program counter (PC) address from the stack by
popping the top two bytes of the stack into the PC. Then it starts to execute from that
address.
ORG 30H
MAIN:
....
END
Note: Only three bytes of ROM space assigned to the reset pin. We put the LJMP as the
first instruction and redirect the processor away from the interrupt vector table.
1. Bit D7 of the IE register (EA) must be set to high to allow the rest of register to take
effect
2. The value of EA
✓ If EA = 1, interrupts are enabled and will be responded to if their corresponding
bits in IE are high
✓ If EA = 0, no interrupt will be responded to, even if the associated bit in the IE
register is high
Example 4.2.1: Show the instructions to (a) enable the serial interrupt, timer 0 interrupt,
and external hardware interrupt 1 (EX1),and (b) disable (mask) the timer 0
interrupt, then (c) show how to disable all the interrupts with a single instruction.
Solution:
The timer flag (TF) is raised when the timer rolls over
✓ In polling TF, we have to wait until the TF is raised. The problem with this
method is that the microcontroller is tied down while waiting for TF to be raised,
and cannot do anything else.
✓ Using interrupts solves this problem and, avoids tying down the controller
✓ If the timer interrupt in the IE register is enabled, whenever the timer rolls over,
TF israised, and the microcontroller is interrupted in whatever it is doing, and
jumps to the interrupt vector table to service the ISR. In this way, the
microcontroller can do other tasks until it is notified that the timer has rolled over.
-----------------------------------------------------------------------------------------------------------
Example 4.5.1: Write a program that continuously get 8-bit data from P0 and sends it to
P1 while simultaneously creating a square wave of 200 μs period on pin P2.1. Use timer 0
to create the square wave. Assume that XTAL = 11.0592 MHz.
Solution:
;--upon wake-up go to main, avoid using memory allocated to Interrupt Vector Table
ORG 0000H
LJMP MAIN ; by-pass interrupt vector table
Example 4.5.2: Write a program to generate a square wave of 50Hz frequency on pin
P1.2. use timer 0, mode 1in interrupt mode to create square wave. Assume that
XTAL=11.0592 MHz
Solution:
ORG 0
LJMP MAIN
ORG 000BH ;ISR for Timer 0
CPL P1.2
MOV TL0,#00
MOV TH0,#0DCH
RETI
ORG 30H
✓ Pin 12 (P3.2) and pin 13 (P3.3) of the 8051, designated as INT0 and INT1, are
used as external hardware interrupts
✓ The interrupt vector table locations 0003H and 0013H are set aside for INT0 and
INT1
✓ There are two activation levels for the external hardware interrupts
• Level trigged
• Edge trigged
In the level-triggered mode, INT0 and INT1 pins are normally high. This is called a
level-triggered or level activated interrupt and is the default mode upon reset of the 8051.
✓ If a low-level signal is applied to them, it triggers the interrupt, and then the
microcontroller stops whatever it is doing and jumps to the interrupt vector table to
service that interrupt.
✓ The low-level signal at the INT pin must be removed before the execution of the last
instruction of the ISR, RETI; otherwise, another interrupt will be generated
-----------------------------------------------------------------------------------------------------------
Example 4.6.1: Assume that the INT1 pin is connected to a switch that is normally high.
Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is
normally off. When it is turned on it should stay on for a fraction of a second. As long as
the switch is pressed low, the LED should stay on.
Solution:
ORG 0000H
LJMP MAIN ;by-pass interrupt
;vector table
;--ISR for INT1 to turn on LED
ORG 30H
MAIN: MOV IE,#10000100B ;enable external INT 1
HERE: SJMP HERE ;stay here until get interrupted
END
------------------------------------------------------------------------------------------------------------
Sampling Low Level-Triggered Interrupt:
The Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in the IE
register are enabled.
✓ After the hardware interrupts in the IE register are enabled, the controller keeps
sampling the INTn pin for a low-level signal once each machine cycle.
✓ The pin must be held in a low state until the start of the execution of ISR
✓ If the INTn pin is brought back to a logic high before the start of the execution of
ISR there will be no interrupt
✓ If INTn pin is left at a logic low after the RETI instruction of the ISR, another
interrupt will be activated after one instruction is executed
✓ To ensure the activation of the hardware interrupt at the INTn pin, make sure that
the duration of the low-level signal is around 4 machine cycles, but no more.
• This is due to the fact that the level-triggered interrupt is not latched
• Thus the pin must be held in a low state until the start of the ISR execution
Note: On reset, IT0 (TCON.0) and IT1 (TCON.2) are both low, making external interrupt
level-triggered.
------------------------------------------------------------------------------------------------------------
4.6.2 EDGE-TRIGGERED INTERRUPT:
To make INT0 and INT1 edge triggered interrupts, we must program the bits of the
TCON (i.e. IT0 and IT1) register.
In edge-triggered interrupts,
✓ The external source must be held high for at least one machine cycle, and then
held low for at least one machine cycle.
✓ The falling edge of pins INT0 and INT1 are latched by the 8051 and are held by
the TCON.1 and TCON.3 bits of TCON register
Regarding the IT0 and IT1 bits in the TCON register, the following two points must be
emphasized.
✓ When the ISRs are finished (that is, upon execution of RETI), these bits (TCON.1
and TCON.3) are cleared, indicating that the interrupt is finished and the 8051 is
ready to respond to another interrupt on that pin
✓ During the time that the interrupt service routine is being executed, the INTn pin
is ignored, no matter how many times it makes a high-to-low transition
Ans:
Both perform the same actions of popping off the top two bytes of the stack into the
program counter, and marking the 8051 return to where it left off. However, RETI also
performs an additional task of clearing the interrupt-in-service flag, indicating that the
servicing of the interrupt is over and the 8051 now can accept a new interrupt on that pin.
If you use RET instead of RETI as the last instruction of the interrupt service routine, you
simply block any new interrupt on that pin after the first interrupt, since the pin status
would indicate that the interrupt is still being serviced. In the cases of TF0, TF1, TCON.1,
and TCON.3, they are cleared due to the execution of RETI.
When the 8051 is powered up, the priorities are assigned according to the sequence given
in table 4.7.1. In reality, the priority scheme is nothing but an internal polling sequence in
which the 8051 polls the interrupts in the sequence listed and responds accordingly.
Example 4.7.1: Discuss what happens if interrupts INT0, TF0, and INT1 are activated at
the same time. Assume priority levels were set by the power-up reset and the external
hardware interrupts are edge triggered.
Solution:
If these three interrupts are activated at the same time, they are latched and kept
internally. Then the 8051 checks all five interrupts according to the sequence listed in
Table 11-3. If any is activated, it services it in sequence. Therefore, when the above three
interrupts are activated, IE0 (external interrupt 0) is serviced first, then timer 0 (TF0), and
finally IE1 (external interrupt 1).
------------------------------------------------------------------------------------------------------------
We can alter the sequence of interrupt priority by assigning a higher priority to any one of
the interrupts by programming a register called IP (interrupt priority)
✓ To give a higher priority to any of the interrupts, we make the corresponding bit in
the IP register high
✓ When two or more interrupt bits in the IP register are set to high. While these
interrupts have a higher priority than others, they are serviced according to the
sequence of Table 4.7.1.
-- IP.7 Reserved
Example 4.7.2: (a) Program the IP register to assign the highest priority to INT1
(external interrupt 1), then (b) discuss what happens if INT0, INT1, and TF0 are activated
at the same time. Assume the interrupts are both edge-triggered.
Solution:
(a) MOV IP,#00000100B ;IP.2=1 assign INT1 higher priority. The instruction SETB IP.2
also will do the same thing as the above line since IP is bit-addressable.
(b) The instruction in Step (a) assigned a higher priority to INT1 than the others;
therefore, when INT0, INT1, and TF0 interrupts are activated at the same time, the 8051
services INT1 first, then it services INT0, then TF0. This is due to the fact that INT1 has
a higher priority than the other two because of the instruction in Step (a). The instruction
in Step (a) makes both the INT0 and TF0 bits in the IP register 0. As a result, the
sequence in Table 4.7.1 is followed which gives a higher priority to INT0 over TF0
------------------------------------------------------------------------------------------------------------
Example 4.7.3: Assume that after reset, the interrupt priority is set the instruction MOV
IP,#00001100B. Discuss the sequence in which the interrupts are serviced.
Solution:
The instruction “MOV IP #00001100B” (B is for binary) and timer 1 (TF1)to a higher
priority level compared with the reset of the interrupts. However, since they are polled
according to Table, they will have the following priority.
ARCHITECTURE OF 8051