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

The 8051 Microcontroller and Embedded Systems: 8051 Assembly Language Programming

Here are the steps to calculate the short jump address: 1. The current PC (program counter) is at address 0004 after executing the MOV instruction. 2. The target address for the jump is 0002, which is 2 bytes before the current PC. 3. Since this is a backward jump, we take the 2's complement of the relative address. 2's complement of 2 is FE. 4. The short jump opcode is 80. So the complete 2-byte instruction is 80 FE. So in summary, the short jump opcode to jump back to address 0002 from the current PC of 0004 is 80 FE.

Uploaded by

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

The 8051 Microcontroller and Embedded Systems: 8051 Assembly Language Programming

Here are the steps to calculate the short jump address: 1. The current PC (program counter) is at address 0004 after executing the MOV instruction. 2. The target address for the jump is 0002, which is 2 bytes before the current PC. 3. Since this is a backward jump, we take the 2's complement of the relative address. 2's complement of 2 is FE. 4. The short jump opcode is 80. So the complete 2-byte instruction is 80 FE. So in summary, the short jump opcode to jump back to address 0002 from the current PC of 0004 is 80 FE.

Uploaded by

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

The 8051 Microcontroller

1
and Embedded Systems
CHAPTER 2
8051 ASSEMBLY LANGUAGE PROGRAMMING
2 SECTION 2.1: INSIDE THE 8051

 Registers

Figure 2–1a
Some 8-bit Registers of the 8051
3 SECTION 2.1: INSIDE THE 8051

 Registers

Figure 2–1b Some 8051 16-bit Registers


4 SECTION 2.1: INSIDE THE 8051

 MOV instruction
 MOV destination, source ;copy source to destination

MOV A,#55H ;load value 55H into reg A


MOV R0,A ;copy contents of A into R0 (A=R0=55H)
MOV R1,A ;copy contents of A into R1 (A=R0=R1=55H)
MOV R2,A ;copy contents of A into R2 (A=R0=R1=R2=55H)
MOV R3,#95H ;load value 95H into R3 (R3=95H)
MOV A,R3 ;copy contents of R3 into A (A=R3=95H)
5 SECTION 2.1: INSIDE THE 8051

 ADD instruction
 ADD A, source ;ADD the source operand
;to the accumulator

MOV A,#25H ;load 25H into A


MOV R2,#34H ;load 34H into R2
ADD A,R2 ;add R2 to accumulator

Executing the program above results in A = 59H


6 SECTION 2.2: INTRODUCTION TO 8051
ASSEMBLY PROGRAMMING
 Structure of Assembly language

ORG 0H ;start (origin) at 0


MOV R5,#25H ;load 25H into R5
MOV R7,#34H ;load 34H into R7
MOV A,#0 ;load 0 into A
ADD A,R5 ;add contents of R5 to A
;now A = A + R5
ADD A,R7 ;add contents of R7 to A
;now A = A + R7
ADD A, #12H ;add to A value 12H
;now A = A + 12H
HERE: SJMP HERE ;stay in this loop
END ;end of asm source file

Program 2-1: Sample of an Assembly Language Program


7 SECTION 2.3: ASSEMBLING AND RUNNING
AN 8051 PROGRAM

 An Assembly language instruction consists of four fields:

[label : ]mnemonic [operands] [;comment]


8 SECTION 2.3: ASSEMBLING AND RUNNING
AN 8051 PROGRAM

Figure 2–2 Steps to Create a Program


9 SECTION 2.3: ASSEMBLING AND RUNNING
AN 8051 PROGRAM

 More about "a51" and "obj" files


 "asm" file is source file and for this reason some assemblers
require that this file have the “a51" extension
 this file is created with an editor such as Windows Notepad or
uVision editor
 uVision assembler converts the a51 assembly language
instructions into machine language and provides the obj file
 assembler also produces the Ist file
10
SECTION 2.4: THE PROGRAM COUNTER
AND ROM SPACE IN THE 8051
 Program counter in the 8051
 16 bits wide
 can access program addresses 0000 to FFFFH
 total of 64K bytes of code
11
SECTION 2.4: THE PROGRAM COUNTER
AND ROM SPACE IN THE 8051
 Where the 8051 wakes up when it is powered up:
 wakes up at memory address 0000 when it is powered up
 first opcode must be stored at ROM address 0000H
12
SECTION 2.4: THE PROGRAM COUNTER
AND ROM SPACE IN THE 8051
 Placing code in program ROM
 the opcode and operand are placed in ROM locations starting at memory 0000
13
SECTION 2.4: THE PROGRAM COUNTER
AND ROM SPACE IN THE 8051
 ROM memory map in the 8051 family

Figure 2–3 8051 On-Chip ROM Address Range


14 SECTION 2.5: 8051 DATA TYPES AND
DIRECTIVES

 8051 data type and directives


 DB (define byte)
 ORG (origin)
 EQU (equate)
 END directive
15 SECTION 2.5: 8051 DATA TYPES AND
DIRECTIVES

 Rules for labels in Assembly language


 each label name must be unique
 first character must be alphabetic
 reserved words must not be used as labels
16 SECTION 2.6: 8051 FLAG BITS AND THE PSW
REGISTER

 PSW (program status word) register

Figure 2–4 Bits of the PSW Register


17 SECTION 2.6: 8051 FLAG BITS AND THE PSW
REGISTER

Table 2–1 Instructions That Affect Flag Bits


18 SECTION 2.7: 8051 REGISTER BANKS AND
STACK

 RAM memory space allocation in the 8051

Figure 2–5
RAM Allocation in the 8051
19 SECTION 2.7: 8051 REGISTER BANKS AND
STACK

 Register banks in the 8051

Figure 2–6 8051 Register Banks and their RAM Addresses


20 SECTION 2.7: 8051 REGISTER BANKS AND
STACK

 How to switch register banks

Table 2–2 PSW Bits Bank Selection


21 SECTION 2.7: 8051 REGISTER BANKS AND
STACK

 Stack in the 8051


 section of RAM used to store information temporarily
 could be data or an address
 CPU needs this storage area since there are only a limited number of registers
The 8051 Microcontroller
22
and Embedded Systems
CHAPTER 3
JUMP, LOOP, AND CALL INSTRUCTIONS
23 OBJECTIVES

 Code 8051 Assembly language instructions using loops


 Code 8051 Assembly language conditional jump instructions
 Explain conditions that determine each conditional jump instruction
 Code long jump instructions for unconditional jumps
 Code short jump instructions for unconditional short jumps
 Calculate target addresses for jump instructions
 Code 8051 subroutines
 Describe precautions in using the stack in subroutines
24 SECTION 3.1: LOOP AND JUMP
INSTRUCTIONS
 Repeating a sequence of instructions a certain number of times is
called a loop.
 The loop action is performed by the instruction
 DJNZ reg, label.
 In this instruction, the register is decremented; if it is not zero, it
jumps to the target address referred to by the label.
 Prior to the start of the loop the register is loaded with the counter for
the number of repetitions.
 In this instruction both the register decrement and the decision to
jump arc combined into a single instruction.
 The registers can be any of R0 - R7. The counter can also be a RAM
location
25 SECTION 3.1: LOOP AND JUMP
INSTRUCTIONS
26 Loop inside a loop

 What happens if we want to repeat an action more times than 256?


Example 3-3
Write a program to (a) load the accumulator with the value 55H,
and (b) complement the ACC 700 times.
Since 700 is larger than 255 (the maximum capacity of any register),
we use two registers to hold the count. The following code shows how
to use R2 and R3 for the count.
MOV A,#55H ;A=55H
NEXT: MOV R3,#10 ;R3=10, the outer loop count
AGAIN: MOV R2,#70 ;R2=70, the inner loop count
CPL A ;complement
27 SECTION 3.1: LOOP AND JUMP
INSTRUCTIONS

 Other conditional jumps


28 Other conditional jumps

 JZ (jump if A = 0)
 In this instruction the content of register A is checked. If it is zero, it jumps to the
target address.
 JZ instruction can be used only for register A.
 It can only check to see whether the accumulator is zero, and it does not apply
to any other register.
 Don't have to perform an arithmetic instruction such as decrement to use the JZ
instruction.
29 Other conditional jumps

 JNZ (jump if A  0)
 In this instruction the content of register A is checked. If it is not zero, it jumps to
the target address.
30 Other conditional jumps

 JNC Jump if no carry, jumps if CY = 0)


 carry flag bit in the flag (PSW) register is used to make the decision whether to
jump
 "JNC label", the processor looks at the carry flag to see if it is raised (CY = 1).
 if it is not, the CPU starts to 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.
31 Other conditional jumps

 JC Jump if carry, jumps if CY = 1)


 if CY = l it jumps to the target address
 JB (jump if bit is high)
 JNB (jump if bit is low)
32 SECTION 3.1: LOOP AND JUMP
INSTRUCTIONS

 All conditional jumps are short jumps

Table 3–1
8051 Conditional
Jump
Instructions
33 Unconditional jump instructions

 There are two unconditional jumps: LJMP (long jump) and SJMP (short
jump).
 LJMP is 3-byte instruction in which the first byte is the op-code, and the second
and third bytes represent the 16-bit address of the target location.
 The 2-byte target address.
34 Unconditional jump instructions

 SJMP (short jump)


 2-byte instruction, the first byte is the op-code and the second
byte is the relative address of the target location.
 The relative address range of 00 – FFH 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).
 If the jump is forward, the target address can be within a space
of 127 bytes from the current PC.
 If the target address is backward, the target address can be
within -128 bytes from the current PC.
35 Calculating the short jump address

Example 3-6

Using the following list tile, verify the jump forward address calculation.

Line PC Op-code Mnemonic Operand

1 0000 ORG 0000

2 0000 7800 MOV R0, #003

3 0002 7455 MOV A, #55H0

4 0004 6003 JZ NEXT

5 0006 08 INC R0

6 0007 04 AGAIN: INC A

7 0008 04 INC A

8 0009 2477 NEXT: ADD A, #77h

9 000B 5005 JNC OVER

10 000D E4 CLR A

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 OVER: ADD A, R3

16 0013 50F2 JNC AGAIN

17 0015 80FE HERE: SJMP HERE

18 0017 END
36 Calculating the short jump address

In that program list "JNC AGAIN" has opcode 50 and relative address F2H.
When the relative address of F2H is added to 15H, the address of the
instruction below the jump, we have 15H+F2H=07 (the carry is dropped).
Notice that 07 is the address of label AGAIN. Look also at "SJMP HERE",
which has 80 and FE for the opcode and relative address, respectively. The
PC of the following instruction. 0017H, is added lo FEH, the relative
address, to get 0015H, address of the HERE label ( 17H + FEH =15H).
Notice that FEH is -2 and 17H + (-2) = 15H. For further discussion of the
addition of negative numbers.
37 SECTION 3.2: CALL INSTRUCTIONS

 CALL is used to call a subroutine.


 Subroutines are often used to perform tasks that need to
be performed frequently.
 This makes a program more structured in addition to
saving memory space.
 There are two instructions : LCALL (long call) and ACALL
(absolute call).
 Deciding which one to use depends on the target
address.
38 SECTION 3.2: CALL INSTRUCTIONS

 LCALL (long call)


 3-byte instruction, the first byte is the op-code and the second and third
bytes are used for the address of the target subroutine.
 LCALL can be used to call subroutines located anywhere within the
64K-byte address space of the 8051.
 To make sure that after execution of the called subroutine the 8051
knows where to come back to, the processor automatically saves on
the stack the address of the instruction immediately below the LCALL.
 When a subroutine is called, control is transferred to that subroutine,
and the processor saves the PC (program counter) on the stack and
begins to fetch instructions from the new location.
 After finishing execution of the subroutine, the instruction RET (return)
transfers control back to the caller. Every subroutine needs RET as the
last instruction.
39 SECTION 3.2: CALL INSTRUCTIONS

 LCALL (long call)

Figure 3–1
8051 Assembly Main Program
That Calls Subroutines
40 SECTION 3.2: CALL INSTRUCTIONS

 CALL instruction and the role of the stack


41 SECTION 3.3: TIME DELAY FOR VARIOUS 8051
CHIPS

 Machine cycle for the 8051


 The MCU takes a certain number of clock cycles to execute an
instruction.
 These clock cycles are referred to as machine cycles.
 In the 8051 family, the length of the machine cycle depends on
the frequency of the crystal oscillator.
 The frequency of the crystal connected to the 8051 family can
vary from 4 MHz to 30 MHz.
 In the original 8051, one machine cycle lasts 12 oscillator periods.
 Therefore, to calculate the machine cycle for the 8051, we take
1/12 of the crystal frequency, then take its inverse.
42 SECTION 3.3: TIME DELAY FOR VARIOUS 8051
CHIPS

 Machine cycle for the 8051

Table 3–2 Clocks per Machine Cycle (MC) for Various 8051 Versions
43 SECTION 3.3: TIME DELAY FOR VARIOUS 8051
CHIPS

 Delay calculation for other versions of 8051

Table 3–3 Comparison of 8051 and DS89C4x0 Machine Cycles


SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS
44
CHAPTER 4
I/O PORT PROGRAMMING

45
46 OBJECTIVES

 List the 4 ports of the 8051


 Describe the dual role of port 0 in providing both data
and addresses
 Code Assembly language to use the ports for input or
output
 Explain the dual role of port 0 and port 2
 Code 8051 instructions for I/O handling
 Code I/O bit-manipulation programs for the 8051
47 SECTION 4.1: 8051 I/O PROGRAMMING

Figure 4–1 8051 Pin Diagram


48 SECTION 4.1: 8051 I/O PROGRAMMING

 All the ports upon RESET are configured as inputs, ready to be used as input
ports.
 When the first 0 is written to a port, it becomes an output.
 To reconfigure it as an input, a 1 must be sent to the port.
 To use any of these ports as an input port, it must be programmed.
49 SECTION 4.1: 8051 I/O PROGRAMMING

 Port 0

Figure 4–2
Port 0 with Pull-Up Resistors
50 Port 0

 It can be used for input or output.


 To use the pins of port 0 as both input and output each pin must be
connected externally to a 10 Kohm pull-up resistor.
 This is due to the fact that P0 is an open drain, unlike P 1, P2, and P3
51 Port 0 as input
 With resistors connected to port 0, in order to make it an input, the port must
be programmed by writing 1 to all the bits.
52 Dual role of port 0

 Port 0 is also designated as AD0 - AD7, allowing it to be used for both


address and data.
 When connecting an 8051/31 to an external memory, port 0 provides both
address and data.
 The 8051 multiplexes address and data through port 0 to save pins. We
discuss that in Chapter 14.
53 SECTION 4.1: 8051 I/O PROGRAMMING

 Port 1
 It can be used as input or output.
 This port does not need any pull-up resistors since it already has pull-up
resistors internally.
 Upon reset, port I is configured as an input port.
54 Port 1 as input

 If port 1 has been configured as an output port, to make it an input port


again, it must programmed as such by writing 1 to all its bits.
55 Port 1 as input

 In the following code, port 1 is configured first as an input port by


writing 1 s to it, then data is received from that port and saved in R7,
R6, and R5.
56 SECTION 4.1: 8051 I/O PROGRAMMING

 Port 2
 Port 2 occupies a total of 8 pins (pins 21 through 28).
 It can be used as input or output.
 Port 2 does not need any pull-up resistors since it
already has pull-up resistors internally.
 Upon reset, port 2 is configured as an input port.
57 Port 2 as input

 To make port 2 an input, it must programmed as such by writing 1 to


all its bits.
 In the following code, port 2 is configured first as an input port by
writing is to it.
58 Dual role of port 2

 In 8031-based systems, port 2 must be used along with P0 to provide


the 16-bit address for external memory.
 Port 2 is also designated as A8 - A15, indicating its dual function.
 Since an 8051/31 is capable of accessing 64K bytes of external
memory, it needs a path for the 16 bits of the address.
 P0 provides the lower 8 bits via A0 - A7
 P2 provides bits A8 - A 15 of the address.
 When the 8051 /31 is connected to external memory, P2 is used for
the upper 8 bits of the 16-bit address, and it cannot be used for I/O.
59 Port 3

 Port 3 can be used as input or output.


 P3 does not need any pull-up resistors.
 Port 3 is configured as an input port upon reset.
 Port 3 has the additional function of providing some extremely important
signals such as interrupts, serial I/O, timer/counter and read/write control for
external memory.
60 SECTION 4.1: 8051 I/O PROGRAMMING

 Port 3

Table 4–1
Port 3 Alternate Functions
61 SECTION 4.1: 8051 I/O PROGRAMMING

 Different ways of accessing the entire 8 bits


62 Different ways of accessing the entire 8 bits
63 SECTION 4.1: 8051 I/O PROGRAMMING

 Ports status upon reset

Table 4–2 Reset Value of Some 8051 Ports


64 SECTION 4.2: I/O BIT MANIPULATION
PROGRAMMING

 A powerful feature of 80511/0 ports is their capability to


access individual bits of the port without altering the rest
of the bits in that port.
 Of the four 8051 ports, we can access either the entire 8
bits or any single bit without altering the rest.
 "SETB X. Y" where X is the port number 0, 1, 2, or 3, and Y
is the desired bit number from 0 to 7 for data bits DO to
D7.
 "SETB P1.5" sets high bit 5 of port 1.
65 SECTION 4.2: I/O BIT MANIPULATION
PROGRAMMING

 The following code toggles bit P1.2 continuously.


66 SECTION 4.2: I/O BIT MANIPULATION
PROGRAMMING

 I/O ports and bit-addressability

Table 4–3
Single-Bit Addressability
of Ports
67 SECTION 4.2: I/O BIT MANIPULATION
PROGRAMMING

 I/O ports and bit-addressability

Table 4–4 Single-Bit Instructions


68 SECTION 4.2: I/O BIT MANIPULATION
PROGRAMMING

 Checking an input bit

Table 4–5 Instructions For Reading an Input Port


69 Reading a single bit into the carry flag
70 Reading input pins vs. port latch

 Some instructions read the status of port pins while others read the status of
an internal port latch.
 When reading ports there are two possibilities:
 1. Read the status of the input pin.
 2. Read the internal latch of the output port.
71 Instructions for reading input ports

 To make any bit of any 8051 port an input port, we must write 1 (logic high)
to that bit.
 After we configure the port bits as input, we can use only certain instructions
in order to get the external data present at the pins into the CPU.
72 Reading latch for output port

Table 4–6 Instructions Reading a Latch (Read-Modify-Write)


73 Read-modify-write feature

 The ports in the 8051 can be accessed by the read-modify-write technique.


 (1) reading the port
 (2) modifying its value
 (3) writing to the port
The 8051 Microcontroller
74
and Embedded Systems
CHAPTER 5
8051 ADDRESSING MODES
75 OBJECTIVES

 List the five addressing modes of the 8051 microcontroller


 Contrast and compare the addressing modes
 Code 8051 Assemblv language instructions using each addressing
mode
 Access RAM using various addressing modes
 List the SFR (special function registers) addresses
 Discuss how to access the SFR
 Manipulate the stack using direct addressing mode
 Code 8051 instructions to manipulate a look-up table
 Access RAM, I/O, and ports using bit addresses
 Discuss how to access the extra 128 bytes of RAM space in the 8052
76 Addressing Modes

 The various addressing modes of a microprocessor are


determined when it is designed, and therefore cannot
be changed by the programmer.
 The 8051 provides a total of five distinct addressing
modes.
 (1) immediate
 (2) register
 (3) direct
 (4) register indirect
 (5) indexed
77 Immediate addressing mode

 The operand comes immediately after the op-code.


 The immediate data must be preceded by the pound sign, "#".
78 Register addressing mode

 Register addressing mode involves the use of registers to hold the data to
be manipulated.
79
SECTION 5.2: ACCESSING MEMORY USING
VARIOUS ADDRESSING MODES
 Direct addressing mode
 There are 128 bytes of RAM in the 8051.
 The RAM has been assigned addresses 00 to 7FH.
 1. RAM locations 00 - 1 FH are assigned to the register banks and
stack.
 2. RAM locations 20 - 2FH are set aside as bit-addressable space
to save singlebit data.
 3. RAM locations 30 - 7FH are available as a place to save byte-
sized data.
80 Direct addressing mode

 It is most often used to access RAM locations 30 - 7FH.


 This is due to the fact that register bank locations are accessed by the
register names of R0 - R7.
 There is no such name for other RAM locations so must use direct
addressing.
81 Direct addressing mode

 In the direct addressing mode, the data is in a RAM memory location


whose address is known, and this address is given as a part of the
instruction.
82 Special Function Registers

 In the 8051, registers A, B, PSW, and DPTR are part of the group of registers
commonly referred to as SFR.
 The SFR can be accessed by their names or by their addresses.
 For example, register A has address E0H and register B has been
designated the address F0H.
 SFR registers and their addresses
83
84 SFR
85
Stack and direct addressing mode

 Another major use of direct addressing mode is the


stack.
 In the 8051 family, only direct addressing mode is
allowed for pushing onto the stack.
 An instruction such as "PUSH A" is invalid. Pushing the
accumulator onto the stack must be coded as "PUSH
0E0H.
 Direct addressing mode must be used for the POP
instruction as well.
 "POP 04" will pop the top of the stack into R4 of bank 0.
86
Register indirect addressing mode

 A register is used as a pointer to the data.


 If the data is inside the CPU, only registers R0 and R 1 are
used for this purpose.
 R2 - R7 cannot be used to hold the address of an
operand located in RAM when using indirect addressing
mode.
 When RO and R 1 are used as pointers they must be
preceded by the @ sign.
87 Register indirect addressing mode
88
Advantage of register indirect addressing
mode
 One of the advantages of register indirect addressing mode is that it makes
accessing data dynamic rather than static as in the case of direct
addressing mode.
 Looping is not possible in direct addressing mode.
 This is the main difference between the direct and register indirect
addressing modes.
89 Advantage of register indirect addressing
mode
90
Limitation of register indirect addressing
mode in the 8051
 R0 and R 1 are the only registers that can be used for
pointers in register indirect addressing mode.
 Since R0 and R l are 8 bits wide, their use is limited to
accessing any information in the internal RAM (scratch
pad memory of 30H - 7FH, or SFR).
 To access data stored in external RAM or in the code
space of on-chip ROM, we need a 16-bit pointer, the
DPTR.
91
Indexed addressing mode and on-chip
ROM access
 Indexed addressing mode is widely used in accessing data
elements of look-up table entries located in the program ROM
space of the 8051.
 The instruction used for this purpose is :
MOVC A, @ A+DPTR
 The 16-bit register DPTR and register A are used to form the address
of the data element stored in on-chip ROM.
 Because the data elements are stored in the program (code) space
ROM of the 8051, the instruction MOVC is used instead of MOV. The
"C" means code.
 In this instruction the contents of A are added to the 16-bit register
DPTR to form the 16bit address of the needed data.
92

Indexed addressing mode and MOVX


instruction
 The 8051 has another 64K bytes of memory space set aside
exclusively for data storage.
 This data memory space is referred to as external memory and it is
accessed by the MOVX instruction.
 The 8051 has a total of 128K bytes of memory space since 64K bytes
of code added to 64K bytes of data space gives us 128K bytes.
 One major difference between the code space and data space is
that, unlike code space, the data space cannot be shared between
code and data.
93 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 Many microprocessors such as the 386 or Pentium allow programs to


access registers and I/0 ports in byte size only.
 If you need to check a single bit of an I/0 port, you must read the
entire byte first and then manipulate the whole byte with some
logic instructions to get hold of the desired single bit.
 This is not the case with the 8051.
 One of the most important features of the 8051 is the ability to
access the registers, RAM, and I/0 ports in bits instead of bytes.
 This is a very unique and powerful feature for a microprocessor
made in the early 1980s.
94 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 Bit-addressable RAM

Figure 5–1
16 Bytes of Internal RAM. Note:
They are both bit- and byte-accessible.
95 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 Bit-addressable RAM

Table 5–2 Single-Bit Instructions


96 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 I/O port bit addresses

Figure 5–2 SFR RAM Address (Byte and Bit)


97 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 Bit memory map

Table 5–3 Bit Addresses for All Ports


98 SECTION 5.3: BIT ADDRESSES FOR I/O AND
RAM

 Registers bit-addressability

Figure 5–3 Bits of the PSW Register


99 Using BIT directive

 The BIT directive is a widely used directive to assign the bit-addressable I/0
and RAM locations.
 The BIT directive allows a program to assign the I/0 or RAM bit at the
beginning of the program, making it easier to modify them.
100 Using EQU directive

 We can also use the EQU directive to assign addresses.


101 Addition of unsigned numbers

The form of the ADD instruction is


 ADD A, source ;A = A + source
102 Addition of individual bytes
103 ADDC and addition of 16-bit numbers
104 BCD (binary coded decimal) number
system

 Unpacked BCD
 The lower 4 bits of the number represent the BCD number.
 The rest of the bits are 0.
 For example, "0000 1001" and "0000 0101" are unpacked BCD for 9 and 5,
respectively.
 Unpacked BCD requires 1 byte of memory or an 8-bit register to contain it.
105 SECTION 6.1: ARITHMETIC INSTRUCTIONS

 Unpacked BCD

Figure 6–1 BCD Code


106 BCD (binary coded decimal) number
system

 Packed BCD
 A single byte has two BCD numbers in it, one in the lower 4 bits, and one in the
upper 4 bits.
 For example, "0101 1001" is packed BCD for 59H.
 It takes only 1 byte of memory to store the packed BCD operands.
 Its more efficient than unpacked BCD.
107 BCD (binary coded decimal) number
system

 There is a problem with adding BCD numbers.


 Adding two BCD numbers must give a BCD result.
 After adding packed BCD numbers, the result is no
longer BCD.

MOV A, #17BCD
ADD A,#28BCD ;A = 3F which is not BCD
;should be 17 + 28 = 45BCD

"DA A" is designed to correct the BCD addition problem.


108 BCD (binary coded decimal) number
system

 DA instruction
MOV A,#47H ;A=47H first BCD operand
MOV B,#25H ;B=25 second BCD operand
ADD A,B ;hex (binary) addition (A=6CH)
DA A ;adjust for BCD addition (A=72H)

 DA A must be used after the addition of BCD operands.


 Important to note that DA A works only after an ADD
instruction, it will not work after the INC instruction.
109 Subtraction of unsigned numbers

 SUBB A, source ;A = A - source – CY


 In the 8051 we have only have subtract with borrow SUBB.
 There are two cases for the SUBB instruction:
 (1) with CY = 0
 (2) with CY = l
110 Subtraction of unsigned numbers
111 Subtraction of unsigned numbers

 If the CY = 0 after the execution of SUBB, the result is


positive.
 If CY = 1, the result is negative and the destination has
the 2's complement of the result.
 Normally, the result is left in 2's complement, but the CPL
(complement) and INC instructions can be used to
change it.
 The CPL instruction performs the 1's complement of the
operand; then the operand is incremented (INC) to get
the 2's complement.
112 Subtraction of unsigned numbers

 SUBB (subtract with borrow) when CY = 1


113 UNSIGNED MULTIPLICATION AND DIVISION

 In multiplying or dividing two numbers in the 8051, the use of registers A and
B is required.
 The multiplication and division instructions work only with these two
registers.
114 Multiplication of unsigned numbers

 The 8051 supports byte-by-byte multiplication only.


 The bytes are assumed to be unsigned data. MUL
AB ;A x B, place 16-bit result in B and A
 After multiplication, the result is in the A and B
registers.
 The lower byte is in A, and the upper byte is in B.
MOV A,#25H ;load 25H to reg. A
MOV B,#65H ;load 65H in reg. B
MUL AB ;25H * 65H = E99 where
;B = 0EH and A = 99H
115 Multiplication of unsigned numbers

Table 6–1 Unsigned Multiplication Summary (MUL AB)


116 Division of unsigned numbers

 In the division of unsigned numbers, the 8051 supports byte over byte only.
DIV AB ;divide A by B
 The numerator must be in register A and the denominator must be in B.
 After the DIV instruction is performed, the quotient is in A and the remainder
is in B.
117 Division of unsigned numbers

 MOV A,#95 ;load 95 into A


MOV B,#10 ;load 10 into B
DIV AB ;now A = 09 (quotient) and
;B = 05 (remainder)

 This instruction always makes CY = 0 and OV = 0 if the denominator


is not 0.
 If the denominator is 0 (B = 0), OV = 1 indicates an error, and CY = 0.
 The standard practice in all microprocessors when dividing a
number by 0 is to indicate in some way the invalid result of infinity.
 In the 805 I, the OV flag is set to 1.
118 Division of unsigned numbers

Table 6–2 Unsigned Division Summary (DIV AB)


119 SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC
OPERATIONS

 Concept of signed numbers in computers


 Computers must be able to accommodate sign numbers.
 Computer scientists have devised the following arrangement for
the representation of signed positive and negative numbers:
 The most significant bit (MSB) is set aside for the sign (+ or -), while
the rest of the bits are used for the magnitude.
 The sign is represented by 0 for positive (+) numbers and 1 for
negative (- ) numbers.
120 Signed 8-bit operands

 In signed byte operands, D7 (MSB) is the sign and D0 to D6 are set aside for
the magnitude of the number.
 If D7 = 0, the operand is positive, and if D7 = 1, it is negative.
121 Positive numbers

 The range of positive numbers that can be represented is 0 to +127.


 If a positive number is larger than +127, a 16-bit size operand must be used.
122 Negative numbers

 For negative numbers, D7 is1.


 The magnitude is represented in its 2's complement.
 To convert to negative number representation (2's complement):
1. Write the magnitude of the number in 8-bit binary (no sign).
2. Invert each bit.
3. Add 1 to it.
123

Overflow problem in signed number


operations
 When using signed numbers, a serious problem arises that must be dealt
with. This is the overflow problem.
 The 8051 indicates the existence of an error by raising the OV (overflow)
flag.
 If the result of an operation on signed numbers is too large for the register,
an overflow has occurred and the programmer must be notified.
124 Compare instruction

 CJNE destination,source,relative address


125 SECTION 6.3: LOGIC AND COMPARE
INSTRUCTIONS

 Compare instruction

Table 6–3 Carry Flag Setting For CJNE Instruction


126 SECTION 6.4: ROTATE INSTRUCTION AND
DATA SERIALIZATION

 Rotating through the carry


 In the 8051 the rotation instructions RL, RR, RLC, and RRC are designed to rotate
the accumulator right or left.
 To rotate a byte the operand must be in register A.
 There are two type of rotations. One is a simple rotation of the bits of A, and the
other is a rotation through the carry.
127 Serializing data

 Serializing data is a way of sending a byte of data one bit at a time


through a single pin of microcontroller.
 There are two ways to transfer a byte of data serially:
 1. Using the serial port. The details of serial port data transfer are
discussed in Chapter 10.
 2. The second method of serializing data is to transfer data one bit at a
time and control the sequence of data and spaces in between them.
 In many new devices such as LCD, ADC, and ROM, the serial
versions of these devices are becoming popular since they take
less space on a printed circuit board.
128 Serializing a byte of data
129 Single-bit operations with CY

Table 6–4 Carry Bit-Related Instructions


130 ASCII numbers

Table 6–5 ASCII Code for Digits 0–9


131 Checksum byte in ROM

 To ensure the integrity of the ROM contents, every system must


perform the checksum calculation.
 The process of checksum will detect any corruption of the contents
of ROM.
 The checksum byte is an extra byte that is tagged to the end of a
series of bytes of data.
 To calculate the checksum byte of a series of bytes of data, the
following steps can be taken:
1. Add the bytes together and drop the carries.
2. Take the 2's complement of the total sum; this is the checksum byte,
which becomes the last byte of the series.
132 Checksum byte in ROM

 To perform the checksum operation, add all the bytes, including the check-
sum byte.
 The result must be zero.
 If it is not zero, one or more bytes of data have been changed (corrupted).
The 8051 Microcontroller
133
and Embedded Systems
CHAPTER 9
8051 TIMER PROGRAMMING IN ASSEMBLY
134 OBJECTIVES

 List the timers of the 8051 and their associated registers


 Describe the various modes of the 8051 timers
 Program the 8051 timers in Assembly to generate time delay
135 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Basic registers of the timer


 Timer 0 and Timer 1 are 16 bits wide
 each 16-bit timer is accessed as two separate registers of low byte and high
byte.
136 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Timer 0 registers
 low byte register is called TL0 (Timer 0 low byte) and the high
byte register is referred to as TH0 (Timer 0 high byte)
 can be accessed like any other register, such as A, B, R0, R1, R2,
etc.
 "MOV TL0, #4 FH" moves the value 4FH into TL0
 "MOV R5, TH0" saves TH0 (high byte of Timer 0) in R5
137 SECTION 9.1: PROGRAMMING 8051 TIMERS

Figure 9–1 Timer 0 Registers


138 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Timer 1 registers
 also 16 bits
 split into two bytes TL1 (Timer 1 low byte) and TH1 (Timer 1 high byte)
 accessible in the same way as the registers of Timer 0.
139 SECTION 9.1: PROGRAMMING 8051 TIMERS

Figure 9–2 Timer 1 Registers


140 SECTION 9.1: PROGRAMMING 8051 TIMERS

 TMOD (timer mode) register


 timers 0 and 1 use TMOD register to set operation modes (only learn
Mode 1 and 2)
 8-bit register
 lower 4 bits are for Timer 0
 upper 4 bits are for Timer 1
 lower 2 bits are used to set the timer mode
 (only learn Mode 1 and 2)
 upper 2 bits to specify the operation
 (only learn timer operation)
141 SECTION 9.1: PROGRAMMING 8051 TIMERS

Figure 9–3 TMOD Register


142 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Clock source for timer


 timer needs a clock pulse to tick
 if C/T = 0, the crystal frequency attached to the 8051 is the
source of the clock for the timer
 frequency for the timer is always 1/12th the frequency of the
crystal attached to the 8051
 XTAL = 11.0592 MHz allows the 8051 system to communicate with
the PC with no errors
 In our case, the timer frequency is 1MHz since our crystal
frequency is 12MHz
Bit 7 - TF1: Timer1 Overflow Flag
1 = Timer1 overflow occurred (i.e. Timer1 goes to its max and roll over back to zero).
0 = Timer1 overflow not occurred.
It is cleared through software. In Timer1 overflow interrupt service routine, this bit will get cleared
automatically while exiting from ISR.
Bit 6 - TR1: Timer1 Run Control Bit
1 = Timer1 start.
0 = Timer1 stop.
It is set and cleared by software.
Bit 5 – TF0: Timer0 Overflow Flag
1 = Timer0 overflow occurred (i.e. Timer0 goes to its max and roll over back to zero).
0 = Timer0 overflow not occurred.
It is cleared through software. In Timer0 overflow interrupt service routine, this bit will get cleared
automatically while exiting from ISR.
Bit 4 – TR0: Timer0 Run Control Bit
1 = Timer0 start.
0 = Timer0 stop.
It is set and cleared by software.
Bit 3 - IE1: External Interrupt1 Edge Flag
1 = External interrupt1 occurred.
0 = External interrupt1 Processed.
It is set and cleared by hardware.
Bit 2 - IT1: External Interrupt1 Trigger Type Select Bit
1 = Interrupt occur on falling edge at INT1 pin.
0 = Interrupt occur on low level at INT1 pin.
Bit 1 – IE0: External Interrupt0 Edge Flag
1 = External interrupt0 occurred.
0 = External interrupt0 Processed.
It is set and cleared by hardware.
Bit 0 – IT0: External Interrupt0 Trigger Type Select Bit
1 = Interrupt occur on falling edge at INT0 pin.
0 = Interrupt occur on low level at INT0 pin.
145 SECTION 9.2: COUNTER PROGRAMMING

Table 9–2 Equivalent Instructions for the Timer Control Register (TCON)
Mode 0 (13-bit timer mode)

Mode 0 is 13-bit timer mode for which 8-bit of THx and 5-bit of
TLx (as Prescaler) are used.

As shown in above figure, 8-bit of THx and lower 5-bit of TLx used to form a
total 13-bit timer. Higher 3-bits of TLx should be written as zero while using
timer mode0, or it will affect the result.
Example

Let's generate a square wave of 2mSec period using an AT89C51


microcontroller with timer0 in mode0 on P1.0 pin of port1. Assume xtal
oscillator frequency of 11.0592 MHz.

As Xtal oscillator frequency is 11.0592 MHz we have machine cycle of 1.085uSec.


Hence, required count to generate delay of 1mSec. is,
Count =(1×10^-3)/(1.085×10^-6) ≈ 921
Maximum count of Mode0 is 2^13 (0 - 8191) and Timer0 count will increment from 0 –
8191. So we need to load value which is 921 less from its maximum count i.e. 8191.
Also, here in the below program, we need additional 13 MC (machine cycles) from call
to return of delay function. Hence value needed to be loaded is,
Value=(8191-Count)+Function_MCycles+1 =7284= 0x1C74
So we need to load 0x1C74 value in Timer0.
1C74 = 0001 1100 0111 0100 b, now load lower 5-bit in TL0 and next 8-bit in TH0
so here we get,
TL0 = 0001 0100 = 0x14 and TH0 = 1110 0011 = 0xE3
Programming steps for delay function

1. Load TMOD register value i.e. TMOD = 0x00 for Timer0/1 mode0 (13-bit
timer mode).
2. Load calculated THx value i.e. here TH0 = 0xE3.
3. Load calculated TLx value i.e. here TL0 = 0x14.
4. Start timer by setting TRx bit. i.e. here TR0 = 1.
5. Poll TFx flag till it does not get set.
6. Stop timer by clearing TRx bit. i.e. here TR0 = 0.
7. Clear timer flag TFx bit i.e. here TF0 = 0.
8. Repeat from step 1 to 7 for delay again.
Mode 1 programming
149

16-bit timer, values of 0000 to FFFFH


TH and TL are loaded with a 16-bit initial value
timer started by "SETB TR0" for Timer 0 and "SETB TR1" for
Timer l
timer count ups until it reaches its limit of FFFFH
rolls over from FFFFH to 0000H
sets TF (timer flag)
when this timer flag is raised, can stop the timer with "CLR
TR0" or "CLR TR1“
after the timer reaches its limit and rolls over, the registers
TH and TL must be reloaded with the original value and TF
must be reset to 0
150 SECTION 9.1: PROGRAMMING 8051 Counter

Figure 9–5a Timer 0 with External Input (Mode 1)


151 SECTION 9.1: PROGRAMMING 8051 TIMERS
(for information only)

Figure 9–5b Timer 1 with External Input (Mode 1)


152 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Steps to program in mode 1


 Set timer mode 1 or 2
 Set TL0 and TH0 (for mode 1 16 bit mode)
 Set TH0 only (for mode 2 8 bit auto reload mode)
 Run the timer
 Monitor the timer flag bit
153 Example 9-4
In the following program, we are creating 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
154
Example 9-9
The following program generates a square wave on pin P 1.5 continuously
using Timer 1 for a time delay. Find the frequency of the square wave if XTAL =
11.0592 MHz. In your calculation do not include the overhead due to the timer
setup instructions in the loop.
155 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Finding values to be loaded into the timer


 XTAL = 11.0592 MHz (12MHz)
 divide the desired time delay by 1.085ms (1ms) to get n
 65536 – n = N
 convert N to hex yyxx
 set TL = xx and TH = yy
156
Assuming XTAL = 11.0592 MHz, write a program to generate a
square wave of 50 Hz frequency on pin P2.3.

 T = 1/50 Hz = 20 ms
 1/2 of it for the high and low portions of the pulse = 10 ms
 10 ms / 1.085 us = 9216
 65536 - 9216 = 56320 in decimal = DC00H
 TL = 00 and TH = DCH
 The calculation for 12MHz crystal uses the same steps
Example 9-12 (cont)
157
Assuming XTAL = 11.0592 MHz, write a program to generate a square
wave of 50 Hz frequency on pin P2.3.
158 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Generating a large time delay


 size of the time delay depends
 crystal frequency
 timer's 16-bit register in mode 1

 largest time delay is achieved by making both TH and TL zero


 what if that is not enough?
159 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Using Windows calculator to find TH, TL


 Windows scientific calculator can be use to find the TH, TL values
 Lets say we would like to find the TH, TL values for a time delay that
uses 35,000 clocks of 1.085ms
1. open scientific calculator and select decimal
2. enter 35,000
3. select hex - converts 35,000 to hex 88B8H
4. select +/- to give -35000 decimal (7748H)
5. the lowest two digits (48) of this hex value are for TL and the next two
(77) are for TH
Example 9-13
160
Examine the following program and find the time delay in seconds.
Exclude the time delay due to the instructions in the loop.
161 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Mode 2 programming
 8-bit timer, allows values of 00 to FFH
 TH is loaded with the 8-bit value
 a copy is given to TL
 timer is started by ,"SETB TR0" or "SETB TR1“
 starts to count up by incrementing the TL register
 counts up until it reaches its limit of FFH
 when it rolls over from FFH to 00, it sets high TF
 TL is reloaded automatically with the value in TH
 To repeat, clear TF
 mode 2 is an auto-reload mode
162 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Steps to program in mode 2


1. load TMOD, select mode 2
2. load the TH
3. start timer
4. monitor the timer flag (TF) with "JNB”
5. get out of the loop when TF=1
6. clear TF
7. go back to Step 4 since mode 2 is auto-reload
Assuming that XTAL = 11.0592 MHz, find (a) the frequency of the square wave
generated on pin P1.0 and (b) the smallest frequency achievable in this program,
163
and the TH value to do that.
164 SECTION 9.1: PROGRAMMING 8051 TIMERS

 Assemblers and negative values


 can let the assembler calculate the value for TH and TL which makes
the job easier
 "MOV TH1, # -100", the assembler will calculate the -100 = 9CH
 "MOV TH1,#high(-10000) "
 "MOV TL1,#low(-10000) "
165 SECTION 9.2: COUNTER PROGRAMMING (for
information only)

 C/T bit in TMOD register


 used as a timer, the 8051's crystal is used as the source of the frequency
 used as a counter, pulse outside the 8051 increments the TH, TL registers
 counter mode, TMOD and TH, TL registers are the same as for the timer
 timer modes are the same as well
166 SECTION 9.2: COUNTER PROGRAMMING (for
information only)
 C/T bit in TMOD register
 C/T bit in the TMOD register decides the source of the clock for the timer
 C/T = 0, timer gets pulses from crystal
 C/T = 1, the timer used as counter and gets pulses from outside the 8051
 C/T = 1, the counter counts up as pulses are fed from pins 14 and 15
 pins are called T0 (Timer 0 input) and T1 (Timer 1 input)
 these two pins belong to port 3
 Timer 0, when C/T = 1, pin P3.4 provides the clock pulse and the counter
counts up for each clock pulse coming from that pin
 Timer 1, when C/T = 1 each clock pulse coming in from pin P3.5 makes
the counter count up
167 SECTION 9.2: COUNTER PROGRAMMING

Table 9–1 Port 3 Pins Used For Timers 0 and 1


168 Example 9-18
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. (for information only)

to LEDs

P2 is connected to 8 LEDs and input T1 to pulse.


169 SECTION 9.2: COUNTER PROGRAMMING

Figure 9–6 Timer 0 with External Input (Mode 2)


170 SECTION 9.2: COUNTER PROGRAMMING

Figure 9–7 Timer 1 with External Input (Mode 2)


171 SECTION 9.2: COUNTER PROGRAMMING
172 SECTION 9.2: COUNTER PROGRAMMING
173 SECTION 9.2: COUNTER PROGRAMMING

 The case of GATE = 1 in TMOD


 GATE = 0, the timer is started with instructions "SETB TR0" and "SETB TR1“
 GATE = 1, the start and stop of the timers are done externally through pins P3.2
and P3.3
 allows us to start or stop the timer externally at any time via a simple switch
174 SECTION 9.2: COUNTER PROGRAMMING

Figure 9–8 Timer/Counter 0


175 SECTION 9.2: COUNTER PROGRAMMING

Figure 9–9 Timer/Counter 1


Good Morning

8051 SERIAL PORT


PROGRAMMING IN ASSEMBLY
17
6
177 OBJECTIVES

 Contrast and compare serial versus parallel communication


 List the advantages of serial communication over parallel
 Explain serial communication protocol
 Contrast synchronous versus asynchronous communication
 Contrast half-versus full-duplex transmission
 Explain the process of data framing
 Describe data transfer rate and bps rate
 Define the RS232 standard
 Explain the use of the MAX232 and MAX233 chips
178 BASICS OF SERIAL COMMUNICATION

Serial versus Parallel Data Transfer


179 BASICS OF SERIAL COMMUNICATION

 serial communication uses single data line making it much


cheaper
 enables two computers in different cities to communicate over
the telephone
 byte of data must be converted to serial bits using a parallel-in-
serial-out shift register and transmitted over a single data line
 receiving end there must be a serial-in-parallel-out shift register
 if transferred on the telephone line, it must be converted to
audio tones by modem
 for short distance the signal can be transferred using wire
 how PC keyboards transfer data to the motherboard
180 BASICS OF SERIAL COMMUNICATION
2 methods, asynchronous and synchronous
synchronous method transfers a block of data
(characters) at a time
asynchronous method transfers a single byte at
a time
Uses special IC chips called UART (universal
asynchronous receiver-transmitter) and USART
(universal synchronousasynchronous receiver-
transmitter)
8051 chip has a built-in UART
181 BASICS OF SERIAL COMMUNICATION

Simplex, Half-, and Full-Duplex Transfers


182 BASICS OF SERIAL COMMUNICATION
 Half- and full-duplex transmission
if the data can be transmitted and received, it is a
duplex transmission
simplex transmissions the computer only sends data
duplex transmissions can be half or full duplex
depends on whether or not the data transfer can be
simultaneous
If one way at a time, it is half duplex
If can go both ways at the same time, it is full duplex
full duplex requires two wire conductors for the data
lines (in addition to the signal ground)
183 BASICS OF SERIAL COMMUNICATION

Asynchronous serial communication and data


framing
data coming in 0s and 1s
to make sense of the data sender and receiver agree
on a set of rules
Protocol
how the data is packed
how many bits/character
when the data begins and ends
184 BASICS OF SERIAL COMMUNICATION
Start and stop bits
asynchronous method, each character is placed
between start and stop bits
called framing
start bit is always one bit
stop bit can be one or two bits
start bit is always a 0 (low)
stop bit(s) is 1 (high)
LSB is sent out first
185 BASICS OF SERIAL COMMUNICATION

Framing ASCII “A” (41H)


186 BASICS OF SERIAL COMMUNICATION

 in modern PCs one stop bit is standard


 when transferring a text file of ASCII characters using 1
stop bit there is total of 10 bits for each character
 8 bits for the ASCII code (1 parity bit), 1 bit each for the
start and stop bits
 for each 8-bit character there are an extra 2 bits, which
gives 20% overhead
187 BASICS OF SERIAL COMMUNICATION

Data transfer rate


rate of data transfer bps (bits per second)
widely used terminology for bps is baud rate
baud and bps rates are not necessarily equal
baud rate is defined as the number of signal changes
per second
Bauds Vs BPS
189 BASICS OF SERIAL COMMUNICATION
 RS232 standards
 most widely used serial I/O interfacing standard
 input and output voltage levels are not TTL compatible
 1 bit is represented by -3 to -25 V
 0 bit is +3 to +25 V
 -3 to +3 is undefined
 to connect RS232 to a microcontroller system must use voltage
converters such as MAX232 to convert the TTL logic levels to
the RS232 voltage levels, and vice versa
 MAX232 IC chips are commonly referred to as line drivers
190 BASICS OF SERIAL COMMUNICATION

RS232 Connector DB-25

RS232 Pins (DB-25)


191 BASICS OF SERIAL COMMUNICATION

DB-9 9-Pin Connector

IBM PC DB-9 Signals


192 BASICS OF SERIAL COMMUNICATION

 Data communication classification


 DTE (data terminal equipment)
 DCE (data communication equipment)
 DTE - terminals and computers that send and receive
data
 DCE - communication equipment responsible for
transferring the data
 simplest connection between a PC and microcontroller
requires a minimum of three pins, TxD, RxD, and ground
193 BASICS OF SERIAL COMMUNICATION

Null Modem Connection


194 BASICS OF SERIAL COMMUNICATION

Examining RS232 handshaking signals


many of the pins of the RS-232 connector are
used for handshaking signals
they are not supported by the 8051 UART
chip
195 BASICS OF SERIAL COMMUNICATION

PC/compatible COM ports


PC/compatible computers (Pentium) microprocessors
normally have two COM ports
both ports have RS232-type connectors
COM ports are designated as COM 1 and COM 2
(replaced by USB ports)
can connect the 8051 serial port to the COM 2 port
196 8051 CONNECTION TO RS232
 RxD and TxD pins in the 8051
 8051 has two pins used for transferring and receiving
data serially
 TxD and RxD are part of the port 3 group
 pin 11 (P3.1) is assigned to TxD
 pin 10 (P3.0) is designated as RxD
 these pins are TTL compatible
 require a line driver to make them RS232 compatible
 driver is the MAX232 chip
197 8051 CONNECTION TO RS232

 MAX232
 converts from RS232 voltage levels to TTL voltage levels
 uses a +5 V power source
 MAX232 has two sets of line drivers for transferring and
receiving data
 line drivers used for TxD are called T1 and T2
 line drivers for RxD are designated as R1 and R2
 T1 and R1 are used together for TxD and RxD of the 8051
 second set is left unused
198 8051 CONNECTION TO RS232

(a) Inside MAX232


(b) its Connection to the 8051 (Null Modem)
199 8051 CONNECTION TO RS233

MAX233
MAX233 performs the same job as the MAX232
eliminates the need for capacitors
much more expensive than the MAX232
200 8051 CONNECTION TO RS233

(a) Inside MAX233


(b) Its Connection to the 8051 (Null Modem)
201 8051 SERIAL PORT PROGRAMMING

Baud rate in the 8051


serial communications of the 8051 with the COM port of
the PC
must make sure that the baud rate of the 8051 system
matches the baud rate of the PC's COM port
can use Windows HyperTerminal program
8051 SERIAL PORT PROGRAMMING
202

PC Baud Rates
203 8051 SERIAL PORT PROGRAMMING

 Baud rate in the 8051


 baud rate in the 8051 is programmable
 done with the help of Timer 1
 relationship between the crystal frequency and the baud rate in the
8051
 8051 divides the crystal frequency by 12 to get the machine cycle
frequency
 XTAL = 11.0592 MHz, the machine cycle frequency is 921.6 kHz
 8051's UART divides the machine cycle frequency of 921.6 kHz by 32
once more before it is used by Timer 1 to set the baud rate
 921.6 kHz divided by 32 gives 28,800 Hz
 Timer 1 must be programmed in mode 2, that is 8-bit, auto-reload
8051 SERIAL PORT PROGRAMMING
204

Timer 1 TH1 Register Values for Various Baud Rates


205 Example: With XTAL = 11.0592 MHz, find the TH1 value
needed to have the following baud rates. (a) 9600 (b)
2400 (c) 1200

 machine cycle frequency: = 11.0592 MHz / 12 = 921.6 kHz


 Timer 1 frequency provided by 8051 UART
= 921.6 kHz / 32 = 28,800 Hz

(a) 28,800 / 3 = 9600 where -3 = FD (hex)


(b) 28,800 / 12 = 2400 where -12 = F4 (hex)
(c) 28,800 / 24 = 1200 where -24 = E8 (hex)
206 8051 SERIAL PORT PROGRAMMING

11.0592 MHz
XTAL oscillator
207 8051 SERIAL PORT PROGRAMMING

SBUF (serial buffer) register


a byte of data to be transferred via the TxD line must be placed
in the SBUF register
SBUF holds the byte of data when it is received by the RxD line
can be accessed like any other register
MOV SBUF,#'D' ;load SBUF=44H, ASCII for 'D‘
MOV SBUF,A ;copy accumulator into SBUF
MOV A,SBUF ;copy SBUF into accumulator
when a byte is written, it is framed with the start and stop bits
and transferred serially via the TxD pin
when the bits are received serially via RxD, it is deframe by
eliminating the stop and start bits, making a byte out of the data
received, and then placing it in the SBUF
PCON

Bit 7 – SMOD
1 = Baud rate is doubled in UART mode 1, 2 and 3.
0 = No effect on Baud rate.
Bit 3:2 – GF1 & GF0:
These are general purpose bit for user.
Bit 1 – PD: Power Down
1 = Enable Power Down mode. In this mode, Oscillator clock turned OFF
and both CPU and peripherals clock stopped. Hardware reset can cancel this
mode.
0 = Disable Power down mode.
Bit 0 – IDL: Idle
1 = Enable Idle mode. CPU clock turned off whereas internal peripheral
module such as timer, serial port, interrupts works normally. Interrupt and
H/W reset can cancel this mode.
0 = Disable Idle mode.
SCON Register
209

•D7-FE – Framing error bit. (If SMOD = 1, then bit 7 (SCON) = FE, and if SMOD = 0, then bit 7 (SCON)
= SM0. FE (Framing Error) is set if a zero is detected in the position of the stop bit while receiving a
character, and cleared by writing zero to the corresponding position of SCON)
•D7-SM0 – This bit is used for serial port mode selection.
•D6-SM1 – This bit is used for serial port mode selection.
•D5-SM2 – This bit is used for serial port mode selection, also known as multiprocessor
communication enable bit. When set, it enables multiprocessor communication in mode 2 and 3, and
eventually mode 1. It should be cleared in mode 0.
•D4-REN – Reception Enable bit enables serial reception when set. When cleared, serial reception is
disabled.
•D3-TB8 – Transmitter bit 8. Since all registers are 8-bit wide, this bit solves the problem of
transmitting the 9th bit in modes 2 and 3. It is set to transmit a logic 1 in the 9th bit.
•D2-RB8 – Receiver bit 8 or the 9th bit received in modes 2 and 3. Cleared by hardware if 9th bit
received is a logic 0. Set by hardware if 9th bit received is a logic 1.
•D1-TI – Transmit Interrupt flag is automatically set at the moment the last bit of one byte is sent.
It’s a signal to the processor that the line is available for a new byte to transmit. It must be cleared
from within the software.
•D0-RI – Receive Interrupt flag is automatically set upon one byte to receive. It signals that byte is
received and should be read quickly prior to being replaced by new data. This bit is also cleared from
within the software.
SCON Register
Mode 0
 In mode 0, serial data are transmitted and received through the
RXD pin, while the TXD pin output clocks. The baud rate is fixed
at 1/12 the oscillator frequency. On transmit, the least significant
bit (LSB bit) is sent/received first.
 Transmission and Reception process
 Transmission – Data transmit is initiated by writing data to the SBUF
register. When all 8 bits have been sent, the TI bit of the SCON register is
automatically set.
 Reception – Data received through the RXD pin are recognized when the
following two conditions are met: bit REN=1 and RI=0. When all 8 bits have
been received, the RI bit of the SCON register is automatically set indicating
that one-byte receive is complete. Since there is no START and STOP bits or
any other bit except data sent from the SBUF register in the pulse sequence,
this mode is mainly used when the distance between devices is short, noise
is minimized.
Mode 1
 10 bits are transmitted through the TXD pin or received through
the RXD pin in the following manner: a START bit (always 0), 8 data
bits (LSB first) and a STOP bit (always 1). The START bit is only used
to initiate data receive, while the STOP bit is automatically written to
the RB8 bit of the SCON register.
 Transmission and Reception process
 Transmission – Data transmit is initiated by writing data to the SBUF
register. End of data transmission is indicated by setting the TI bit of the
SCON register.
 Reception – The START bit (logic zero (0)) on the RXD pin initiates data
receive. The following two conditions must be met: bit REN=1 and bit RI=0.
Both of them are stored in the SBUF register. The RI bit is automatically set
upon data reception is complete. The Baud rate in this mode is determined
by the timer 1.
Mode 2
 11 bits are transmitted through the TXD pin or received through the RXD
pin: a START bit (always 0), 8 data bits (LSB first), a programmable 9th
data bit and a STOP bit (always 1). On transmit, the 9th data bit is
actually the TB8 bit of the SCON register. This bit usually has a function of
parity bit. On receive, the 9th data bit goes into the RB8 bit of the same
register (SCON).The baud rate is either 1/32 or 1/64 the oscillator
𝟐𝑺𝑴𝑶𝑫(𝟎,𝟏)
frequency.: 𝒇𝒃𝒂𝒖𝒅𝟐 = 𝟔𝟒𝒅
× 𝑶𝒔𝒄𝒊𝒍𝒍𝒂𝒕𝒐𝒓 𝑭𝒓𝒆𝒒𝒖𝒆𝒏𝒄𝒚
 Transmission and Reception process
 Transmission – Data transmit is initiated by writing data to the SBUF register.
End of data transmission is indicated by setting the TI bit of the SCON register.
 Reception – The START bit (logic zero (0)) on the RXD pin initiates data receive.
The following two conditions must be met: bit REN=1 and bit RI=0. Both of them
are stored in the SBUF register. The RI bit is automatically set upon data
reception is complete.
Mode 3
 Mode 3 is the same as Mode 2 in all respects except the baud
rate.
 The baud rate in Mode 3 is variable.
 The parity bit is the P bit of the PSW register.
 Before initiating data transmit, the byte to transmit is stored in
the accumulator and the P bit goes into the TB8 bit in order to
be “a part of the message”.
 The procedure is opposite on receive, received byte is stored in
the accumulator and the P bit is compared with the RB8 bit.
 If there are no variations the data received is correct.
215 8051 SERIAL PORT PROGRAMMING

 SM0 and SM1 determine the mode


 only mode 1 is important
 when mode 1 is chosen, the data framing is 8 bits, 1 stop bit,
and 1 start bit
 compatible with the COM port of PCs
 mode 1 allows the baud rate to be variable and is set by Timer
1 of the 8051
 for each character a total of 10 bits are transferred, where the
first bit is the start bit, followed by 8 bits of data, and finally 1
stop bit.
216 8051 SERIAL PORT PROGRAMMING

REN (receive enable)


REN=1, allows 8051 to receive data on the RxD
if 8051 is to both transfer and receive data, REN must
be set to 1
REN=0, the receiver is disabled
SETB SCON.4 and CLR SCON.4,
217 8051 SERIAL PORT PROGRAMMING

 TI (transmit interrupt)
 when 8051 finishes the transfer of the 8-bit character, it raises the TI flag to
indicate that it is ready to transfer another byte
 RI (receive interrupt)
 when the 8051 receives data serially via RxD, it places the byte in the
SBUF register
 then raises the RI flag bit to indicate that a byte has been received and
should be picked up before it is lost
8051 SERIAL PORT PROGRAMMING IN
218
ASSEMBLY

 Program to transfer data serially


1. TMOD register is loaded with the value 20H
2. TH1 is loaded with value to set the baud rate
3. SCON register is loaded with the value 50H
4. TR1 is set to 1 to start Timer1
5. TI is cleared by the "CLR TI" instruction
6. transmit character byte is written into the SBUF register
7. TI flag bit is monitored to see if the character has been transferred
completely
8. to transfer the next character, go to Step 5.
219
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:
MOV TMOD,#20H ;timer 1,mode 2(auto reload)
MOV TH1,#-6 ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
HERE:JNB RI,HERE ;wait for char to come in
MOV A,SBUF ;saving incoming byte in A
MOV P1,A ;send to port 1
CLR RI ;get ready to receive next byte
SJMP HERE ;keep getting data
Example 10-5
Assume that the 8051 serial port is connected to the COM port of a PC, and on the PC,
220 we are using the hyperterminal program to send and receive data serially. P1 and P2 of
the 8051 are connected to LEDs and switches, respectively. Write an 8051 program to (a)
send to PC the message “We Are Ready”, (b) receive any data send by PC and put it on
LEDs connected to P1, and (c) get data on switches connected to P2 and send it to PC
serially. The program should perform part (a) once, but parts (b) and (c) continuously,
use 4800 baud rate.

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
MOVC A,@A+DPTR ;get the character
Contd….
Contd from prev slide….
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
;----serial data transfer. ACC has the data-----
SEND: MOV SBUF,A ;load the data
H_2: JNB TI,H_2 ;stay here until last bit gone
CLR TI ;get ready for next char
RET ;return to caller
;----Receive data serially in ACC---------------
RECV: JNB RI,RECV ;wait here for char
MOV A,SBUF ;save it in ACC
CLR RI ;get ready for next char
RET ;return to caller
;-----The message---------------
MYDATA:DB ‘We Are Ready’,0
END
8051 SERIAL PORT PROGRAMMING
223

Importance of the TI flag


check the TI flag bit, we know whether can transfer
another byte
TI flag bit is raised by the 8051
TI flag cleared by the programmer
writing a byte into SBUF before the TI flag bit is raised,
may lead to loss of a portion of the byte being transferred
8051 SERIAL PORT PROGRAMMING
224

 Program to receive data serially


1. TMOD register is loaded with the value 20H
2. TH1 is loaded with value set the baud rate
3. SCON register is loaded with the value 50H
4. TR1 is set to 1 to start Timer 1
5. RI is cleared with the "CLR RI" instruction
6. RI flag bit is monitored to see if an entire character has been received yet
7. RI=1 SBUF has the byte, its contents are moved into a safe place
8. to receive the next character, go to Step 5
225 8051 SERIAL PORT PROGRAMMING

 Importance of the RI flag bit


1. it receives the start bit, next bit is the first bit of the
character
2. when the last bit is received, a byte is formed and placed in
SBUF
3. when stop bit is received, makes RI = 1
4. when RI=1, received byte is in the SBUF register, copy
SBUF contents to a safe place
5. after the SBUF contents are copied the RI flag bit must be
cleared to 0
226
8051 SERIAL PORT PROGRAMMING
 Doubling the baud rate in the 8051
 two ways to increase the baud rate
1. Use a higher-frequency crystal
2. Change a bit in the PCON register: Baud*𝟐𝑺𝑴𝑶𝑫(𝟎,𝟏)

Baud Rate Comparison for SMOD = 0 and SMOD = 1


Mode 2

𝟐𝑺𝑴𝑶𝑫(𝟎,𝟏)
𝒇𝒃𝒂𝒖𝒅𝟐 = × 𝑶𝒔𝒄𝒊𝒍𝒍𝒂𝒕𝒐𝒓 𝑭𝒓𝒆𝒒𝒖𝒆𝒏𝒄𝒚
𝟔𝟒𝒅
228
8051 SERIAL PORT PROGRAMMING

Interrupt-based data transfer


it is a waste of the microcontroller's time to poll the
TI and RI flags
to avoid wasting time, use interrupts instead of
polling
8051 INTERRUPTS

229
230 OBJECTIVES
 Contrast and compare interrupts versus polling
 Explain the purpose of the ISR (interrupt service routine)
 List the 6 interrupts of the 8051
 Explain the purpose of the interrupt vector table
 Enable or disable 8051 interrupts
 Program the 8051 timers using interrupts
 Describe the external hardware interrupts of the 8051
 Contrast edge-triggered with level-triggered interrupts
 Program the 8051 for interrupt-based serial communication
 Define the interrupt priority of the 8051
231 8051 INTERRUPTS
Interrupts vs. polling
on receiving interrupt, the microcontroller
interrupts whatever it is doing and executes
interrupt service routine (ISR)
microcontroller can serve many devices
each device gets attention based on the priority
polling wastes time
232 8051 INTERRUPTS

Interrupt service routine


for each interrupt there must be ISR
for every interrupt, there is a fixed location in
memory that holds the address of its ISR
interrupt vector table
233 8051 INTERRUPTS

Interrupt Vector Table for the 8051


234 8051 INTERRUPTS
 Steps in executing an interrupt
1. Micro Controller finishes the instruction it is executing and saves the address
of the next instruction (PC) on the stack
2. it saves the current status of all the interrupts internally
3. it jumps to a fixed location in memory called the interrupt vector table
4. the microcontroller gets the address of the ISR from the interrupt vector table
and jumps to it and starts to execute the ISR until it reaches the last
instruction RETI
5. the microcontroller returns to the place where it was interrupted, it gets the
PC address from the stack by popping the top two bytes of the stack into the
PC and then it starts to execute from that address
235 8051 INTERRUPTS

ORG 0 ;wake-up ROM reset location


LJMP MAIN ;by-pass int. vector table

;---- the wake-up program


ORG 30H
MAIN:
....
END
Redirecting the 8051 from the Interrupt Vector Table at Power-up
236 8051 INTERRUPTS
Enabling and disabling an interrupt
upon reset all interrupts are disabled
interrupts must be enabled by software
IE register (interrupt enable) is responsible for
enabling and disabling the interrupts
IE is a bit-addressable register
237 8051 INTERRUPTS

 Steps in enabling an interrupt


1. EA must be set to 1
2. set the relevant bits in IE register to high
3. EA = 0, no interrupt will be responded to, even if
the relevant bit in the IE register is high
IE (Interrupt Enable) Register
D7 D6 D5 D4 D3 D2 D1 D0
EA --- ET2 ES ET1 EX1 ET0 EX0
239 Example
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:
(a)MOV IE,#10010110B ;enable serial,timer 0, EX1

Another way to perform the same manipulation is


SETB IE.7 ;EA=1, global enable
SETB IE.4 ;enable serial interrupt
SETB IE.1 ;enable Timer 0 interrupt
SETB IE.2 ;enable EX1

(b) CLR IE.1 ;mask (disable) timer 0 ,interrupt only

(c) CLR IE.7 ;disable all interrupts


240 PROGRAMMING TIMER INTERRUPTS
 Roll-over timer flag and interrupt

 if the timer interrupt is enabled, whenever TF=1, the microcontroller is


interrupted in whatever it is doing, and jumps to the interrupt vector
table to service the ISR
Example 11-2
241 Write a program that continuously get 8-bit data from P0 and sends it to P1 while simultaneously creating a square wave of
200 micro second period on pin P2.1. Use timer 0 to create the square wave. Assume that XTAL = 11.0592 MHz.
Solution:
We will use timer 0 in mode 2 (auto reload). TH0 = 100/1.085 us = 92
;--upon wake-up go to main, avoid using
;memory allocated to Interrupt Vector Table
ORG 0000H
LJMP MAIN ;by-pass interrupt vector table
;
;--ISR for timer 0 to generate square wave
ORG 000BH ;Timer 0 interrupt vector table
CPL P2.1 ;toggle P2.1 pin
RETI ;return from ISR
;--The main program for initialization
ORG 0030H ;after vector table space
MAIN: MOV TMOD,#02H ;Timer 0, mode 2
MOV P0,#0FFH ;make P0 an input port
MOV TH0,#-92 ;TH0=A4H for -92
MOV IE,#82H ;IE=10000010 (bin) enable, Timer 0
SETB TR0 ;Start Timer 0
BACK: MOV A,P0 ;get data from P0
MOV P1,A ;issue it to P1
SJMP BACK ;keep doing it loop unless interrupted by TF0
END
Bit 3 - IE1: External Interrupt1 Edge Flag
1 = External interrupt1 occurred.
0 = External interrupt1 Processed.
It is set and cleared by hardware.
TCON Bits for Bit 2 - IT1: External Interrupt1 Trigger Type Select Bit
Interrupt 1 = Interrupt occur on falling edge at INT1 pin.
0 = Interrupt occur on low level at INT1 pin.
Bit 1 – IE0: External Interrupt0 Edge Flag
1 = External interrupt0 occurred.
0 = External interrupt0 Processed.
It is set and cleared by hardware.
Bit 0 – IT0: External Interrupt0 Trigger Type Select Bit
1 = Interrupt occur on falling edge at INT0 pin.
0 = Interrupt occur on low level at INT0 pin.
243 PROGRAMMING EXTERNAL HARDWARE INTERRUPTS

 External interrupts INT0 and INT1

Activation of INT0 and INT1


244 PROGRAMMING EXTERNAL HARDWARE INTERRUPTS

Level-triggered interrupt
INT0 and INT1 pins are normally high
if low-level signal is applied, it triggers the interrupt
microcontroller stops whatever it is doing and jumps to
the interrupt vector table to service the interrupt
the low level signal must be removed before the
execution of the last instruction of the interrupt service
routine, RETI
otherwise, another interrupt will be generated
Example 11-5
Assume that the INT1 pin is connected to a switch that is normally
245 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 0013H ;INT1 ISR
SETB P1.3 ;turn on LED
MOV R3,#255
BACK: DJNZ R3,BACK ;keep LED on for a while
CLR P1.3 ;turn off the LED
RETI ;return from ISR
;--MAIN program for initialization
ORG 30H
MAIN: MOV IE,#10000100B ;enable external INT 1
HERE: SJMP HERE ;stay here until get interrupted
END
246 PROGRAMMING EXTERNAL HARDWARE
INTERRUPTS

 Sampling the low level-triggered interrupt


 to ensure the activation of the hardware interrupt at the INTx
pin, make sure that the duration of the low-level signal is
around 4 machine cycles
247 PROGRAMMING EXTERNAL HARDWARE
INTERRUPTS

 Sampling the low level-triggered interrupt

Minimum Duration of the Low Level-Triggered Interrupt (XTAL = 11.0592 MHz)


Assume that pin 3.3 (INT1) is connected to a pulse generator, write a program in
which the falling edge of the pulse will send a high to P1.3, which is connected
248
to an LED (or buzzer). In other words, the LED is turned on and off at the same
rate as the pulses are applied to the INT1 pin.
Solution:
ORG 0000H
LJMP MAIN
;--ISR for hardware interrupt INT1 to turn on LED
ORG 0013H ;INT1 ISR
SETB P1.3 ;turn on LED
MOV R3,#255
BACK: DJNZ R3,BACK ;keep the buzzer on for a while
CLR P1.3 ;turn off the buzzer
RETI ;return from ISR
;------MAIN program for initialization
ORG 30H
MAIN: SETB TCON.2 ;make INT1 edge-triggered int.
MOV IE,#10000100B ;enable External INT 1
HERE: SJMP HERE ;stay here until get interrupted
END
249 PROGRAMMING EXTERNAL HARDWARE
INTERRUPTS

 Sampling the edge-triggered interrupt


 external source must be held high for at least one machine cycle, and
then held low for at least one machine cycle to ensure that the transition
is seen by the microcontroller

Minimum pulse duration to detect edge-


triggered interrupts XTAL=11.0592MHz
250
PROGRAMMING THE SERIAL
COMMUNICATION INTERRUPT
 RI and TI flags and interrupts
 1 interrupt is set for serial communication
 used to both send and receive data
 when RI or TI is raised the 8051 gets interrupted and jumps to
memory address location 0023H to execute the ISR
 the ISR must examine the TI and RI flags to see which one
caused the interrupt and respond accordingly
Write a program in which the 8051 reads data from P1 and writes it to P2 continuously while giving a copy of it
to the serial COM port to be transferred serially. Assume that XTAL=11.0592. Set the baud rate at 9600.
251 ORG 0000H
LJMP MAIN
ORG 23H
LJMP SERIAL ;jump to serial int ISR
ORG 30H
MAIN: MOV P1,#0FFH ;make P1 an input port
MOV TMOD,#20H ;timer 1, auto reload
MOV TH1,#0FDH ;9600 baud rate
MOV SCON,#50H ;8-bit,1 stop, ren enabled
MOV IE,10010000B ;enable serial int.
SETB TR1 ;start timer 1
BACK: MOV A,P1 ;read data from port 1
MOV SBUF,A ;give a copy to SBUF
MOV P2,A ;send it to P2
SJMP BACK ;stay in loop indefinitely
;-----------------SERIAL PORT ISR
ORG 100H
SERIAL: JB TI,TRANS;jump if TI is high
MOV A,SBUF ;otherwise due to receive
CLR RI ;clear RI since CPU doesn’t
RETI ;return from ISR
TRANS: CLR TI ;clear TI since CPU doesn’t
RETI ;return from ISR
END
252 SERIAL COMMUNICATION INTERRUPT

Table 11–2 Interrupt Flag Bits for the 8051/52


Example:
Write a program using interrupts to do the following:
253 (a) Receive data serially and sent it to P0,
(b) Have P1 port read and transmitted serially, and a copy given to P2,
(c) Make timer 0 generate a square wave of 5kHz frequency on P0.1.
Assume that XTAL-11,0592. Set the baud rate at 4800.
Solution: MOV IE,10010010B ;enable serial int.
SETB TR1 ;start timer 1
ORG 0 SETB TR0 ;start timer 0
LJMP MAIN BACK: MOV A,P1 ;read data from port 1
ORG 000BH ;ISR for timer 0 MOV SBUF,A ;give a copy to SBUF
CPL P0.1 ;toggle P0.1 MOV P2,A ;send it to P2
RETI ;return from ISR SJMP BACK ;stay in loop indefinitely
ORG 23H ; ;------SERIAL PORT ISR
LJMP SERIAL;jump to serial ISR ORG 100H
ORG 30H SERIAL:JB TI,TRANS;jump if TI is high
MAIN:MOV P1,#0FFH ;make P1 an input port MOV A,SBUF ;otherwise due to receive
MOV TMOD,#22H;timer1,mode2(auto MOV P0,A ;send serial data to P0
reload) CLR RI ;clear RI since CPU doesn’t
MOV TH1,#0F6H;4800 baud rate RETI ;return from ISR
MOV SCON,#50H;8-bit, 1 stop, ren TRANS:CLR TI; clear TI
enabled RETI ;return from ISR
MOV TH0,#-92 ;for 5kHZ wave END
254 INTERRUPT PRIORITY IN THE 8051/52

 Interrupt priority upon reset

Table 11–3 8051/52 Interrupt Priority Upon Reset


255 INTERRUPT PRIORITY IN THE 8051/52

 Setting interrupt priority with the IP register

Figure 11–8 Interrupt Priority Register (Bit-addressable)


256 Example 11-12(a)
Program the IP register to assign the highest priority to INTI, then (b) discuss what
happens if INT0, INT1, and TF0are activated at the same time. Assume that the
interrupts are both edge-triggered.

 (a) MOV IP,#00000100B or "SETB IP.2“

 (b) when INT0, INT1, and TF0 interrupts are activated at the same time, the
8051 services INT1 first, then it services INT0, then TF0
257 INTERRUPT PRIORITY IN THE 8051/52

Interrupt inside an interrupt


what happens if the 8051 is executing an ISR belonging to
an interrupt and another interrupt is activated?
a high-priority interrupt can interrupt a low-priority
interrupt
no low-priority interrupt can get the immediate attention of
the CPU until it has finished servicing the high-priority
interrupts
258 INTERRUPT PRIORITY IN THE 8051/52

 Triggering the interrupt by software


 can test an ISR with instructions to set the interrupts high
 "SETB TF1" will interrupt the 8051 in whatever it is doing and
force it to jump to the interrupt vector table
 don’t have to wait for Timer 1 to roll over
 useful for testing ISR
8051-C

Write an 8051 C program to send values 00 – FF to port P1.


Solution:
#include <reg51.h>
void main(void)
{
unsigned char z;
for (z=0;z<=255;z++)
P1=z;
}
8051 C Data Types
ata Types Bits Bytes Value Range
bit 1 0 to 1
signed char 8 1 -128 - +127
unsigned char 8 1 0 – 255
enum 8 / 16 1 or 2 -128 - +127 or -32768 - +32767
signed short int 16 2 -32768 - +32767
unsigned short int 16 2 0 – 65535
signed int 16 2 -32768 - +32767
unsigned int 16 2 0 – 65535
signed long int 32 4 -2147483648 - +2147483647
unsigned long int 32 4 0 — 4294967295
float 32 4 ±1.175494E-38 - ±3.402823E+38
double 32 4 ±1.175494E-38 - ±3.402823E+38
sbit 1 0 or 1
sfr 8 1 0 – 255
sfr16 16 2 0 – 65535
The sbit type defines a bit within a special function register
(SFR). It is used in one of the following ways:

sbit name = sfr-name ^ bit-position;

sbit name = sfr-address ^ bit-position;

sbit name = sbit-address;

Where,
name: is the name of the SFR bit.
sfr-name: is the name of a previously-defined SFR.
bit-position: is the position of the bit within the SFR.
sfr-address: is the address of an SFR.
sbit-address: is the address of the SFR bit.
Write an 8051 C program to send hex values for ASCII characters of 0, 1,
2, 3, 4, 5, A, B, C, and D to port P1.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mynum[]=“012345ABCD”;
unsigned char z;
for (z=0;z<=10;z++)
P1=mynum[z];
}
Write an 8051 C program to toggle all the bits of P1 continuously.
Solution:
//Toggle P1 forever
#include <reg51.h>
void main(void)
{
for (;;)
{
p1=0x55;
p1=0xAA;
}
}
Write an 8051 C program to send values of –4 to +4 to port P1.
Solution:
//Singed numbers
#include <reg51.h>
void main(void)
{
char mynum[]={+1,-1,+2,-2,+3,-3,+4,-4};
unsigned char z;
for (z=0;z<=8;z++)
P1=mynum[z];
}
Write an 8051 C program to toggle bits of P1 continuously forever with some delay.
Solution:
//Toggle P1 forever with some delay in between
//“on” and “off”
#include <reg51.h>
void main(void)
{
unsigned int x;
for (;;) //repeat forever
{
p1=0x55;
for (x=0;x<40000;x++); //delay size unknown
p1=0xAA;
for (x=0;x<40000;x++);
}
}
Write an 8051 C program to toggle bits of P1 ports continuously with a 250 ms.
Solution:
#include <reg51.h>
void MSDelay(unsigned int);
void main(void)
{
while (1) //repeat forever
{
p1=0x55;
MSDelay(250);
p1=0xAA;
MSDelay(250);
}
}
void MSDelay(unsigned int itime)
{
unsigned int i,j;
for (i=0;i<itime;i++)
for (j=0;j<1275;j++);
}
LEDs are connected to bits P1 and P2. Write an 8051 C program that shows
the count from 0 to FFH (0000 0000 to 1111 1111 in binary) on the LEDs.

Solution:
#include <reg51.h>
#defind LED P2;
void main(void)
{
P1=00; //clear P1
LED=0; //clear P2
for (;;) //repeat forever
{
P1++; //increment P1
LED++; //increment P2
}
}
Write an 8051 C program to get a byte of data form P0. If it is less than 100,
send it to P1; otherwise, send it to P2.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mybyte;
P0=0xFF; //make P0 input port
while (1)
{
mybyte=P0; //get a byte from P0
if (mybyte<100)
P1=mybyte; //send it to P1
else
P2=mybyte; //send it to P2
}
}
Write an 8051 C program to toggle only bit P2.4 continuously without
disturbing the rest of the bits of P2.
Solution:
//Toggling an individual bit
#include <reg51.h>
sbit mybit=P2^4;
void main(void)
{
while (1)
{
mybit=1; //turn on P2.4
mybit=0; //turn off P2.4
}
}
Write an 8051 C program to monitor bit P1.5. If it is high, send 55H to P0; otherwise, send
AAH to P2.
Solution:
#include <reg51.h>
sbit mybit=P1^5;
void main(void)
{
mybit=1; //make mybit an input
while (1)
{
if (mybit==1)
P0=0x55;
else
P2=0xAA;
}
}
Logical Operation
#include <reg51.h>
void main(void)
{
P0=0x35 & 0x0F; //ANDing
P1=0x04 | 0x68; //ORing
P2=0x54 ^ 0x78; //XORing
P0=~0x55; //inverting
P1=0x9A >> 3; //shifting right 3
P2=0x77 >> 4; //shifting right 4
P0=0x6 << 4; //shifting left 4
}
Write an 8051 C program to toggle all the bits of P0 and Write an 8051 C program to get bit P1.0 and send it to P2.7
P2 continuously with a 250 ms delay. Using the after inverting it.
inverting and Ex-OR operators, respectively. Solution:
Solution: #include <reg51.h>
#include <reg51.h> sbit inbit=P1^0;
void MSDelay(unsigned int); sbit outbit=P2^7;
void main(void) bit membit;
{ inbit=1;
P0=0x55; Void main(void)
P2=0x55; {
while (1) while (1)
{ {
P0=~P0; membit=inbit; //get a bit from P1.0
P2=P2^0xFF; outbit=~membit; //invert it and send
MSDelay(250); //it to P2.7
} }
} }
switch (z)
Write an 8051 C program to read the P1.0 and P1.1 {
bits and issue an ASCII character to P0 according to case(0):
the following table. {
P1.1 P1.0 P0=‘0’;
0 0 send ‘0’ to P0 break;
0 1 send ‘1’ to P0 }
1 0 send ‘2’ to P0 case(1):
1 1 send ‘3’ to P0 {
Solution: P0=‘1’;
#include <reg51.h> break;
void main(void) }
{ case(2):
unsigned char z; {
z=P1; P0=‘2’;
z=z&0x3; break;
}
case(3):
{
P0=‘3’;
break;
}
}
}
Write an 8051 C program to convert packed BCD
0x29 to ASCII and display the bytes on P1 and P2.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char x,y,z;
unsigned char mybyte=0x29;
x=mybyte&0x0F;
P1=x|0x30;
y=mybyte&0xF0;
y=y>>4;
P2=y|0x30;
}
Write an 8051 C program to convert ASCII digits of ‘4’ and ‘7’ to
packed BCD and display them on P1.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char bcdbyte;
unsigned char w=‘4’; Hex value in w=0x34
unsigned char z=‘7’; Hex value in w=0x37
w=w&0x0F; w=0x04
w=w<<4; w=0x40
z=z&0x0F; z=0x07
bcdbyte=w|z; bcdbyte=0x47
P1=bcdbyte;
}
Write an 8051 C program to get bit P1.0 and send it to P2.7 after
inverting it.
Solution:
#include <reg51.h>
sbit inbit=P1^0;
sbit outbit=P2^7;
bit membit;
void main(void)
{
while (1)
{
membit=inbit; //get a bit from P1.0
outbit=~membit; //invert it and send it to P2.7
}
}
Write an 8051 C program to turn bit P1.5 on and off 50,000
times.
Solution:
sbit MYBIT=0x95;
void main(void)
{
unsigned int z;
for (z=0;z<50000;z++)
{
MYBIT=1;
MYBIT=0;
}
}
Write an 8051 C program to get the status of bit P1.0, save it,
and send it to P2.7 continuously.
Solution:
#include <reg51.h>
sbit inbit=P1^0;
sbit outbit=P2^7;
bit membit; //use bit to declare
//bit- addressable memory
void main(void)
{
while (1)
{
membit=inbit; //get a bit from P1.0
outbit=membit; //send it to P2.7
}
}
Write an 8051 C program to toggle all the bits of P0 and P2 continuously
with a 250 ms delay. Using the inverting and Ex-OR operators, respectively.
Solution:
#include <reg51.h>
void MSDelay(unsigned int);
void main(void)
{
P0=0x55;
P2=0x55;
while (1)
{
P0=~P0;
P2=P2^0xFF;
MSDelay(250);
}
}
Write an 8051 C program to get bit P1.0 and send it to P2.7 after
inverting it.
Solution:
#include <reg51.h>
sbit inbit=P1^0;
sbit outbit=P2^7;
bit membit;
void main(void)
{
while (1)
{
membit=inbit; //get a bit from P1.0
outbit=~membit; //invert it and send it to P2.7
}
}
Write an 8051 C program to calculate the checksum byte for the data 25H,
62H, 3FH, and 52H. Copy the byte to port2 and cumilitive sum to port1. Finally
copy the checksum to port1.

Solution:
#include <reg51.h>
void main(void)
{
unsigned char mydata[]={0x25,0x62,0x3F,0x52};
unsigned char sum=0;
unsigned char x;
unsigned char chksumbyte;
for (x=0;x<4;x++)
{
P2=mydata[x];
sum=sum+mydata[x];
P1=sum;
}
chksumbyte=~sum+1;
P1=chksumbyte;
}
Write an 8051 C program to perform the checksum operation to ensure data
integrity. If data is good, send ASCII character ‘G’ to P0. Otherwise send ‘B’ to P0.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char mydata[]={0x25,0x62,0x3F,0x52,0xE8};
unsigned char chksum=0;
unsigned char x;
for (x=0;x<5;x++)
chksum=chksum+mydata[x];
if (chksum==0)
P0=‘G’;
else
P0=‘B’;
}
Write an 8051 C program to convert 11111101 (FD hex) to
decimal and display the digits on P0, P1 and P2.
Solution:
#include <reg51.h>
void main(void)
{
unsigned char x,binbyte,d1,d2,d3;
binbyte=0xFD;
x=binbyte/10; x=253/10=25; reminder =3
d1=binbyte%10; d1=3 (reminder)
d2=x%10; d2=25%10=5
d3=x/10; d3=25/10 =2
P0=d1;
P1=d2;
P2=d3;
}
Write a C program to send out the value 44H serially one bit at a
time via P1.0. The LSB/ MSB should go out first.
Solution:
#include <reg51.h>
sbit P1b0=P1^0;
sbit regALSB=ACC^0; // sbit regALSB=ACC^7;
void main(void)
{
unsigned char conbyte=0x44;
unsigned char x;
ACC=conbyte;
for (x=0;x<8;x++)
{
P1b0=regALSB;
ACC=ACC>>1; // ACC=ACC<<1;
}
}
Write a C program to bring in a byte of data serially one bit at a
time via P1.0. The LSB should come in first.
Solution:
#include <reg51.h>
sbit P1b0=P1^0;
sbit ACCMSB=ACC^7;
bit membit;
void main(void)
{
unsigned char x;
for (x=0;x<8;x++)
{
membit=P1b0;
ACCMSB=membit;
ACC=ACC>>1;
}
P2=ACC;
}
Write an 8051 C program to toggle all the bits of port P1 continuously
with some delay in between. Use Timer 0, 16-bit mode to generate the
delay.
Solution:
#include <reg51.h> void T0Delay()
void T0Delay(void); {
void main(void) TMOD=0x01;
{ TL0=0x00;
while (1) TH0=0x35;
{
TR0=1;
P1=0x55;
T0Delay(); while (TF0==0);
P1=0xAA; TR0=0;
T0Delay(); TF0=0;
} }
}
A switch is connected to pin P1.7. Write an 8051 C program to monitor SW and create
the following frequencies on pin P1.5:SW=0: 500Hz; SW=1: 750Hz, use Timer 0, mode
1 for both of them.
void T0M1Delay(unsigned char c)
#include <reg51.h>
{
sbit mybit=P1^5;
TMOD=0x01;
sbit SW=P1^7;
if (c==0)
void T0M1Delay(unsigned char);
{
void main(void)
TL0=0x67;
{
TH0=0xFC;
SW=1;
}
while (1)
else
{
{
mybit=~mybit;
TL0=0x9A;
if (SW==0)
TH0=0xFD;
T0M1Delay(0);
}
else
TR0=1;
T0M1Delay(1);
while (TF0==0);
}
TR0=0;
}
TF0=0;
}
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)
{
SBUF=‘A’; //place value in buffer
while (TI==0);
TI=0;
}
}
Write an 8051 C program to transfer the message “YES” serially at 9600 baud, 8-bit data, 1 stop bit. Do
this continuously.
Solution:
#include <reg51.h>
void SerTx(unsigned char);
void main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFD; //9600 baud rate
SCON=0x50;
TR1=1; //start timer
while (1)
{
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
} void SerTx(unsigned char x)
} {
SBUF=x; //place value in buffer
while (TI==0); //wait until transmitted
TI=0;
}
Program the 8051 in C 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:
#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
{
While (RI==0); //wait to receive
mybyte=SBUF; //save value
P1=mybyte; //write value to port
RI=0;
}
}
Write a C program using interrupts to do the following: (a) Receive data serially and send it to P0
(b) Read port P1, transmit data serially, and give a copy to P2 (c) Make timer 0 generate a square wave of 5
kHz frequency on P0.1. Assume that XTAL = 11.0592 MHz. Set the baud rate at 4800.
#include <reg51.h> void main()
sbit WAVE =P0^1; {
void timer0() interrupt 1 unsigned char x;
{ P1=0xFF; //make P1 an input
WAVE=~WAVE; //toggle pin TMOD=0x22;
} TH1=0xF6; //4800 baud rate
void serial0() interrupt 4 SCON=0x50;
{ TH0=0xA4; //5 kHz has T=200us
if (TI==1) IE=0x92; //enable interrupts
{ TR1=1; //start timer 1
TI=0; //clear interrupt TR0=1; //start timer 0
} while (1)
else {
{ x=P1; //read value from pins
P0=SBUF; //put value on pins SBUF=x; //put value in buffer
RI=0; //clear interrupt P2=x; //write value to pins
} }
} }
Write a C program that continuously gets a single bit of data from P1.7 and sends it to P1.0, while
simultaneously creating a square wave of 200 s period on pin P2.5. Use Timer 0 to create the square wave.
Assume that XTAL = 11.0592 MHz.
Solution:
We will use timer 0 mode 2 (auto-reload). One half of the period is 100 s. 100/1.085 s = 92, and TH0 = 256 -
92 = 164 or A4H
#include <reg51.h>
sbit SW =P1^7;
sbit IND =P1^0;
sbit WAVE =P2^5;
void timer0(void) interrupt 1
{
WAVE=~WAVE; //toggle pin
}
void main()
{
SW=1; //make switch input
TMOD=0x02;
TH0=0xA4; //TH0=-92
IE=0x82; //enable interrupt for timer 0
while (1) {
IND=SW; //send switch to LED
}
}
Write a C program using interrupts to do the following: (a) Receive data serially and send it to
P0; (b) Read port P1, transmit data serially, and give a copy to P2 (c) Make timer 0 generate a
square wave of 5 kHz frequency on P0.1 Assume that XTAL = 11.0592 MHz. Set the baud rate
at 4800.
void main() {
#include <reg51.h> unsigned char x;
sbit WAVE =P0^1; P1=0xFF; //make P1 an input
void timer0() interrupt 1 { TMOD=0x22;
WAVE=~WAVE; //toggle pin TH1=0xF6; //4800 baud rate
} SCON=0x50;
void serial0() interrupt 4 { TH0=0xA4; //5 kHz has T=200us
if (TI==1) { IE=0x92; //enable interrupts
TI=0; //clear interrupt TR1=1; //start timer 1
} TR0=1; //start timer 0
else { while (1) {
P0=SBUF; //put value on pins x=P1; //read value from pins
RI=0; //clear interrupt SBUF=x; //put value in buffer
} P2=x; //write value to pins
} }
}
Write a C program using interrupts to do the following: (a) Generate a 10 KHz frequency on P2.1 using T0 8-
bit auto-reload (b) Use timer 1 as an event counter to count up a 1-Hz pulse and display it on P0. The pulse is
connected to EX1. Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.

Solution:
#include <reg51.h> void main() {
sbit WAVE =P2^1; cnt=0; //set counter to 0
Unsigned char cnt; TMOD=0x42;
void timer0() interrupt 1 TH0=0x-46; //10 KHz
{ IE=0x86; //enable interrupts
WAVE=~WAVE; //toggle pin TR0=1; //start timer 0
} while (1);
void timer1() interrupt 3 //wait until interrupted
{ }
cnt++; //increment counter
P0=cnt; //display value on
pins
}

You might also like