MCS® 51 Microcontroller Family User`s Manual

MCS® 51 Microcontroller Family User`s Manual

[email protected] MICROCONTROLLER

FAMILY USER’S MANUAL

ORDER NO.: 272383-002

FEBRUARY 1994

Intel Corporation makes no warrsnfy for the uee of ite products and assumes no responsibility for any ewors which may appear in this document nor does it make a commitment to update the information contained herein.

Intel retains the right to make changes to these specifications at any time, without notk

Contact your local Intel sales office or your distributor to obtain the latest speoificationa before placing your product order.

MDS is an ordering code only and is not usad ae a product name or trademark of Intel Corporation.

Intel Corporation and Intel’s FASTPATH are not affiliated with Kinetics, a division of Excelan, Inc. or its FASTPATH trademark or products,

Additional copies of this document or other Intel literature maybe obtained from:

Intel Corporation

Literature Selas

P.O. Box 7S41

Mt. Prospect, IL 6005S-7641 or call 1-800-879-4683 c-INTELCORPORATION, 1093

MCS” 51 CONTENTS

PAGE

MICROCONTROLLER

FAMILY

MCS 51 Family of Microcontrollers

Archkedural Ovewiew .............................l-l

USER’S MANUAL

CHAPTER 2

MCS 51 Programmer’s Guide and

Instruction Set ..........................................2-l

CHAPTER 3

8051, 8052 and 80C51 Hardware

Description ...............................................3.l

CHAPTER 4

8XC52J54/58 Hardware Description ............4-1

CHAPTER 5

8XC51 FX Hardware Description .................5-1

CHAPTER 6

87C51GB Hardware Description .................8-1

CHAPTER 7

83CI 52 Hardware Description ....................7-1

[email protected] 51 Family of

Microcontrollers

Architectural Overview

1

[email protected] FAMILY OF CONTENTS

MICROCONTROLLERS

PAGE

INTRODUCTION .........................................1-3

ARCHITECTURAL

.....”.....’.......”.....-...-..........I-5

OVERVIEW

M;~$&:RGA-~oN INMc-

51

.................................................1-6

Lo ical Separation of Program and Data

h emoy ....................................................l+

Program Memo~ .........................................l-7

Data Memory ...............................................1 -8

THE MC951 INSTRUCTION SET .............1 -9

Program Status Word ..................................1 -9

Addressing Modes .....................................l-l O

Arithmetic Instructions ...............................1-10

Logical lnstrudions ....................................l.l2

Data Tran#ers ...........................................l.l2

Boolean Instructions

..................................1-14

Jump Instructions ......................................1-16

CPU TIMING .............................................l-l7

Machine Cycles .........................................1-18

Interrupt Structure ......................................l.2O

ADDITIONAL REFERENCES ...................1 -22

1-1

w

ir&L

[email protected]

ARCHITECTURAL OVERVIEW

INTRODUCTION

The

8051 is

the original member of the

MCW-51

family, and is the core for allMCS-51 devices. The features of the

8051 core are -

8-bit

CPU optimized for control applications

Extensive Boolean processing (Single-blt logic) capabtilties

64K Program Memory address space

64K Data Memory address space

4K bytes of on-chip Program Memory

128 bytesof on-chip Data RAM

32 bidirectional and individually addressable 1/0 lines

Two 16-bit timer/counters

Full duplex UART

6-source/5-vector interrupt structure with two priority levels

On-chip clock oscillator

The basic architectural structure of this 8051 core is shown in Figure L

EXTERNAL

I I

COUNTER

INPUTS

II

BUS

CONTROL

11

H

4 1/0 PORTS

Po P2

AODRESS/DATA

PI P3

Figure 1. Block Diagram of the 8051 Core

H

PORT

TXO

SERIAL

Q

RXD

270251-1

1-3

intd.

[email protected] ARCHITECTURAL OVERVIEW

1-4

i~.

[email protected]’-5l ARCHITECTURAL OVERVIEW

1-5

i~.

[email protected]

ARCHITECTURAL OVERVIEW

I

8

0

0

9

0

0

8

0

,

I

I

* -----------

8

1

1

1

I

1

I o

1

1

1

1

PROORAMMrhtosv

(REM ONLY)

--------------

FFFFw

T -

EXTERNAL

1

0

@

*

I

:

#

o

0

:

-

---

G=o

2STERNAL

--------

0000

-------m.1

IN7ERNAL

-.!

$ s

1

1

1

1

I

1

1

1

1

I

,

I

I

B

1

1

1

1

1

1

1

1

1

:

:

I

*

0

9

I

I

OATAMEMORY

(RW/WRlT2)

I

I

I

I

8

-----------------------t

8

I

1

0

9

8

0 t

#

#

8

: o

9

8

,

I

1

: FfH: ------

0

9

8

1

0:

9, e,

9

I 00

1

--------

EXIERNALm

IN7ERNM

---------

-

0000

..-

J:

-.

-.-:

. . . . .

I

8

8

I

0

I

0

I

*

I

#

I

I

I

I

I

I

1

I

I

:

1

I

1

1

0

1

1

I

1

1% tiR

270251-2

Figure 2. MCW’-51 Memory Structure

CHMOS Devices

Functionally, the CHMOS devices (designated with

“C” in the middle of the device name) me all

fiuy

compatible with the 8051, but being CMOS, draw less current than an HMOS counterpart. To further exploit the power savings available in CMOS circuitry, two reduced power modes are added

Software-invoked Idle Mode, during which the CPU is turned off while the RAM and other on-chip peripherals continue operating. In this mode, current draw is reduced to

about 15%

of the current drawn when the device is fully active.

Software-invoked Power Down Mode, during which all on-chip activities are suspended. The on-chip

RAM continues to hold its data. In this mode the device typically draws less than 10 pA.

Although the 80C51BH is functionally compatible with its HMOS counterpart, s~lc differeneea between the two types of devices must be considered in the design of an application circuit if one

wiahea

to ensure complete interchangeability between the HMOS and CHMOS devices. These considerations are discussed in the Ap plieation Note AP-252, “Designing with the

80C5lBH.

For more information on the individual devices and features listed in Table 1, refer to the Hardware De scriptions and Data Sheets of the specific device.

1-6

MEMORY ORGANIZATION

[email protected] DEVICES

IN

Logical Separation of Program and

Data Memory

AU MCS-51 devices have separate address spacea for

Program and Data Memory, as shown in Figure 2. The logical separation of Program and Data Memory allows the Data Memory to be acceased by 8-bit addressea, which can be more quickly stored and manipulated by an 8-bit CPU. Nevertheless, ld-bh Data Memory addresses can also be generated through the DPTR register.

Program Memory can only be read, not written to.

There can be up to 64K bytes of Program Memory. In the ROM and EPROM versions of these devices the loweat 4K, 8K or 16K bytes of Program Memory are provided on-chip. Refer to Table 1 for the amount of on-chip ROM (or EPROM) on each device. In the

ROMleas versions all Program Memory is external.

The read strobe for external Program Memory is the signal PSEN @rogram Store Enable).

[email protected] ARCHITECTURAL OVERVIEW

intel.

Data Memory occupies a separate addrexs space from

%OgrCt122 hkznory.

Up to

64K

bytes of exterttd RAM can be addreased in the externrd Data Memo~.

The CPU generatea read and write signals RD and

~, as needed during external Data Memory accesses.

External Program Memory and external Data Memory

~~ combined if-desired by applying the ~ ~d

PSEN signals to the inputs of an AND gate and using the output of the gate as the read strobe to the external

Program/Data memory.

ProgramMemory

Figure 3 shows a map of the lower part of the Program

Memory. After reset, the CPU begins execution from location OWOH.

AS shown in [email protected] 3, each interrupt is

assigned

a tixed location in Program Memory. The interrupt causes the

CPU to jump to that location, where it commences execution of the serviee routine. External Interrupt O, for example, is assigned to location 0003H. If External Interrupt O is going to & used, its service routine must begin at location 0003H. If the interrupt is not going to be used, its service location is available as general purpose Program Memory.

The lowest 4K (or SK or 16K) bytes of Program Memory can be either in the on-chip ROM or in an external

ROM. This selection is made by strapping the ~ (External Access) pin to either VCC or Vss.

In the 4K byte ROM devices, if the= pin is strapped to VcC, then program fetches to addresses 0000H through OFFFH are directed to the internal ROM. Program fetches to addresses 1000H through FFFFH are directed to external ROM.

In the SK byte ROM devices, = = Vcc selects addresses (XtOOHthrough lFFFH to be internal, and addresses 2000H through F’FFFH to be external.

In the 16K byte ROM devices, = = VCC selects addresses 0000H through 3FFFH to be internal, and addresses 4000H through FFFFH to be external.

If the ~ pin is strapped to Vss, then all program fetches are directed to external ROM. The ROMleas parts must have this pin externally strapped to VSS to enable them to execute properly.

The read strobe to externally: PSEN, is used for all external oro.cram fetches. PSEN LSnot activated for in-

INTSRRUPT

LOCATIONS

R2S~

i

..-.

&

(O033H)

002EH

002SH

00IBH

0013H II

000SH

0003H

0000H

Ssvrm

270251-3

Figure 3. MCW’-51 Program Memory

The interrupt aeMce locations are spaced at 8-byte intervak 0U03H for External Interrupt O, 000BH for

Tmer O, 0013H for External Interrupt 1, 00IBH for

Timer 1, etc. If an interrupt service routine is short enough (as is often the case in control applications), it can reside entirely within

that

8-byte interval. Longer service routinea can use a jump instruction to skip over subsequent interrupt locations, if other interrupts are in use.

‘s

1 m%

Po m l==

ALE

a’s ‘z~

LArcn

EPROM

INSTR.

270251-4

Figure 4. Executing from External

Program Memory

The hardware configuration for external program execution is shown in Figure 4. Note that 16 I/O lines

(Ports O and 2) are dedicated to bus fictions during external Program Memory f~hes.

Port O(PO in Figure

4) servex as a multiplexed address/data bus. It emits the low byte of the Program Counter (PCL) as an address, snd then goes into a float state awaiting the arrival of the code byte from the Program Memory. During the time that the low byte of the Program Counter is valid on PO, the signal ALE (Address Latch Enable) clocks this byte into an address latch. Meanwhile, Port

2 (P2 in Figure 4) emits the high byte of the Program

Countex (WI-I). Then ~ strobex the EPROM and the code byte is read into the microcontroller.

1-7

[email protected] ARCHITECTURAL OVERVIEW

Program Memory addresses are always 16 bits wide, even though the aotual amount of Program Memory used ntSy be kSS than 64K bytes. External prOq exeoutiorssacrifices two of the 8-bit ports, PO and P2, to the fisnction of addressing the Program Memory.

Data Memory

The

right nal Dats Memory spaces available to the MCS-51 user.

[email protected] 5 shows a hardware configuration for accessing up to 2K bytes of external RAM. The CPU in this ease is executing from internal ROM. Port O serves as a multiplexed address/data bus to the RAM, and 3 lines of Port 2 are bein~d to page the RAM. The CPU generates = and WR signals as needed during exter-

ial

WM ameases.

-

Internal Data Memory is mapped in Figure 6. The memory space is shown divided into three bloeka, which are generally referred to as the Lower 128, the

Upper 128, and SFR space.

Internal Data Memory addresses are always one byte

Wid%which implies an address space of only 256 bytes.

However, the addressing modes for intemssl RAM ean in fact seeommodate 384 bytes, using a simple trick.

Direct addresses higher than 7FH awes one memory space, and indirect addresses higher than 7FH access a different memory space. Thus Figure 6 shows the Upper 128 and SFR

spaceoccupyingthe ssmeblockof addrq

80H throu~ FFH, slthoud they are physi-

cally

separateentities;

1’

I

I

270251-5

Figure

5.

Accessing External Data Memory.

If the Program Memory is Internal, the Other

Bits of P2 are Available as 1/0.

There ean be up to 64K bytea of external Data Memo-

ry.

External Data Memory addresses can be either 1 or

2 bytes wide. One-byte addresses are often used in cxmjunction with one or more other 1/0 lines to page the

R4M, as shown in Figure 5. Two-byte addresws ears atso be used, irz which case the high address byte is emitted

at

Port 2.

BANK

SELECT

BRS IN

‘1 eo{o

Ill

“{

‘0{ 10H

0’{ OBH lSH

20H n

7FH

2FH

1

SN-ACORESSASLSSPACE

(S~ A~ESSES O-7F)

1FH

17H

OFH

07H

4 SANKSOF

8 REGIS7SRS

RO-R7

RESETVALUEOF

S7ACKPOIN7ER

270251-7

Figure 7. The Lower 128 Bytes of internal RAM

The

Imwer

128

bytes of W are present in all

MCS-51 devices as mapped in [email protected] 7. The lowest 32 bytes are grouped into 4 banks of 8 registers. Program instructions call out these registers as RO through R7.

Two bits in the Program Status Word (PSW) seleet which register bank is in use. This allows more effieient use of code space, since register instructions are shorter than instructions that use direet addreasiig.

~:..

.-...

-

FFH

UPP~

128

‘m

LOWER

, AC=IELE

, SV INDIREC7

SDH9

ONLY

ACCESSIBLE

SY 01REC7

ANO INC+REC7

ACCESSIBLE

BV OIRECT

: AtORESSING AODRSSSING o AGGRESSING

W

80H

1

‘E~m CONTROLems

TIMER

RE—

STACKiolN7ER

ACCUMULATOR

(’nC.)

270251-6

Figure 6. Internal Data Memory

FFH

80H

I

NO SIT-AOORSSSABLE

SPACES

AVAIUBLE AS S7ACK

SPACEIN DEVICESWMI

256 BWES RAM

Figure 6. The Upper 128 Bytes of Internal RAM

270251-8

I-6

in~.

[email protected] ARCHITECTURAL OVERVIEW

CARRYFLAG RECEIVESCMi/fmw;

FROU BIT 1 Of ALU OPERANOS

1

CTIAC]

FOIRSIIRBO[ b a a A

OVI

*

A

I

P

I

KWO

PARllY

ACCLWUIATORSS7

~ NARoWARCTO 1 IF IT CONTAINS

AN 000 NUMBEROF 1S, OTHERWISE

171SRESE7TO0

— Psw 1

USER OEFINABLEFUG

Psw6—

AUXILIARYCARRYFLAG RECEIVES

CARRYOUT FROM B171 OF

AOOMON OPERANOS nw5

GENERALPURPOSES7ATUS FLAG

REGtS7ER t

Psw 2

OVERFLOWFIAO SET BY

ARITIMCWOPERAl!ONS

Psw3

BANK

270251-10

-.

.. . . . . .. .

.

. . .

. . .

.

.

---------

Figure 1u. Psw (Progrsm ssssus worn) Register m mc5w-51 t2evtces

The next 16 bytea above the register bankBform a block of bit-addressable memory apace. The MCS-51 instruction set includes a wide seleetion of single-blt instructions, and the 128 bits in this area can be directly addressed by these irsstmctions. The bit addreascs in this area are W)H through 7FH.

!%teers addresses in SFR mace are both byte. and bit.

addressable. The blt-addre&able SFRS are ‘those whose address ends in 000B. The bit addresses in this ares are

80H

throUgh FFH.

All of the bytes in the LQwer 128 can be accessed by either direct or indirect addressing. The Upper 128

(Figure 8) can only be accessed by indirect addressing.

The Upper 128 bytes of RAM are not implemented in the 8051, but me in the devices with 256 bytea of RAM.

(Se Table 1).

Figure 9 gives a brief look at the Special Funotion Register (SFR) space. SFRS include the Port latchea, timers, pe2iphA controls, etc. l%ese registers can only&

-seal by dmect addressing. In general, all MCS-51 microcontrollers have the same SFRB as the 8051, and at the same addresses in SFR space. However, enhancements to the 8051 have additional SFRB that are not present in the 8051, nor perhaps in other proliferations of the family.

THE [email protected] INSTRUCTION SET

All

members of the MCS-51 family execute the same instruction set. The MCS-51 instruction set is optimized for 8-bit control applications. It provides a variety of fast addressing modes for accessing the internal

MM to facilitate byte operations on small data structures. The instruction sd provides extensive support for one-bit variables as a separate data t% allowing direct blt manipulation in control and logic systems that require Boolean prmessirsg.

An overview of the MCS-51 instruction set is prrsented below, with a brief description of how certain instructions might be used. References to “the assembler” in this discussion are to Intel’sMCS-51 Macro Assembler,

ASM51. More detailed information on the instruction set can be found in the MCS-51 Macro Assembler User’s Guide (Grder No. 9W3937 for 1S1SSystems, Grder

No. 122752 for DOS Systems).

“u

EOH

RE~MAPPSO POR7S

80H m

PORT .3

AOH

90H

Porn 2

POR7 1

B

J-A--I

AOORESSES7NAT END IN

OH OR EN ARCALSO

B~-AOORESSABLE

-POR7 PINS

-ACCUMULATOR

-Psw

(E7c.)

Program Status Word

The Program Status Word (PSW) contains several status bits that reflect the current state of the CPU. The

PSW, shown in Figure 10, resides in SFR space. It contains the Csrry bi~ the Auxdiary Carry (for BCD operations), the two register bank select bits, the Gvesflow flag, a Parity bit, and two userdefinable status tlags.

The Carry bit, other than serving the functions of a

Carry bit in arithmetic operations, also sesws as the

“Accumulator” for a number of Boolean operations.

270251-9

Figure 9. SFR Spsce

1-9

[email protected]

ARCHITECTURAL OVERVIEW

The bits RSOand RSl are wed to select one of the four register banks shown in Figure 7. A number of instructions refer to these RAM locations as RO through R7.

The selection of which of the four banks is being referred to is made on the basis of the bits RSO and RS1 at execution time.

The Parity bit reflects the number of 1s in the Accumulator P = 1 if the Accumulator contains an odd number of 1s, and P = O if the Accumulator contains an even number of 1s. Thus

the

number of 1s in the Accumulator plus P is always even.

Two bits in the PSW are uncommitted and maybe used as general purpose status flags.

IMMEDIATE CONSTANTS

The value of

a constant can follow the opcode in Program Memory. For example,

MOV A, # 100 loads the Accumulator with the decimal number 100.

The same number could be specified in hex digitz as

64H.

Addressing Modes

The

addressing modes in the MCS-51 instruction set are as follows

DIRECT ADDRESSING

In direct addressing the operand is specitied by an 8-bit addreas field in the instruction. Only internal Data

RAM and SFRS can be directly addressed.

INDEXED ADDRESSING only

Program Memory can be amessed with indexed addressing, and it can only be read. This addressing mode is intended for reading look-up tables in Program

Memory. A Id-bit base register (either DPTR or the

Program Counter) points to the base of the table, and the Accumulator is setup with the table entry number.

The address of the table entry in Program Memory is formed by adding the Accumulator data to the base pointer.

Another type of indexed addreaaing is used in the “case jump” instruction. In this case the destination address of a jump instruction is computed as the sum of the base pointer and the Accumulator &ta.

INDIRECT ADDRESSING

In indirect addressing the instruction specifies a register which contains the address of the operand. Both internal and external RAM can be indirectly addressed.

The address register for 8-bit addresses can be RO or

RI of the selected register bank, or the Stack Pointer.

The addreas register for id-bit addresses can only be the id-bit “data pointer” register, DPTR.

REGISTER INSTRUCTIONS

The

register banks, containing registers RO through R7, can be accemed by certain instructions which carry a

3-bit register specification within the opcode of the instruction. Instructions that access the registers this way are code efficient, since this mode elirninatez an addreas byte. When the instruction is executedj one of the eight registers in the selected bank is amessed. One of four banks is selected at execution time by the two bank select bits in the PSW.

REGISTER-SPECIFIC INSTRUCTIONS

Some instructions are specific to a certain register. For example, some instructions always operate on the Accumulator, or Data Pointer, etc., so no address byte is needed to point to it. The opcode itself does structions that refer to the Accurrdator as A assemble as accumulator-specific opcmdes.

1-1o

Arithmetic Instructions

The

menu of arithmetic instructions is listed in Table 2.

The table indicates the addressing modes that can be used with each instruction to access the <byte> operand. For example, the ADD A, <byte> instruction can be written as

ADD

ADD

ADD

ADD

A,7FH

A,@RO (indirect addressing)

A,R7 (register addressing)

A, # 127 (iediate constant)

The execution times listed in Table 2 assume a 12 MHz clock frequency. All of the arithmetic instructions execute in 1 ps except the INC DPTR instruction, which takes 2 W, snd the Multiply and Divide instructions, which take 4 ps.

Note that any byte in the internal Data Memory space can be incremented or decremented without going through the Accumulator.

One of the INC instructions operates on the Id-bit

Data Pointer. The Data Pointer is used to generate

16-bit addresses for external memory, w being able to increment it in one 16-bit operation is a usefirl feature.

The MUL AB instruction multiplies the Accumulator by the data in the B register and puts the Id-bit product into the concatenated B and Accumulator registers.

inl#

[email protected] ARCHITECTURAL OVERVIEW

Mnemonic

ADD A,

<byte>

I ADDOA, <byte>

SUBB A, <byte>

INC

A

I INC . <byte>

I lhJC DPTR

I DEC A

DEC

MUL

DIV

I

IDAA

<byte>

AB

AB

Table 2 A Ust of the [email protected] Arithmetic Instructions

Operation

A = A + <byte>

I A= A+< byte>+C

A= A–<byte>-C

I A=A+l

I

<byte> =<byte>+l

I DPTR = DpTR + 1

I A= A-l

<byte> = <byte>

B.A=Bx A

I A = Int [A/B]

B = MOd [A/Bl

I Decimal Adjust

– 1

I

I

I

I

I

I

Addressing Modes

Dk I Ind

x x

Rq

x

X

x

X

I

I

X

X

I

I

X

x x

Accumulator onlv

X

I

I

x

Data Pointer only

I

Accumulator only x x

ACC and

B only

ACC and

B only

Accumulatoronly lmm

x

X

x

Execution

Time (@

I

Ill

]

I

I

11-1

121

Ill

1

4

4

1

1

1

1

The DIV AB instruction divides the Accumulator by the data in the B register and leevea the 8-bit quotient in the Accumulator, and the 8-bit remainder in the B register.

eompletcs the shift in 4 p.s and leaves the B register holding the bits that were shifted out.

Oddly enough, DIV AB finds lees use in arithmetic

“divide” routines than in radix eonversions and pro-

~ble shift operstioILs. k example of the use of

DIV AB in a radix conversion will be given later. In s~ operations, dividing a number by 2n shifts its n bits to the right. Using DIV AS to perform the division

The DA A instruction is for BCD arithmetic operations. In BCD arithmetic, ADD and ADDC instructions should always be followed by a DA A operation, to ensure that the

red is also in

BCD. Note that DA

A will not convert a binary number to BCD. The DA

A operation produces a meaningfid

result only as the

second step in the addition of two BCD bytes.

Table

3.

A Uet

of the [email protected] Instructions

I

Mnemonic

I

Operation

.AND. <byte>

ANL A,< byte> A = A

ANL

ANL

ORL

ORL

ORL

XRL

<byte>,A

<bvte>, #data

A,< byte>

<bvte>,A

<byte>, #data

A,< byte>

<byte>

<byte>

= <byte>

= <byte>

.AND. A

.AND.

#data

I

A =

A.OR.

<byte>

<byte> = <byte> .OR. A

XRL <byte>,A

XRL <byte>, #data

CRL A

CPL A

IRL A

RLC A

RR A

RRC A

I

I <byte> = <byte> .OR. #data

A = A .XOR. <byte>

<byte> = <byte> .XOR. A

<byte> = <byte> .XOR.

#data

A=OOH

A =

.NOT.

A

I Rotate ACC Left 1 bit

I Rotate Left through Csrry

Rotate ACC Right

1 bit

Rotate Right through Carry

SWAP A Swap Nibbles in A

Dir

x x

Addressing Modes

Ind I Reg I

Imm

x x x x

I

I

I X1X1X1X x x

X1X1X x

I

I X

I

Accumulator only x

Accumulator

only

Accumulator onlv

Accumulator only

Accumulator only

Accumulator only

Accumulator

onlv

I

I

I

Ill

Execution

Time (ps)

2

1

1

2

1

1

1

1

2

1

1

1

1

1

1

I

I

I

1-11

irrtel.

[email protected] ARCHITECTURAL OVERVIEW

Logical Instructions

Table 3 shows the list ofMCS-51 logical instructions.

The instructions that perform Boolean operations

(AND, OIL Exclusive OIL NOT) on bytes perform the operation on a bit-by-bit bssis. That is, if the Aecumu-

Iator contains 001101OIB and <byte> contains

O1OIOOIIB,then

The SWAP A instruction interchanges the high and low nibbles within the Accumulator. This is a useful operation in BCD manipulations. For exampie+ if the

Accumulator contains a binary number which is known to be leas thsn IQ it can be qnickly converted to BCD by the following code:

ANL

A, <byte>

MOV B,# 10

DIV AB

SWAP A

ADD A,B will leave the Accumulator holding OOO1OOOIB.

The addrcasing modes that can be used to access the

<byte> operand are

listedin

Table 3. Thus, the ANL

A, <byte> instruction may take any of the forms

Dividing the number by 10 leaves the tens digit in the low nibble of the Accumulator, and the ones digit in the

B register. The SWAP and ADD instructions move the tens digit to the high nibble of the Accumulator, and the onea digit to the low nibble.

ANL

ANL

ANL

ANL

A,7FH

A,@Rl

A,R6

A, # 53H

(direct addressing)

(indirect addressing)

(register addressing)

(immediate constant)

Data Transfers

AU of the logical instructions that are Accumulatorspecflc execute in lps (using a 12 MHz clock). The othem take 2 ps.

Note that Boolean operations can be performed on any byte in the lower 128 internal Data Memory space or the SFR space using direct addressing, without having to use the Accumulator. The XRL <byte >, #data instruction, for example offets a quick and easy way to invert port bits, as in

XRL Pl,#oFFH

INTERNAL RAM

Table 4 shows the menu of instructions that are available for moving data around within the internal memory spaces, and the addressing modes that can be used with each one. Wkh a 12 MHz clock, all of these instructions execute in either 1 or 2 ps.

The MOV < dest >, < src > instruction allows dats to be transferred between any two internal RAM or SFR lwations without going through the Accumulator. Remember the Upper 128 byes of data RAM can be acwased only by indirect addressing, and SFR space only by direct addressing.

If the operation is in response to an interrupt, not using the Accumulator saves the time and effort to stack it in the service routine.

The Rotate instructions (3U & RLC A, etc.) shift the

Aeeurtmlator 1 bit to the MI or right. For a left rotation, the MSB rolls into the LSB position. For a right rotation, the LSB rolls into the MSB position.

Note that in all MCS-51 devices, the stack resides in on-chip RAM, and grows upwards. The PUSH instruction first increments the Stack Pointer (SP), then copies the byte into the stack. PUSH and POP use only dkcct addressing to identify the byte being

saved or

restored,

Table 4. A List of the [email protected] Data Tranafer Instructions that Access Internal Data Memory Space

Mnemonic

MOV A, <src>

MOV <cleat> ,A

MOV <dest>, <src>

MOV DPTR,#data16

PUSH

<WC>

POP

<dest>

XCH A, <byte>

XCHD A,@Ri

Operation

A = <src>

<dest> = A

<dest> = <src>

DPTR = 16-bit immediate constant.

INC SP: MOV “@’SP’, <src>

MOV <dest>, “@SP”: DEC SP

ACC and <byte> exchange data

ACC and @Riexchange low nibbles x x x

Dir

x x x

Addressing Modes

Ind

x x x

Reg

x x x

Imm

x x x x x x

Execution

Time (ps)

2

2

2

1

1

1

1

2

1-12

[email protected] ARCHITECTURAL

OVERVIEW

i~o

but the stack itself is accessed by indirect addressing using the SP register. This means the stack can go into the Upper 128, if they are implemented, but not into

SFR space.

Atler the routine has been executed, the Accumulator contains the two digits that were shitled out on the right. Doing the routine with direct MOVS uses 14 code bytes and 9 ps of execution time (assuming a 12 MHs clock). The same operation with XCHS uses less code and executes almost twice as fast.

In devices that do not implement the Upper 128, if the

SP points to the Upper 128, PUSHed bytes are lost, and

POPped bytes are indeterminate.

The Data Transfer instructions include a id-bit MOV that can be used to initialise the Data Pointer (DPTR) for look-up tables in Program Memory, or for Id-bit external Data Memory accesw.

To right-shift by an odd number of digits, a one-digit shift must be executed. Figure 12 shows a sample of code that will right-shii a BCD number one digi~ using the XCHD instruction. Again, the contents of the registers holding the number and of the Accumulator

are shownalongsideeach

instruction.

MOV Rl, #2EH

MOV RO,#2DH m

The XCH A, <byte> instruction causes the Amulator snd addressed byte to exchsnge data. The

XCHD

A, @Ri instruction is similar, but only the low nibbles are involved in the exchange.

loop for R1 = 2EH

To see how XCH and XCHD can be used to fatitate data manipulations, consider first the problem of shit%ing an 8digit BCD number two digits to the right. Figure 11 shows how this can be done using direct MOVS, and for comparison how it can be done using XCH instructions. To aid in understanding how the code works, the contents of the registers that are holding the

BCD number and the content of the Accumulator are shown alongside each instruction to indicate their status after the instruction has been executed.

.00P

MOV A,@Rl

XCHD A,@RO

SWAP A

MOV @Rl,A

DEC

DEC

RI

RO

CJNE Rl,#2AH,LOOP

Imp for RI = 2DH loop for R1 = 2CH: ioop for RI = 2BH:

00 12 34 56 78 76

00 12 34 56 78 76

00 12 34 58 78 67

00 12 34 58 67 67

00 12 34 58 67 67

00 12 34 56 67 67

00 12 36 45 67 45

00 18 23 45 67 23

0s

01 22

45 67 01

CLR A 06

01 23

45 67 00

~

MOV

MOV 2EH2DH % ;;

MOV

A,2EH

2CH:2BH 00 12

:

(a) Using direct MOVS 14 bytes, 9 ps

% ~

XCH A,2AH 00 01 23 45 67 06

Figure 12. Shifting a SCD Number

One Digit to the Right

First, pointers RI and RO are setup to point to the two bytea containing the last four BCD digits. Then a loop is executed which leaves the last byte, location 2EIL gm

(b) Using XCHS 9 bytes, 5 ps

Figure 11. Shifting a

. .

BCD

Number

holding the last two digits of the shifted number. The pointers are decrernented, and the loop is repeated for location 2DH. The CJNE instruction (Compare and

Jump if Not Equal) is a loop control that will be described later.

The loop is executed from LOOP to CJNE for R1 =

2EH, 2DH, 2CH and 2BH. At that point the digit that was originally shii out on the right has propagated

Two Dlgite to the Right

to location 2AH. Siice that location should be left with

0s, the lost digit is moved to the Accumulator.

1-13

[email protected]

ARCHITECTURAL OVERVIEW

EXTERNAL RAM

Table 5 shows a list of the Data Transfer inatmctions that acceas external Data Memory. Only indirect ad-

&easing can be used. The choice is whether to use a one-byte address, @M where Ri can be either RO or

RI of the selected register bank, or a two-byte address,

@DPTR. The disadvantage to using 16-bit addresses if only a few K

bytesof externalRAMare involvedis that

16-bit addresses use alf 8 bits of Port 2 as addreas bus. On the other hand, S-bit addresses allow one to address a few K bytes of RAM, as shown in Figure 5, without having to sacrifice all of Port 2.

Alf of these instructions execute in 2 pa, with a

12 MHz clock.

Tabfe 5. A

List of the [email protected] Data

Trsnafer Instructions that Accees

Extarnsl Data Memory Spaoe

Address

Width

8 b~

Mnemonic

MOVX A,@’Ri

Operation

Execution

Time (*)

~

8 bb

‘6 bns

16 bfia

MOVX @Ri,A

‘ovx “@DpTR

‘ovx ‘DmR’A

Read external

RAM @Ri

Write external

RAM @Ri

Read external

RAM @DPTR

Writa exlemal

RAM @DPTR

2

2

2

Note that in all external Data RAM acaases, the

Ac-

cumulator is always either the destination or source of the data.

The read and write strobes to external RAM are activated only during the execution of a MOVX instruction. Normally these signals are inactive and in fact if they’re not going to be used at u their pins are available as extra 1/0 lines. More about that later.

LOOKUP TABLES

Table 6 shows the two instructions that are available for reading lookup tables in Program Memory. Since these instructions access only Program Memory, the lookup tablea can only be read, not updated. The nmemonic is MOVC for “move constant”.

If the table access is to external Program Memory, then the read strobe is PSEN.

I

Table 6. Tha MCS3’-51 Lookup

Table Read Inetmctions

at

(A + PC) -

The first MOVC instruction in Table 6 can accommodate a table of up to

256

entries, numbered O through

255. The

number of the desired entry is loaded into the

Accumulator, and the Data Pointer is setup to point to beginning of the table. Then

MOVC A,@A+DPTR copies the desired table entry into the Accumulator.

The other MOVC instruction works the same way, except the Program Counter (PC) is used as the table base, and the table is accewed through a subroutine.

First the number of the desired entry is loaded into the

Accumulator, and the subroutine is cslled:

MOV

CALL

&ENTRY_NUMBER

TABLE

The subroutine “TABLE” would look like this:

TABLE: MOVC A,@A + PC

The table itself immediately follows the RET (return) instruction in Program Memory. This type of table can have up to 255 entries, numbered 1 through 255. Number O can not be used, because at the time the MOVC instruction is executed, the PC contains the address of the RET instruction. An entry numbered O would be the RET opcode itseff.

Boolean Instructions

MCS-51 devices contain a complete Boolean (single-bit) processor. The internal RAM contains 128 addressable bits, and the SFR space can support up to 128 other addressable blta. Afl of the port lines are bWaddressabl% and each one csn be treated as a separate singleblt port. The instructions that access these bits are not just conditional branches, but a complete menu of move, aeL clear, complement, OR and AND instmctions. These kinds of bit operations are not essily obtained in other architectures with any amount of byte-

Oriented Sottware.

1

1-14

[email protected] ARCHITECTURAL OVERVIEW

intd.

Table

7. A List of the MCS’@-51

Boolean Instrutilons

Mnemonic Operation

ANL C,bit IC = C .AND.

bit

I

ANL C./bit ! C = C .AND. .NOT. bit I

1 nnl

n

G.

16= C.OR. bit

Execution

Time (us)

2

2

2

MO\

F

UIL,U

ICLR c

CLR bit

SETB C

SETB bn

CPL C

I UIL –

Ic=o

w

]bit=o

Ic=l

Ibit= 1

I C = .NOT. C

CPL bit

JC rel

JNC rel

I bit = .NOT. bit lJumpif C= 1

Jump if C = O

JB bit,rel Jump if bti = 1

JNB bit,rel Jump if bit = O

JBC bit,rel IJump if bti = 1; CLR bit I

1=

1

1

I

1

1

1

2

2

2

1

2

2

The instruction set for the Boolean processor is shown in Table 7. Alt bit ameaaca are by direct addressing. Blt addreases OOHthrough 7PH are in the Lower 128, and bit addresses 80H through FFH are in SFR space.

Note how easily an internal ilag can be moved to a port pin:

MOV

MOV

C,PLAG

P1.o,c

In this example, FLAG is the name of any addressable bit in the Lower 128 or SFR space. An 1/0 line (the

LSB of Port 1, in this case) is set or cleared depending on whether the flag blt is 1 or O.

The bTy in the

PsW is used as the single-bit ACCU.

mulator of the Boolean processor. Bit instructions that refer to the Carry bit as C assemble as Carry-specflc instructions (CLR C, etc). The Carry bit also has a direct addreas, since it resides in the PSW register, which is bit-addressable.

I

1

Note that the Boolean instruction set includes ANL and ORL operations, but not the XRL (_ExclusiveOR) operation. An XRL operation is simple to implement in sof?.ware.Suppose, for example, it is Wuired @ form the Exclusive OR of two bits

C = bitl .XRL. bit2

The sot%vare to do that could be as follows:

MOV

CPL

OVER (continue)

C,bit 1 bit2,0VER

C

Fkst, bit 1 is moved to the Carry. If bit2 = O, then C now contains the correct reauh. That is, bit 1 .XRL. bit2

= bitl ifbiti = O. On the other hand, ifbit2 = 1 C now contains the complement of the correct result. It need only be inverted (CPL C) to complete the opcrstion.

This code uses the JNB instruction, one of a series of bk-teat instructions which execute a jump if the addressed bit is set (JC, JB, JBC) or if the addressed bit is not set (JNG JNB). In the above case, blt2 is being tested, and if bitZ = Othe CPL C instruction is jumped over.

JBC executes the jump if the addressed bit is set, and also clears the bit. Thus a fig can be teated and cleared in one operation.

All the PSW bits are directly addressable so the Parity bit, or the general purpose flags, for example, are also available to the bit-test instructions.

RELATIVE OFFSET

The

destination address for these jumps is specitied to the assembler by a label or by an actual address in

Program Memory. However, the destination address assembles to a relative offset byte. This is a signed

(two’s complement) oftket byte which is added to the

PC in two’s complement arithmetic if the jump is executed.

The range of the jump is therefore -128 to + 127 Program Memory bytes relative to the first byte following the instruction.

1-15

i~.

[email protected] ARCHITECTURAL OVERVIEW

Jump lnstruMlons

Table 8 shows the list of unconditional jumps.

Table 8. Unconditional Jumps in MCW’-51 Oavices

I

Mnarnonic

I

Operation

I JMP addr

I Jumo to addr

JMP @A+ DPTR I Jump to A+ DPTR

I Call subroutine at addr

I

Exeeution

Tilna (us)

121

2

2

CALL addr

1

RET

I

RETI

NOP

I

Returnfrominterrupt I

No oparation z

2

1

I

I

The Table lists a single “JMP addr” instruction, but in fact there are three-SJMP, LJMP and AMP-which differ in the format of the destination address. JMP is a generic mnemonic which can be used if the programmer does not care which way the jump is eneoded.

The SJMP instruction eneodes the destination address as a relative offset, as deaeribed above. The instruction is 2 bytes long, eonsiating of the opeode and the relative offset byte. The jump distance is limited to a range of

-128 to + 127 bytes reIative to the instruction following the SJMP.

The LJMP instruction eneodea the destination address as a Id-bit constant. The instruction is 3 bytes long, consisting of the opeode and two address bytes. The destination address ean be anywhere in the 64K Program Memory

SPSW.

The

AJMP

instruction

encodes

the

destination

address as an 1 l-bit constant. The instruction is

2 bytee long, eonaisting of the opode, which itself contains 3 of the

11 address bits, followed by another byte containing the low 8 bits of the destination address. When the instruction is executed, these 11 bits are simply substituted for the low 11 bits in the PC. The high 5 bits stay the same.

Hence the destination has to be within the same 2K block as the instruction following the AJMP.

In all eases the programmer specifies the de&nation address to the assembler in the same way as a label or as a id-bit constant. The assembler will put the destination address into the eormct format for the given instruction. If the format required by the instruction will not support the distance to the specified destination rtddresa, a “Destination out of range”

message is written

into the Lkt fde.

The JMP @A+ DPTR instruction supports ease jumps. The destination address is computed at exeeution time as the sum of the lti-bit DPTR register and the Accumulator. Typically, DPTR is set up with the addms of a jump table, and the Accumulator is given an index to the table. In a 5-way branch, for examplq an integer O through 4 is loaded into the Accumulator.

The code to be executed might be ax follows

MOV

MOV

RLA

JMP

DPTR, #JUMP_TABLE

A,INDEX_NUMBER

@A+DPTR

The RL A instruction converts the index

number (O

through 4) to an even number on the range Othrough 8, because each entry in the jump table is 2 bytee long:

~P_TABLE

MMP

AJMP

AJMP

AJMP

CASE_O

CASE_l

CASE_2

CASE_3

CASE_4

Table 8 shows a single “CALL addr” instruction, but there are two of them-LCALL and ACALL-which differ in the format in which the subroutine address is given to the CPU. CALL is a generic mnemonic which ean be used if the programmer does not care which way the address is encoded.

The LCALL instruction uses the Id-bit address format, and the subroutine ean be anywhere in the 64K Program Memory space. The ACALL instruction uses the

1l-bit format, and the subroutine most be in the same

2K bkxk as the instruction following the ACALL.

In any case the programmer specifies the subroutine address to the assembler in the same way as a label or as a 16-bit constant. The assembler will put the address into the correct format for the given instructions.

Subroutines should end with a RET instruction, which returns execution to the instruction following the

CALL.

RETI is used to return from an interrupt service routine. The only difference between RET and RETI is that RETI tells the interrupt control system that the interrupt in progress is done. If there is no interrupt in progress at the time RETI is executed, then the RETI is functionally identical to RBT.

Table 9 shows the list of conditional jumps available to the MCS-51 user. All of these jumps specify the destination address by the relative ot%et meth~ and so are lindted to a jump distance of – 128 to + 127 bytes from the instruction following the conditional jump instruction. Important to note, however, the user speeifies to the assembler the actual destination address the same way as the other jump as a label or a id-bit constant.

1-16

[email protected] ARCHITECTURAL OVERVIEW

i~.

Mnemonic

JZ

JNZ

rei

rel

DJNZ <byte> ,rel

CJNE A, <byte> ,rei

CJNE <byte> ,#data,rei

Table 9. Conditions Jumps in [email protected] Devioes

Operation

Jump if A = O

Jumpif A+O

Deorement and jump if not zero

Jumpif A # <byte>

Jump if <byte> # #data

Dir

Addressing Modes ind Rag imm

Accumulator oniy

Accumulator oniy

x x x x x x

There is no Zero bit in the PSW. The JZ and JNZ instructions test the Accumulator data for thst ccmdition.

The DJNZ instruction (Dezrement and Jump if Not

Zero) is for loop control. To execute a loop N times, load a counter byte with N and tersnina te the loop with a DJNZ to the beginning of the loop, as shown below for N = 10:

MOV com~#lo

LOOP: (begin loop)

*

RrsONAmR

@

Mes

-51

Execution

Time (ps)

2

2

2

2

2

Vss

=

270251-11

Figure 13. Using the On-Chip Oeciilator

(;d Imp)

DJNZ

COUNTER,LOOP

(continue)

The CJNE instruction (Compare and Jump if Not

Equal) can also be used for loop control as in Figure 12.

Two bytes are specified in the operand field of the instruction. The jump is executed only if the two bytes are not equal. In the example of Figure 12, the two bytes were the data in R1 and the constant 2AH. The initial data in R1 was 2EH. Every time the loop was executed, R 1 was decresnertted, and the looping was to continue until the R1 &ta reached 2AH.

Another application of this instruction is in “great= than, less than” comparisons. The two bytes in the op erand field are taken as unsigned integers. If the first is less than the second, then the Carry bit is set (l). If the first is greater than or equal to the second, then the

Carry bit is cleared.

CPU TIMING

All

MCS-51 microcontrollers have an on-chip oscillator which can be used if desired as the clock source for the

CPU. To use the on-chip oscillator, connect a crystal or ceramic resonator between the XTAL1 and XTAL2 pins of the microcontroller, and capacitors to ground as shown in Figure 13.

EilSRNAL

CLOCK

SIGNAL

CLOCK

w’%

SmLS

HMOS

ORCnuos

-4-I

=

A.

HMOS

or CHMOS

270251-12

-i-l

B. HMOS Only

WRNAL

L=

=

(w) s

STAL2

STAL1

Vss nut

Vss u

ONLY

Mcs”-51

HMOS

ONLY

Mm%!

CHMOS

STU.2

C. CHMOS only

270251-13

270251-14

Figure 14. Using an Externai Ciock

1-17

i~.

MCS’5’-51 ARCHITECTURAL OVERVIEW

Examples of how to drive the clock with an external oscillator are shown in Figure 14. Note that in the

HMOS devices (S051, etc.) the signal at the XTAL2 pin actually drives the internal clock generator. In the

CHMOS devices (SOC5lBH, ete.) the signsl at the

XTAL1 pin drives the internal clock generator. If only one pin is going to be driven with the external oscillator signal, make sure it is the right pin.

The internal clock generator defmea the sequence of states that make up the MCS-51 machine cycle.

Machine Cycles

A machine cycle consists of a sequence of 6 statea, numbered S1 through S6. Each state time lasts for two oscillator periods. Thus a machine cycle takes 12 Oscillator periods or 1 ps if the oscillator frequency is

12 MHz.

Each state is divided into a Phase 1 half and a Phase 2 half. Figure 15 shows the fetch/execute sequences in

(%L)

ALE

51

52 as se as .% s

52 as

Plm Prps PIP2 PIPS

PIPs

Pips PIPS Pips PIP2 mm

S4.SE

L

P2

PIPS

as

51

Pips

I

I

1

J

!

I

I nw OPCODE.

READ NEXT

I

I

I

(A) t-byts, l-eydshs2mdh,

e.g.,

WC A.

I

I

r

READ OPCODE.

I

I

I

I

(B)

2-byte. 1*

I

I

[email protected]

*.e.. Aoo A,mdma

i

I

I

I

I

READ NEXT OPCODE AGAIN. ~

1

I

I

I

OPCOOE (DISCARD).

-------

-------

S1 as es

I

[c)

l-byle,2qs4C imhlesm

.s., INC DPTR.

[

e4ae

------

-----

I

I

I

I

I

Seslases

I

1

e4aEes

,

I

I

RSAO NEXT OPCODE AGAIN.

— READ OPCOOE

(MWX).

READ NEXT

OPCOOE (OISCARD)

?

sla2a2s4] as eel

NO

, ‘1=””

~NOALE

1~

NO

S11S21S2]24SSSS

FETCH.

1

,,;

AOOR DATA

[0)

MOW (l-,

I

[email protected]@

I

ACCESS EXTERNAL

MEMORY

J

I

I

j

I

-----

I

------

I

I

-----

I

.-----

I

270251-15

Figure 15. Stete Sequences in [email protected]’-5l Devices

1-18

[email protected] ARCHITECTURAL OVERVIEW

in~e

states and phases for various kinds of instructions. NormalIy two program fetches sre generated during each machine cycle, even if the instruction being executed doesn’t require it. If the instruction being executed doesn’t need more code bytes, the CPU simply ignores the extra fetch, and the Program Counter is not incremented.

Execution of a one-cycle instruction (Figure 15A and

B) begins during State 1 of the machine cycle when the opcode is latched into the Instruction Register. A second fetch occurs during S4 of the same machine cycle,

Execution is complete at the end of State 6 of this mschine cycle.

The

MOVX

instructions take two machine

cycles to execute. No program fetch is generated during the see ond cycle of a MOVX instruction. This is the ordy time program fetches are skipped. The fetch/execute sequence for MOVX instructions is shown in Figure

15(D).

The fetch/execute sequences are the same whether the

Program Memory is internal or external to the chip.

Execution times do not depend on whether the Program Memory is internal or external.

Figure 16 shows the signals and timing involved in program fetches when the Program Memory is external. If

Program Memo~xternsl, then the Program Memory read strobe PSEN is normally activated twice per machine cycle, as shown in Figure 16(A).

If an access to external Data Memory occurs, as shown in Figure 16(B), two PSENS are skippe$ because the address and data bus are being used for the Data Memory access.

Note that a Data Memory bus cycle takes twice as much time as a Program Memory bus cycle. Figure 16 shows the relative timing of the addresses being emitted at Ports O and 2, and of ALE and PSEN. ALE is used to latch the low address bvte from PO into the address latch.

ALE

-N

ro

~

r

ONE MACHINE CVCLS sl[a21s21s41aslss

T

P2

PCH OUTX

ONE

MACIUNE CYCLE

SIIS21S21S41SE

I

1

I

1

1

1

I

PCH OUT

I

1 I

I

I

1

I

L r

I 1

I

I

I

1

x [

PCH OUT

x’

I

PCNOUT

I

1

I

1 I

I

1

1

I

I t5i:F t~::$m ty;LL&T &T

I

!

,

I

I

1

I

I

1

1

WITH%)UT A

MOVX.

G:v:m’lxm:m

-N

E

~

P2PcH [email protected](

)

I

1 1

I

I

I

! PCHOUT

x!

I

I

I

I

I

OPH OUT

OR P2 OUT

I

,

I

1

1

I

I

1

1

I

I

I

I

1

x:

PCH OUT )( PWOUT

(B)

WITH A

MOVX.

t P&m&T iAC:O&UT

Figure 16. Bus Cycles in [email protected] Oevices Extilng

2702!31 -16 irom External Program Memory

1-19

i~e

[email protected] ARCHITECTURAL OVERVIEW

When the

CPU is executing from intemrd Program

Memory, ~ is not activated, and program addresses are not emitted. However, ALE continues to be activated twice per machine cycle and so is available as a clock output signal. Note, however, that one ALE is skipprd during the execution of the MOVX instmction.

Interrupt Structure

The

8051

core provides 5 interrupt sources 2 external interrupts, 2 timer interrupts, and the serial pat interrupt. What follows is an overview of the interrupt structure for the t3051.Other MCS-51 devices have additional interrupt sources and vectors as shown in Table 1. Refer to the appropriate chapters on other devices for further information on their interrupts.

INTERRUPT ENABLES

Each of the interrupt sources can be individually enabled or disabled by setting or clearing

a

bit in the SFR

(MSB)

EAl — I—IESIETI

Enablebk = 1 enablesb interqf.

Ensblebk =odieabksit

(LSB)

IEXIIETOIEXO

symbol

Pmiti9n Function

EA

IE.7

d&bles all intempts. If EA = O, no interruptW be acknowledged.If EA

= 1, each intenupt source is itiiuslfy enabled or disebled by

ES

ETl

Exl

ETo

Exo

IE.6

IE.5

IE.4

IE.3

IE.2

IE.1

IE.O

settingw clearingite eneblebit.

reserved” reewed”

Ser!41Pwf Intemuptenabletin.

TImw 1 OverflowInterrupteneblebit

Gtsmsl Intenupf1 enable bit

TimerOflwrffw Interruptenabfebm

EstemslIntenuptOenablebit

“Thesereservedbiteare used in otherMCS-51devices.

Figure 17. IE (Interrupt Enable)

Register in the 8051

natned IE (Interrupt Enable). This register also contains a global disable bit, which can be cleared to disable all interrupts at once. Figure 17 shows the IE register for the 8051.

INTERRUPT PRIORITIES

Each interrupt source can also be individually pro-

~ed t? one of two

priority levels by setting or

clearing a blt m the SFR named 1P (Interrupt Priority).

Figure 18 shows the 1P register in the 8051.

A low-priority interrupt w be interrupted

by a high-

priority interrupt, but not by another low-priority inter-

IUpt. A high-priority any other interrupt source.

If two interrupt rquests of different priority levels are received simultaneously, the request of Klgher priority level is serviced. If interrupt requests of the same prioritylevel are received simultaneously, an interred polling sequence determines which request is serviced. Thus within each priority level there is a second priority structure determined by the polling sequence.

Figure 19 shows, for the 8051, how the IE and IP regieters and the polling sequence work to determine which if any inttipt Wiilbe-serviced.

(MSB)

——

IPSIPTI IPXIIPTOIPXO

(LSB)

Prforifybit=lsssign shighpriwity.

Prioritytit = OassignslowprWity.

symbol POeitiQn Functfon

IP.7

IP.6

resewed” rewed”

Ps

PTl

Pxl

PTo

Pxo

IP.5

IP.4

IP.3

IP2 lP.1

fP.o

reserved-

Serial Porfinterruptp+eritybii

Timer 1 intenuptpfbrity bfi.

ExternalIntenupt1 ptirity bit.

limsr Ointerruptpriorftybii

ExternalIntellupto priorityMt.

“These resewedtits are usedin other MCB-51devices.

Figure 18. 1P (Interrupt Priority)

Register in the 8051

1-20

intd.

[email protected] ARCHITEC~RAL OVERVIEW

HIGH PRIORllY

INTERRUPT

IE REGISTER 1P REGISTER o b

1.

+h-O+io

1 I

I

TFo /&+.

e b

INTERRUPT

‘POLUNG

SEQUENCE

1 o

-&-J.

1

I

:

0 b

7FI J&o

I

I

:

J+

0

v

RI n

I

A \

~

LyPwPNrr

270251-17

Figure

.-

19.8051

Intermpt control system

In operatiom all the interrupt tlags are latched into the interrupt control system during State 5 of every machine cycle. The samples are polled during the following machine cycle- If the flag for an enabled interrupt is found to be set (l), the interrupt system generates an

LCALL to the appropriate location in Program Memory, unless some other condition blocks the interrupt.

Several conditions can block an interrupt, among them that an interrupt of equal or higher priority level is already in progress.

The hardware-generated LCALL csusea the contents of the Program Counter to be pushed onto the stack, and reloads the PC with the beginning address of the service routine. As previously noted (Rgare 3), the service routine for each interrupt begins at a fixed location.

Only the Program Counter is automatically pushed onto the stack, not the PSW or any other register. Having only the PC be automatically saved allows the programmer to decide how much time to spend saving which other registers. This enhances the interrupt response time, albdt at the expense of increasing the pro-

-er’s bu~en of responsibility. As a result, many snterrupt functions that are typical in control applicstions-togghmg a port pim for example, or reloading a timer, or unloading a serial but%r-can otten be mmpleted in lms time than it takes other architectures to

commence

them.

SIMULATING A THIRD PRIORITV LEVEL IN

SOFIWARE

Some applications

require more than the two priority levels that are provided by on-chip hardware in

MCS-51 devices. In these cases, relatively simple software can be written to produce the same effect as a thkd priority level.

Firat, interrupts that are to have higher priority than 1 are ssaigned to priority 1 in the 1P (Interrupt Priority) register. The service routines for priority 1 interrupts that are supposed to be interruptible by “priority 2“ interrupts are written to include the following code

PUSH

MOV

IE

IE, #MASK

CALL

******

LABEL

(execute service routine)

******

IE POP

RET

LABEL RETI

1-21

[email protected] ARCHITECTURAL

OVERVIEW

As soon as any priority 1 interrupt is acknowledged, the IE (Interrupt Enable) register is m-defined so as to disable all but “priority 2“ interrupts. Then, a CALL to

LAEEL exeoutes the RETI instruction, which clears the priority 1 interrupt-in-program tlip-flop. At this point SIly priority 1 interrupt that is enabled can be seticed, but

Ody “priority’

2“ illtCSTUptS

POPping IE restores the original enable byte. Tberr a normal RET (rather than another RETI) is used to terminate the service routine. The additional software adds 10 ps (at

12 MHz) to priority 1 interrupts.

ADDITIONAL REFERENCES

The following application notes are found in the

Embedded Chstml AppIicatwns

handbook. (Order Num-

ber: 270648)

1. AP-69 “An Introduction to

the Intel [email protected] Sin.

gle-Chip Microcomputer Family”

2. AP-70 “Using the Intel MCW-51 Boolean Processing Capabtities”

1-22

[email protected]’s

Guide and Instruction Set

2

MCWI51 PROGRAMMER’S CONTENTS

GUIDE AND

MEMORYORGANIZATION

PAGE

INSTRUCTION SET

PROGRAM MEMORY .................................2-3

Data Memory...............................................2-4

INDIRECT ADDRESS AREA,...........,.........2-6

DIRECT AND INDIRECT ADDRESS

AREA ......................................................2-6

SPECIAL FUNCTION REGISTERS............2-8

WHAT DO THE SFRS CONTAIN JUST

AFTER POWER-ON OR A RESET,......,,2-9

SFR MEMORY MAP .................................2-lo

PSW: PROGRAM STATUS WORD. BIT

ADDRESSABLE ...................................2-1 1

PCON: POWER CONTROL REGISTER.

NOT BIT ADDRESSABLE .....,..,........,..2-1 1

INTERRUPTS............................................2-1 2

IE: INTERRUPT ENABLE REGISTER.

BIT ADDRESSABLE ............................2-12

ASSIGNING HIGHER PRIORITY TO

ONE OR MORE INTERRUPTS ..,.........,2-13

PRIORITY WITHIN LEVEL .......................2-13

1P:INTERRUPT PRIORITY REGISTER.

BIT ADDRESSABLE ..,..........,.,,...........2-13

TCON: TIMEFVCOUNTER CONTROL

REGISTER. BIT ADDRESSABLE ......,.2-14

TMOD: TIMEWCOUNTER MODE

CONTROL REGISTER. NOT BIT

ADDRESSABLE ...................................2-14

TIMER SET-UP .........................................2-1 5

2-1

TIMER/COUNTER 1..................................2-16

T2CON: TIMEWCOUNTER 2 CONTROL

REGISTER. BIT ADDRESSABLE ........2-17

TIMEWCOUNTER 2 SET-UP ...................2-18

SCON: SERIAL PORT CONTROL

REGISTER. BIT ADDRESSABLE ....,...2-19

CONTENTS

PAGE

CONTENTS

PAGE

SERIAL PORT SET-UP............................ 2-19

USING TIMEFUCOUNTER2 TO

GENERATE BAUD RATES ..................2-20

GENERATING BAUD RATES ..................2-1 9

Serial Port in Mode O................................ 2-19

‘ER’AL ‘ORT ‘N ‘ODE 2 .“.”””-””-””””.

2-20

Serial Port in Mode 1 ................................ 2-19

SERIAL PORT IN MODE 3 ...................O. 2-20

USING TIMER/COUNTER 1 TO

GENERATE BAUD RATES ..................2-20

M=&51 INSTRUCTION SET .................2-21

INSTRUCTION DEFINITIONS ................. 2-28

2-2

i~.

PROGRAMMER’S

AND INSTRUCTION SET

The informationpreaentedin this chapter is collectedfrom the MCW-51 ArchitecturalOverviewand the Hardware

Descriptionof the 8051,8052and 80C51chapters of this book. The material has been selected and rearrangedto form a quick and convenientreferencefor the programmersof the MCS-51.This guidepertains specificallyto the

8051,8052and 80C51.

MEMORY ORGANIZATION

PROGRAM MEMORY

The 8051

has separateaddressspacesfor Program Memoryand Data Memory.The Program Memorycan be up to

64K bytes long.The lower4K (8K for the 8052)may resideon-chip.

Figure 1 showsa map of the 8051program memory,and Figure 2 showsa map of the 8052program memory.

m.

FFFF

WK

BwEe exrmful.

OR

64K evree

EXTERNAL

10M

Omo

Figure

1. The 8051 Program Memory

270249-1

2-3

[email protected]’SGUIDE AND INSTRUCTION SET

S4K

BWEB

270249-2

Data Memory:

The 8051can address up to 64K bytes of Data Memoryexternal to the chip. The “MOW? instmetion is used to access the external data memory.(Refer to the MCS-51Instmction Set, in this chapter, for detailed deaeriptionof instructions).

The 8051has 128bytesof on-chipRAM (256bytesin the 8052)plus a numberof SpecialFunctionRegisters(SFRS).

The lower 128byteaof 3Uh4 can be accessedeither by direct addressing(MOVdata addr) or by indirect addressing

(MOV @Ri).Figure 3 showsthe 8051and the 8052Data Memoryorganization.

2-4

in~e

MCS”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

OFFF

64K

Bwea

“F

9—————I

&

INomECT

Aoon~

270249-3

w’

m

n=

Figure 3a. The 8051 Data Memory

FFFl m’rEmAL

6

IWIRECT

ONLY em To FFn

ema

OmE(n om.Y

Olmcl &

INOIRECT

AwnEaslNG

64K m-me

ExnmNAL

00.

Figure 3b. The 8052 Date Memory

270249-4

I

2-5

i~.

[email protected]’S GUIDE AND INSTRUCTION SET

INDIRECT ADDRESS AREA:

Note that in Figure 3b the SFRSand the indirect address RAM have the same addreasea(80H-OFFH).Nevertheless, they are two separate areas and are amesaed in two diiferentways.

For examplethe instruction

MOV

8oH,#o&lH

writesOAAHto Port Owhichis one of the SFRSand the instruction

MOV

Rr),#80H

MOV

@RO, writesOBBHin location 80H of the data RAM. Thus, after executionof both of the aboveinstructionsPort Owill contain OAAHand location 80 of the MM will contain OBBH.

Note that the stack operationsare examplesof indirect addressing,so the upper 128bytesof data MM are available as stack space in those deviceswhich implement 256 bytesof internal RAM.

DIRECT AND INDIRECT ADDRESS AREA:

The 128bytesof W whichcan be ameasedby both direct and indirect addressingcan be dividedinto 3 segments as listedbelow and shownin Figure 4.

1. Registar Banks

O-3:

Locations

Othrough lFH

(32

bytes).ASM-51and the deviceafter reset defaultto register bank O. To use the other register banks the user must select them in the software (refer to the MCS-51Micro

AssemblerUser’s Guide). Each register bank contains 8 one-byteregisters, Othrough 7.

Resetinitiahzesthe StackPointerto location 07H and it is incrementedonceto start from location08H whichis the first register(RO) of the secondregister bank. Thus, in order to use more than one register bank, the SP shouldbe intiaked to a different locationof the RAM where it is not used for data storage (ie, higher part of the WNW).

2. Bit AddressableArex 16 bytes have been assignedfor this segment,20H-2FH.Each one of the 128bits of this wgmmt can be directly addressed(0-7FH).

The bits can be referred

to

in two ways both of which are acaptable by the ASM-51.One way is to refer to their address ie. Oto 7FH. The other way is with referenceto bytes20H to 2FH. Thus,bits O-7 can alsobe referred to as bits 20.0-20.7, and bits 8-FH are the same as 21.0-21.7 and so on.

Each of the 16bytes in this segmentcan also be addressedas a byte.

3. Scratch Pad Arex Bytes30H through 7FH are availableto the user as &ta MM. However,if the stack pointex has been initializedto this arm enough number of bytes shouldbe left aside to prevent 5P data destruction.

2-6

in~.

[email protected]’SGUIDE AND INSTRUCTION SET

Figure4 shows the difYerentsegmentsof the on-chipRAM.

sol

4SI

SCRATCH

Pm

14P

ARSA

1.7

I

3F

301

2s

20

0...

18

10

0s

00

1

0

3

2

. . . 7F 2P

AaaRLLs

27 SSGMENT

IF

1?

RSGISIER

OF

BANKS

07

270249-5

Figure 4.128 Bytes of RAM Direct and Indirect Addreeesble

2-7

in~.

[email protected]’S GUIDE AND

INSTRIJCTlON SET

SPECIAL FUNCTION REGISTERS:

Table 1 containsa list of all the SFRs end their addressee.

ComparingTable 1and Figure 5 showsthat all of the SFRs that are byteand bit addressableare locatedon the first col~n of-the diagram in Figure 5.

Table 1

Symbol

*ACC

*B

“Psw

SP

DPTR

DPL

DPH

*PO

*P1

*P3

*IP

*IE

TMOD

“TCON

*+ T2CON

THO

TLO

TH1

TL1

+TH2

+TL2

+ RCAP2H

+ RCAP2L

SBUF

PCON

= Bitaddreaaable

+ = 8052

only

Name

Accumulator

B Register

ProgramStatusWord

Stack Pointer

Data Pointer2 Bytes

LowByte

HighByte

Porto

Port1

Port2

Port3

InterruptPriorityControl

InterruptEnable Control

Timer/Counter Mode Control

Timer/Counter Control

Timer/Counter 2 Control

Timer/Counter O HighByte

Timer/Counter O LowByte

Timer/Counter 1 HighByte

Timer/Counter 1 LowByte

Timer/Counter 2 HighByte

Timer/Counter 2 LowByte

T/C 2 Capture Reg. HighByte

T/C 2 Capture Reg. LowByte

SerialControl

Serial Data Buffer

PowerControl

Address

OEOH

OFOH

ODOH

81H

88H

OC8H

8CH

8AH

8DH

8BH

OCDH

OCCH

OCBH

OCAH

82H

83H

80H

90H

OAOH

OBOH

OB8H

OA8H

89H

98H

99H

87H

2-8

int&

[email protected] PROGRAMMERS GUIDE AND INSTRUCTION SET

WHAT DO THE

SFRS CONTAIN JUST A~ER POWER-ON OR A RESET?

Table 2 lists the contents of each SFR after power-onor a hardware reset.

Table 2. Conte

Register

“ACC

“B

*PSW

SP

DPTR

DPH

DPL

*PO

*P1

*P2

*P3

*IP

*IE

TMOD

+T2CON

THO

TLO

TH1

TL1

+TH2

+TL2

+RCAP2H

+RCAP2L

SBUF

PCON

) of the SFRS after reset

Value in Binary

00000000

00000000

00000000

00000111

00000000

00000000

11111111

11111111

11111111

11111111

8051 XXXOOOOO,

8052 XXOOOOOO

8051 OXXOOOOO,

8052 OXOOOOOO

00000000

00000000

00000000

00000000

00000000

00000000

00000000

00000000

00000000

00000000

00000000

00000000

Indeterminate

HMOS OXXXXXXX

CHMOS OXXXOOOO

= Undefined

= BitAddreassble

+ = 8052only

2-9

intd.

M(3%51 PROGRAMMERS GUIDE AND INSTRUCTION SET

SFR MEMORY MAP

D8

DO

C8 co

B8

BO

F8

FO

E8

EO

A8

AO

98

90

88

80

B

ACC

Psw

T2CON

1P

P3

IE

P2

SCON

PI

SBUF

TCON TMOD

Po

Bit

-r

Addressable

SP

8 Bytes

RCAP2L RCAP2H TL2

TLO

DPL

TH2

TL1

DPH

Figure 5

THO TH1

PCON

DF

D7

CF

C7

BF

B7

AF

FF

F7

EF

E7

A7

9F

97

8F

87

2-1o

i~.

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

Those SFRsthat havetheir bits assignedfor variousfunctionsare listedin this section.A briefdescriptionof each bit is providedfor quick reference.For more detailed informationrefer to the Architecture Chapter of this book.

CY

AC

FO

Rsl

Rso

Ov

P

CY

PSW: PROGRAM STATUS WORD. BIT ADDRESSABLE.

AC FO RS1 RSO Ov I — I P

PSW.7

Carry

Flag.

PSW.6

AuxiliaryCarry Flag,

PSW.5

Flag Oavailableto the user for generalpurpose.

PSW.4

PSW.3

RegisterBank selector bit 1 (SEE NOTE 1).

RegisterBank selector bit O(SEE NOTE 1).

PSW.2

OverflowFlag.

Psw.1

Psw.o

User definableflag.

Parity flag. Set/cleared by herdwareeach instructioncycleto indicateerrodd/werr number of

‘1’bita in the accumulator.

NOTE:

RS1 o o

1

1

RSO

0

1

0

1

Register Bank

2

3

0

1

Address

OOH-07H

08H-OFH

10H-17H

18H-l FH

PCON: POWER CONTROL REGISTER. NOT BIT ADDRESSABLE.

SMOD I — I — I — GF1 GFO PD IDL

SMOD Double baud rate bit. If Timer 1 is used to generatebaud rate end SMOD = 1, the baud rate is doubled when the SeriatPort is used in modes 1, 2, or 3.

Not implemented,reservedfor future w.*

Not implemented,reservedfor future w.*

Not implemented,reservedfor future use.”

GF1 General purposeflag bit.

GFO General purposeflag bit.

PD

Power Down bit. Setting this bit activates Power Down operation in the 80C51BH.(Availableonly in

CHMOS).

IDL Idle Modebit. %.ttittgthis bit activatesIdle Modeoperationin the 80C51BH.(Availableonlyin CHMOS).

If 1sare writtento PD andIDL at the sametimejPD tske$precedence,

featurea.In thatcase,theresetor inactivevalueofthe newbitwillbeO,anditsectivevaluewillbe 1.

2-11

irltele

[email protected]’SGUIDE AND INSTRUCTION SET

INTERRUPTS:

In order to use any of the interrupts in the MCS-51,the followingthree steps must be taken.

1. 3et the EA (enableall) bit in the IE register to 1.

2. Set the correspondingindividualinterrupt enablebit in the IE register to 1.

3. Beginthe

interruptservice

routineat the em-respondingVector Addressof that interrupt. SeeTablebelow.

I

Interrupt

Souroe

I

Vector

Address

IEO

TFO

IE1

TF1

RI &Tl

TF2 & EXF2

OO03H

OOOBH

O013H

OOIBH

O023H

O02BH

I

In addition,for extemaf interrupts,pins~ and INT1 (P3.2and P3.3)must be set to 1,and dependingon whether the intermpt is to be level or transitionactivated, bits ITOor IT1 in the TCON register may needto be set to 1.

ITx = Olevel activated

ITx = 1 transitionactivated

IE: INTERRUPT ENABLE REGISTER. BIT ADDRESSABLE.

If the bit is O,the correspondinginterrupt is disabled.If the bit is 1,the corresponding

interrupt

is enabled.

EA —

ET2

ES ETl EX1 ETo EXO

EA

ET2

Es

IE.7

Disablesall interrupts.IfEA = O,no interrupt willbe acknowledged.IfEA = 1,each interrupt source is individuallyenabledor disabledby setting or elearing its enablebit.

IE.6

Not implemented,reservedfor future use.*

IE.5

IE.4

Enable or disablethe Timer 2 overflowor capture interrupt (8052only).

Enable or disablethe serial port interrupt.

ET1

EX1

ETO

IE.3

Enable or disablethe Timer 1 overtlowinterrupt.

IE.2

Enable or disableExternal Interrupt 1.

IE.1

Enable or disablethe Timer Ooverflowinterrupt.

EXO IE.O

Enable or disableExternal Interrupt O.

*Usersoftwareshould not write 1sto reserved bits. These bits may be used in futore MCS-51preducts to invoke new features. In that case, the reset or inactivevalue of the new bit wilt be O,and its active valuewillbe 1.

2-12

[email protected] PROGRAMMER’SGUIDE AND INSTRUCTION SET

ASSIGNING HIGHER PRIORITY TO ONE OR MORE INTERRUPTS:

In order to assign higher priority to an interrupt the correspondingbit in the 1P register must be set to 1.

Rememberthat whilean interrupt servieeis in progress,it cannot be interrupted by a lower or same levelinterrupt.

PRIORITV WITHIN LEVEL:

Priority within level is only to resolvesimultaneousrequestsof the same priority level.

From high to low, interrupt sourcesare listed below:

IEO

TFo

IE1

TF1

RI or TI

TF2 or EXF2

1P:INTERRUPT PRIORITY REGISTER. BIT ADDRESSABLE.

If the bit is O,the correspondinginterrupt has a lowerpriority and if the bit is 1 the correspondinginterrupt has a higher priority.

I

— —

PT2

Ps PTl

Pxl PTO

1P.7

1P.6

Not irnplementi reservedfor future use.*

Not implemented,reservedfor future use.*

PT2 1P. 5 Detines the Timer 2 interrupt priority level(8052only).

Ps

Pm

Pxl

PTo

Pxo

1P.4

Definesthe SerialPort interrupt priority level.

1P. 3

1P.2

1P. 1

Definesthe Timer 1 interrupt priority level.

Defines External Interrupt 1 priority lexwl.

Defines the Timer Ointerrupt priority level.

1P.O

Definesthe External Interrupt Opriority level.

Pxo

*Usersoftware should not write 1s to reserved bits. Theaebits may be used in fiture MCS-51products to invoke new features. In that case, the reset or inactive valueof the new bit will be O,and its active value willbe 1.

2-13

intel.

[email protected] PROGRAMMER’SGUIDE

AND

INSTRUCTION SET

TCON: TIMER/COUNTER CONTROL REGISTER. BIT ADDRESSABLE.

TFl

TFl

TR1

TFO

TRO

IEI

IT1

IEO

ITO

TR1 TFO TRO IE1 IT1 IEO ITO

TCON. 7 Timer 1 overflowflag. Setby hardware when the Timer/Counter 1 overtlows.Clearedby hsrdware as processorvectorsto the interrupt service routine.

TCON.6 Timer 1 run control bit. Set/ckared by softwareto turn Timer/Counter 1 ON/OFF.

TCON. 5 Timer Ooverflowflag. Setby hardware when the Timer/Counter Ooverflows.Clearedby hsrdware as proceasorvectorsto the seMce routine.

TCON.4 TixnerOrun control bit. Set/cleared by software to turn Timer/Counter OON/OFF.

TCON. 3 External Interrupt 1 edge flag. Set by hardware when Extemsf Interrupt edge is detected.

Clearedby hardware wheninterrupt is proeesaed.

TCON.2 Interrupt 1 type control bit. Set/cleared by sotlwsre to specifyfalling edgeflowleveltriggered

External Interrupt.

TCON. 1 External Interrupt Oedgeflag.Set by hardware when ExternalInterrupt edgedeteeted.Cleared

by hardware when interrupt is proeeased.

TCGN.O Interrupt Otype control bit. Set/cleared by sotlwsre to specifyfsfling edge/low leveltriggered

External Interrupt.

TMOD: TIMER/COUNTER MODE CONTROL REGISTER. NOT BIT

ADDRESSABLE.

Ml o o

1

1

1

TIMER 1 TIMER O

GATE WhenTRx (in TCON) is set rmdGATE = 1,TIMEIUCOUNTERxwillrun only whileINTx pinis high

(hardware ecmtrol).When GATE = O,TWIER./C0UNTERx will run only while TRx = 1 (software control).

CiT’

Ml

MO

Timer or Counter seleetor. Ckred for Timer operation(input from internal system clock).Set for Counter operation(input from Tx input

pin).

Mode selectorbit. (NOTE 1)

Mode selectorbit. (NOTE 1)

NOTE1:

MO

00

1

02

1

1

Operating Mode

13-bit Timer (MCSA8 compatible)

1

16-bit Timer/Counter

3

8-bit Auto-ReloadTimer/Counter mimer o).TLois an a-bitTimer/Counter controlledby

the standard Timer

o controlbite,THOisan 8-bitTimer and is controlledby Timer 1 controlbits.

3 (Timer 1) Timer/Counter 1 stopped.

2-14

intel.

[email protected]’SGUIDE AND INSTRUCTION SET

TIMER SET-UP

Tables 3 through 6 give some valuesfor TMOD whicheen be used to setup Timer Oin differentmodes.

It is assumedthat only one timer is beingused at a time. If it is desiredto run TimersOend 1 simukaneoudy,in

snY mod%

the valuein TMOD for Timer Omust be ORed with the value shownfor Timer 1 (Tables5 and 6).

For example,ifit is desired to run Timer Oin mode1GATE (externalcontrol),and Timer 1in mode2 COUNTER, then the value that must be loaded into TMOD is 69H (09H from Table 3 ORed with 60H from Table 6).

Moreover.it is assumedthat the user, at this mint, is not ready to turn the timers on and will do that at a different point in he programby setting bit T-Rx(in TCON)to 1.

-

TIMER/COUNTER O

o

1

2

3

As a Timer:

MODE

““N

Table 3 m

OOH

13-bit Timer

16-bit Timer OIH

8-bit Auto-Reload two 6-bit Timera

02H

03H

08H

09H

OAH

OBH

As a Counter:

Table 4

MODE

2

3 o

1

COUNTER 0

FUNCTION

13-bitTimer

16-bitTimer

8-bit Auto-Reload one8-bitCounter

INTERNAL

CONTROL

(NOTE 1)

04H

05H

06H

07H

NOTES

1. TheTimeristurnedON/OFF

by

eettinglclearing

2. The Timeria turnedON/OFF control).

by

the 1 to Otransition

TMOD

EXTERNAL

CONTROL

(NOTE 2)

OCH

ODH

OEH

OFH

(P3.2)whenTRO= 1

2-15

intd.

[email protected]@.51 PROGRAMMERS GUIDE AND INSTRUCTION SET

TIMER/COUNTER 1

As a Time~

MODE

2

3 o

1

TIMER 1

FUNCTION

13-bitTimer

16-bitTimer

8-bit Auto-Reload does notrun

Table 5

INTERNAL

CONTROL

(NOTE 1)

OOH

10H

20H

30H

TMOD

EXTERNAL

CONTROL

(NOTE 2)

80H

90H

AOH

BOH

As a Counter:

Table 6

2

3 o

1

13-bitTimer

16-bitTimer

8-bitAuto-Reload not available

40H

50H

60H

WH

DOH

EOH

NOTES

2. The Timeris turnedON/OFF by the 1 to O transition (P3.3)whenTR1 = 1

2-16

[email protected]

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

T2CON: TIMER/COUNTER 2 CONTROL REGISTER. BIT ADDRESSABLE

8052

Only

TF2

TP2

EXF2 RCLK TCLK EXEN2 TR2

Cln cP/m

T2CON.7 Timer 2 overfiowtlag set by hardware and cleared by software.

either RCLK = 1 or CLK = 1

TP2 cannotbe set when

T2CON.6 Timer 2 external fig set wheneithera c.mtureor reload is causedbv a nemtive transition on EXP2

RCLK

TLCK

EXEN2

T2C0N. 5 to vector to the Timer 2 interrupt routine.EXF2 must be cleared by software

Receiveclock tlag. When set, causesthe Serial Port to use Timer 2 overtlowpulses for its receiveclockin modes 1 & 3. RCLK = OcausesTimer 1 overflowto be used for the receive clock.

T2C0N. 4

T2C0N. 3

Transmit clock flag. When set, causesthe Serial Port to use Timer 2 overtlowpulses for its transmit clock in modes 1 & 3. TCLK = O causes Timer 1 overflowsto be used for the transmit clcck.

Timer 2 external enable flag. When set, allows a capture or reload to occur as a result of

negative

transition on T2EX if Timer 2 is not being used to clock the Serial Port.

EXEN2 = OcauaeaTimer 2 to ignoreeventsat T2EX.

TR2

CRT

T2CON.2

T2CON. 1

SoftwareSTART/STOP control for Timer 2. A logic 1 starts the Timer.

Timer or Counter select.

cP/Rm T2CON.o

O = Internal Timer. 1 = ExternalEventCounter (fallingedgetriggered).

Capture/Reload flag. Whereset, captures will occur on negative transitions at T2EX if

EXEN2 = 1. When cleared, AuteReloads will occur either with Timer 2 overflowsor negativetransitions at TZEXwhenEXEN2 = 1. When either RCLK = 1 or TCLK = 1, this bit is ignoredand the Timer is forcedto Auto-Reloadon Timer 2 overflow.

2-17

in~.

M~Q.51

PROGRAMMERS GUIDE AND INSTRUCTION SET

TIMER/COUNTER 2 SET-UP

Ex~t for the baud rate mnerstor mode. the values aiven for T2CONdo not include the settine of the TR2 bit.

ller~fore, bit TR2 must ~ set, separately,to turn th~Timer on.

As

a Timer:

MODE

16-bitAuto-Reload

16-bitCapture

BAUD rate generatorreceive& transmitsame baudrate receive only transmitonlv

Table 7

INTERNAL

CONTROL

(NOTE 1)

OOH

OIH

T2CON

EXTERNAL

CONTROL

(NOTE 2)

08H

09H

34H

24H

14H

36H

26H

16H

4s a Counter:

MODE

16-bitAuto-Reload

16-bitCapture

NOTES

I

Table 8

INTERNAL

CONTROL

(NOTE 1)

02H

03H

TMOD

EXTERNAL

CONTROL

(NOTE 2)

OAH

OBH

I

2-18

i~e

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

SCON: SERIAL PORT CONTROL REGISTER. BIT ADDRESSABLE.

I

SMO SM1

SMO

SCON. 7

SM2 REN TB8

Serial Port modespecifier.(NOTE 1).

RB8 TI

RI

SM1 SCON.6

SM2

SCON.5

REN SCON.4

Serial Port modespecifier.(NOTE 1).

Enablesthe multiproceasor eomrnunieationfeaturein modes2 & 3. In mode2 or 3, if SM2is set to 1 then RI will not be activated if the -veal 9th data bit (RB8)is O.In mode 1,ifSM2 = 1 then RI will not be activated if a valid stop bit was not received.In modeO,SM2 shouldbe O.

(SeeTable 9).

Set/Cleared by softwareto Enable/Disable reeeption.

TB8

RB8 SCON.2

In modes2 & 3, is the 9th data bit that was received.In mode 1,ifSM2 = O,RB8 is the stop bit that was received.In mode O,RB8 is not used.

TI

SCON.3

The 9th bit that will be transmitted in modes2 & 3. Set/Cleared by software,

RI

SCON.1

Transmit interrupt tlag. Set by hardware at the end of the 8th bit time in mode O,or at the beginningof the stop bit in the other modes.Must be cleared by software.

SCON.O

Receive interrupt flag. Set by hardware at the end of the 8th bit time in mode O,or halfway through the stop bit time in the other modes(exceptsee SM2).Must be cleared by software.

NOTE1:

SMO o o

1

1

SM1

0

1

0

1

Mode

0

1

2

3

Deaoription

SHl~ REGISTER

8-Bit UART

9-Bit UART

9-Bit UART

Saud Rate

FOSC.112

Variable

Fo.sc./64OR

Fosc./32

Variable

SERIAL PORT SET-UP:

MODE

2

3 o

1 o

1

2

3

Table 9

SCON

10H

50H

90H

DOH

:0;

BOH

FOH

SM2 VARIATION

SingleProcessor

Environment

(SM2 = O)

Multiprocessor

Environment

(SM2 = 1)

GENERATING BAUD RATES

Serial Port in Mode O:

ModeOhas a freedbaud rate whichis 1/12 of the oscillatorfrequency.To run the serial port in this mode none of the Timer/Countersneed to be

Baud Rate = Y

Serial Port in Mode 1:

Mode 1 hss a variablebaud rate. The baud rate can be generatedby either Timer 1 or Timer 2 (8052only).

2-19

i~.

[email protected]’SGUIDE AND INSTRUCTION SET

USING TIMER/COUNTER 1 TO GENERATE BAUD RATES:

For this purpose,Timer 1 is used in mode 2 ([email protected]).Refer to Timer Setupsectionof this chapter.

BaudRate=

32X 12x [256 – (THI)]

If SMOD = O,then K = 1.

If SMOD = 1, then K = 2. (SMODis the PCON register).

Most of the time the user knowsthe baud rate and needsto know the reload valuefor TH1.

Therefore,the equation to calculate IT-Hcan be written as:

TH1 must be an integer value.Roundingoff THl to the neareat integer may not producethe desired baud rate. In this casejthe user may have to chooseenother crystal frequency.

Sincethe PCON register is not bit addressable,one wayto set the bit is logicalORingthe PCON register. (ie, ORL

PCON,#80H). The address of PCON is 87H.

USING TIMER/COUNTER 2 TO GENERATE BAUD RATES:

For this purpose,Timer 2 must be used in the baud rate generating mode. Refer to Timer 2 Setup Table in this chapter. If Timer 2 is beingclockedthrough pin T2 (P1.0)the baud rate is:

16

And if it is beingclockedinternallythe baud rate is:

BaudRate=

OscFraq

32X [65536- (RCAP2H,RCAP2L)]

To obtain the reload value for RCAP2H and RCAP2Lthe aboveequationcan be rewritten as:

RCAP2H,RCAP2L= 65536 – 32 ;:a::ate

SERIAL PORT IN MODE 2:

The

baud rate is fixedin this modeand is 7,, or%. of the oscillatorfrequencydpding on the v~ue of the SMOD bit in the PCON register.

In this modenone of the Timers are used and the clock comesfrom the internal phase 2 clock.

SMOD = 1, Baud Rate = YWOsc Frcq.

SMOD = O,Baud Rate = yWw FrMI.

To set the SMODbit: ORL pcON, #80H. The address of PCON is 87H.

SERIAL PORT IN MODE 3:

The

baud rate in mode 3 is variableand sets up exactlythe same as in mode 1.

2-20

I

i~.

M=”-51

PROGRAMMER’S

GUIDE AND INSTRUCTION SET

Interrupt ResponseTime: Refer to Hardware Description Chapter.

Instructions that Affect Flag

Settings(l)

Instruetkm

ADD

ADDC

SUBB

MUL

DIV

DA

RRC

RLC

SETBC x x

1 ox ox x

Ffsg

C

OV AC xx xx xx

Inetmetion Flsg

C OV AC

X CLRC

X CPLC o x

X ANLC,bit X

ANLC,/bit X

ORLC,bit X

ORLC,bit X

MOVC,bit X

CJNE x

(l)FJotethat

operationson SFR byte address 208 or bit addresses 209-215(i.e., the PSW or bits in the

PSW) will also afect flag settings.

Nota on inetruetionsat and ad&aesingmodes:

Rn — Register R7-RO of the currently selectedRegister Bank.

direct — 8-bit internal data location’s address.

This could been Internal Dsta RAM locetion (0-127) or a SFR [i.e., I/O pofi control register, status register, etc. (128-255)].

@Ri — 8-bit internal data RAM location (O-

255)addreasedindirectly through register R1 or RO.

#data — 8-bitco~~t includedin instruction.

#data 16— 16-bitconstant includedin instmction.

addr 16 — 16-bit destination address. Used by

addr

rel

bit

LCALL & LJMP. A branch can be anywhere within the 64K-byte Program Memory

SddR$S SpCCe.

1 — n-bit destination sddrrss. Used by

ACALL & AJMP. The branch willbe within the same 2K-byte page of program memo~ as the first byte of the foil-g instruction.

— Signed(two’scomplement)S-bitoffset byte.Usedby SJMP end all conditional jumps. Range is -128

to + 127 bytes

relative to first byte of the followinginstruction.

— Direct Addressedbit in Internal Data

W or SpecialFunction Register.

[email protected] INSTRUCTION SET

Table 10.8051 Inatruotion Set Summary

Mnemonic Dsseription

‘m

--. -

ADD A,direct

Accumulator

Adddirectbyteto

Accumulator

ADD

SUBB

SUBB

A,@Ri

ADD A,#date toAccumulator

Addimmediate dateto

Accumulator

ADDC A,Rn

ADDC

ADDC

ADDC

A,dirsct

[email protected]

A,#date

Accumulator withCarry

Adddirectbyteto

Accumulator withCarry

Addindirect

RAMto

Accumulator withCarry

Addimmediate datetoAcc withCeny

SUBB A,Rn

A,direct

[email protected]

A.#date fromAcewith borrow

Subtrectdirect bytefromAcc withborrow

Subfrectindiract

RAMfromACC withborrow

Subtract

1

2

1

2

1

2

1

2

1

2

1

2

INC

INC

INC

A

Rn direct fromAccwith borrw

Increment

Accumulator

Increment direct byte

1

1

2

INC @Ri

1

DEC A

DEC Rn

RAM

Decrement

Accumulator

Decrement

Regieter

1

1

DEC

DEC direct

@Ri byte

Decrement

2

1

Oaeilfstor

Period

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

12

.

2-21

i~e

[email protected]’SGUIDE AND INSTRUCTION SET

Mnemonic

KRL A,#data

KRL direct,A

Table 10.8051 Inetruotion Sat Summary (Continued)

Deaoription

~we o:acw~r

24

. ------ ----------

LUUIGAL urtm IIUNS

RL A NC DPTR 1

Pointer dUL AB

)IV AB

)A A

Ditie A byB

1

Accumulator

.OGICALOPERATtONS

\NL A,Rn

ANDRegieterto 1 tNL A,direct

Accumulator

ANDdiractbyte 2

1

1

4NL A,@Ri

4NL A,#date

4NL direct,A toAccumulator

ANDindirect

RAMto

1

Accumulator

ANDimmediate 2 datato

Accumulator

ANDAccumulator 2 todirectbyte

4NL diract, 3 datatodirectbyte

)RL A,Rn 1

Accumulator

2RL A,direct

2RL A,@Ri

3RL A,#date

ORdirectbyteto

Accumulator

2

ORindiract 1 toAccumulator

ORimmediate datato

2

3RL dirac4,A

Accumulator

ORAccumulator 2 todirectbyte

3

3RL dirsct,~date OR immediate detetodiractbyte

KRL A,Rn Excluaiva-OR 1

I(RL A,diraot

KRL A,@Ri regieterto

Armmulator

ExclusMe-OR directbyteto

Accumulator

Exclush/e-OR

2

1

Accumulator

Exclusiva-OR

Accumulator

Excluaive-OR directbyte

KRL direct,gdata Exclueive-OR

2

2

3

48

48

12

12

12

12

12

12

24

12

12

12

12

12

24

12

12

12

12

12

24

RLC A Rotate

. .

,.

RR

RRC

A

A

SWAP A

Rotate

Accumulator

Right

Rotate

Accumulator

Rightthrough mecerry

Swapnibbles withinthe

Accumulator

DATATRANSFER

MOV A,Rn Move

MOV A,direct

MOV A,@Ri

MOV A,#date

MOV Rn.A

MOV Rn,direot

MOV Rn,#date

Accumulator

Movediract byteto

Accumulator

Moveindirect

RAMto

Accumulator

Move immediate dateto

Accumulator

Move

Accumulator toregister

Movedirect byteto register

Move

MOV direct,A toregister

Mova

Accumulator todirectbyte

Moveregister MOV direct,Rn todirectbyte

MOV diract,direct Movedirect

MOV direct,@Ri bytatodiract

Moveindirect

RAMto directbyte

MOV direct,#date Move

MOV @Ri,A todireotbyte

Move

CLR A

CPL A todirectbyte

Clear

Accumulate

Complement

Accumulator

1

1

12

12

I

.

2-22

1

1

1

1

2

1

2

1

2

2

2

3

1

1

1

2

3

2

12

12

12

12

12

12

12

12

12

12

12

12

24

24

24

24

24

12

in~.

M=”-51 PROGRAMMER’S GUIDE AND INSTRUCTION SET

I

Table 10.8051 Instruction Set

Summary(Continued)

I

Mnemonic

Oeecriptfon

Byte ~~k~o’ Mnemonic

Description Byte

Oeciltetor

Period

MOV

MOV

@Ri,direct

@Ri,#date

Movedirect byteto

Move immediate dateto

2

2

MOV

DPTR,#data16LoedDets

3

MOVC A,@A+DPTR

16-bitconstant

MoveMe 1

MOVC A,@A+PC

MOVX A,@Ri

MOVX A,@DPTR

MOVX @Ri,A

MOVX @DPTR,A

PUSH direct

POP direct

XCH A,Rn

XCH A,direct

XCH

A,@Ri

XCHD A,@Ri

DPTRtoAcc

MoveCode

PCtoAcc

Move

External

RAM(8-bit eddr)toAcc

Move

External

RAM(l&bit addr)toAcc

MoveAccto

(8-bitaddr)

MoveAccto

(lS-bitaddr)

Pushdirect byteonto stack

Popdirect bytefrom stack

Exchange

Exchange directbyte with

Exchange with orderDigif

1

1

1

1

1

2

2

1

2

1

1

24

12

24

24

24

24

24

24

24

24

24

12

12

12

12

GLH

CLR

SETB

CPL

L bit c bit c

CPL

ANL

ANL

ORL

ORL

MOV

MOV

JC

JNC

JB

JNB

JBC bit

C,bit

C,/bit

C,bit

C,/bit

C,bit bit,C rel rel bit,rel bi$rel bit.rel

wearwny

SetCarry

Setdirectbit

Complement carry

Complement directbit

ANDdirectbit toCARRY

ANDcomplement ofdirectbit tocarry

ORdirectbit tocarry

ORcomplement ofdirectbit tocarry

Movedirectbit tocarry

MoveCsrryto directbit

JumpifCsny isset

JumpifCarry notset

Jumpifdirecf

Bitisset

Jumpifdirect

BitisNotset

Jumoifdirect

Bitisset& clearbit

2

2

2

2

2

2

2

2

2

3

3

3

1

2

1

2

1

ACALL addrl1 Absolute

Subroutine call

LCALL addr16 Long

Subroutine

RET call

Returnfrom

Subroutine

RETI

Retumfrom intempt

AJMP addrll Absolute

Jump

WMP addr16 LongJump

SJMP rel ShortJumo

(relativeaddr)

2

3

1

1

2

3

2

12

12

12

12

12

12

24

24

24

24

12

24

24

24

24

24

24

24

24

24

24

24

24

24 with Acc

2-23

int#

[email protected]’S GUIDE AND INSTRUCTION SET

Table 10.8051 Instruction Set SummarY (Continued)

Mnemonic Description Byte ‘~or

. . . . . . ..

-m . ..-,,,..-

BmANGmNQ

,-—.,....

(wnunueq

.’,

JMP @A+DPTR Jumpindirecf

1

24

JZ rel

DPTR

Jumpif

Accumulator isZero

Jumpif JNZ rel

Accumulator isNotZero

CJNE A,direct,rei Compare directbyteto

AccandJump ifNotEquai

CJNE A,#date,rel Compare

2

2

3

3

AccandJumo ifNotEqual

24

24

24

24

CJNE Rn,#date,rei Compare

JumpifNot

Equal

CJNE @Ri,#data,rel Compare

DJNZ Rn,rei

DJNZ direct,rel

NOP

Mnemonic Description Syte ~~or

3

3

JumpifNot

Equal

Decrement 2

JumpifNot

Zero

Decrement directbyte andJumpif

NotZero

3

NoOperation 1

24

24

24

24

12

2-24

i~.

[email protected] PROGRAMMERS GUIDE AND INSTRUCTION SET

Hex

Number

Code of

Bytes

26

27

28

23

2A

2B

2C

2D

2E

2F

ID lE

IF

20

21

22

23

24

25

16

19

1A lB lC

06

Oe

OA

OB

Oc

OD

OE

00

01

02

03

04

05

06

07

OF

10

11

12

13

14

15

16

17

30

31

32

;

:

2

1

1

1

1

1

1

1

1

2

2

3

2

1

1

1

1

1

1

1

1

1

2

1

1

1

1

2

3

1

1

1

1

1

1

1

1

3

2

1

1

1

3

1

1

1

2

Table 11. Instruction Q

Mnemonic

Operands

DEC

DEC

DEC

DEC

DEC

DEC

DEC

DEC

DEC

DEC

JB

AJMP

RET

RL

ADD

ADD

ADD

ADD

ADD

ADD

ADD

ADD

ADD

ADD

ADD

ADD

INC

INC

INC

INC

INC

INC

NOP

AJMP

WMP

RR

INC

INC

INC

INC

INC

INC

JBC

ACALL

LCALL

RRC

DEC

DEC

JNB

ACALL

RETI codesddr codesddr

A

A dstsaddr

@RO

@Rl

RO

RI

R2

R3

R4

R5

R6

R7 bitaddr,codeaddr codeaddr codeaddr

A

A dataaddr

@RO

@Rl

RO

RI

R2

R3

R4

R5

R6

R7 bifaddr,codeaddr codeaddr

A

A,#dats

A,datsaddr

A,@RO

A,@Rl

A,RO

A,R1

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7 bitaddr,codeaddl codeaddr i in Haxadecirnal Order

Hex code

Number of Bytes

Mnemonic

ANL

ANL

ANL

ANL

ANL

ANL

ANL

JZ

AJMP

XRL

ORL

ORL

ORL

ORL

ORL

ORL

JNC

ACALL

ANL

ANL

ANL

ANL

ANL

ANL

ANL

AJMP

ORL

ORL

ORL

ORL

ORL

ORL

ORL

ORL

RLC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADDC

ADD(2

JC

XRL

XRL

XRL

44

45

46

47

46

49

4A

3E

3F

40

41

42

43

36

39

3A

3B

3C

3D

33

34

35

36

37

56

57

5e

59

5A

5B

5C

5D

5E

5F eo

61

62

50

51

52

53

54

55

4B

4C

4D

4E

4F

63

64

65

1

1

1

2

2

2

1

1

1

1

1

1

3

2

2

1

2

2

2

1

1

1

1

1

2

2

1

2

2

3

1

1

1

1

1

2

1

1

1

1

1

1

1

1

2

2

1

1

3

2

2 operands

A,R3

A,R4

A,R5

A,Re

A,R7 codeaddr codeaddr dataaddr,A dataaddr,#data

A,#data

A,datsaddr

A,@RO

A,@Rl

A,RO

A,R1

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7 codeaddr codeaddr datesddr,A

A

A,#data

A,datsaddr

A,@RO

A,@Rl

A,RO

A,R1

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7 codeaddr codeaddr datsaddr,A dateaddr,#data

A,#data

A,dataaddr

A,@RO

A,@Rl

A,RO

A,R1

A,R2 datesddr,#data

A,#data

A,dataaddr

2-25

int#

[email protected]

PROGRAMMER’S GUIDE AND INSTRUCTION SET

Hex

Number

Code of

Bytaa

2

2

2

2

2

2

2

2

2

2

2

2

3

2

2

2

1

1

1

1

1

2

2

2

2

2

2

2

3

2

2

2

1

3

2

2

2

1

1

1

1

1

1

1

2

1

1

1

2

1

2

89

8A

8B

SC

8D

8E

8F

90

91

81

82

83

84

85

86

87

66

92

93

94

95

M

97

98

76

79

7A

70

7C

7D

7E

7F

80

72

73

74

75

76

77

5C

6D

SE

SF

70

71

5s

57

56

59

3A

5B hAov

Mov

MOV

MOV

SJMP

AJMP

ANL

MOVC

DIV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

ORL

JMP

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

XRL

XRL

XRL

XRL

XRL

XRL

XRL

XRL

XRL

XRL

JNZ

ACALL

MOV

MOV

MOV

MOV

ACALL

MOV

MOVC

SUBB

SUBB

SUBB

SUBB

SUBB

Mnemonic

Oparanda

A,@RO

A,@Rl

~RO

A,RI

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7 codeaddr codeaddr

C,bitaddr

@A+DPTR

A,#data datsaddr,#data

@Rl,#data

RO,#data

Rl, #data

R2,#data

R3,#data

R4,#data

R5,#data

R6,#data

R7,#data codeaddr codeaddr

C,bitaddr

A,@A+PC

AB dataaddr,dataaddr dataaddr,@RO dataaddr,@Rl dataaddr,RO dataaddr,Rl dataaddr,R2 dataaddr,R3 dataaddr,R4 dataaddr,R5 dataaddr,R6 dataaddr,R7

DPTR,#data codeaddr bitsddr,C

A,@A+DPTR

A,#data

A,dataaddr

A,@RO

A,@Rl

A,RO

s . . .

.

.-—-------,--.

.....---, -----

AD

AE

AF

BO

B1

02

A7

A8

A9

AA

AB

AC

Al

A2

A3

A4

A5

A6

99

9A

9B

9C

9D

9E

9F

AO

BC

BD

BE

BF co c1

C2

C3

C4

C5

C8

B3

24

B5

B6

B7

08

B9

BA

BB

C7

C8

C9

CA

CB

Hex Number

Coda of Bytaa

1

1

1

1

1

1

1

2

2

2

1

1

1

1

1

1

1

1

3

3

3

3

3

3

3

2

1

3

2

2

2

3

2

2

2

1

1

2

3

3

3

2

2

2

2

2

2

2

2

2

Mnemonic

ANL

ACALL

CPL

CPL

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

CJNE

PUSH

AJMP

CLR

CLR

SWAP

SUBB

SUBB

SUBB

SUBB

SUBB

SUBB

SUBB

ORL

AJMP

MOV

INC

MUL reaervad

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

XCH

XCH

XCH

XCH

XCH

XCH

XCH operands

A,R1

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7

C,/bitaddr codeaddr

C,bitaddr

DPTR

AB

@RO,dataaddr

@Rl,dataaddr

Rl,dataaddr

R2,dataaddr

R3,dstaaddr

R4,dataaddr

R5,dataaddr

R6,dataaddr

R7,dataaddr

C,/bitaddr codeaddr bitaddr c

A,#data,codeaddr

@Rl,#data,codeaddr

RO,#data,codeaddr

Rl,#datasodeaddr

R2,#data$odeaddr

R3,#daQcodeaddr

R4,#[email protected] addr

R5,#data,codeaddr

R8,#data,codeaddr

R7,#data,codeaddr dataaddr codeaddr bitaddr c

A

A,dataaddr

A,@RO

A,@Rl

A,RO

A,R1

A,R2

A,R3

2-26

ir&

[email protected] PROGRAMMER’SGUIDE AND INSTRUCTION SET

1

2

1

2

2

2

1

1

2

2

2

2

2

2

3

1

1

1

1

2

2

1

1

1

1

2

Table 11. Instruction Opoode

Hex

Number

Code of Bytee ‘nemonic

Operende cc

D5

D6

D7

CM

D9

DA

DB

CD

CE

CF

Do

D1

D2

D3

D4

E2

E3

E4

E5

DC

DD

DE

DF

EO

El

DJNZ

DJNZ

DJNZ

DJNZ

DJNZ

DJNZ

DJNZ

DJNZ

MOVX

AJMP

MOVX

MOVX

CLR

MOV

XCH

XCH

XCH

XCH

POP

ACALL

SETB

SETB

DA

DJNZ

XCHD

XCHD

A,R4

A,R5

A,R6

A,R7 dateaddr codaaddr biladdr c

A dateaddr,codeaddr

A,@RO

A,@Rl

Rl,codeaddr

R2,codeaddr

R3,cadeaddr

R4,codeaddr

R5,codaaddr

R6,c0deaddr

R7,codeaddr

A,@DPTR codeaddr

A,@RO

A,@Rl

A

A,dateaddr

In1

xadecimal Order (Continued)

Hex

Code

Number of Bytee

1

1

1

1

1

1

1

1

1

1

2

1

1

1

2

1

1

1

1

1

1

1 i

1

1

1

F6

F7

F8

F9

FA

FB

FI

F2

F3

F4

F5

E6

E7

E8

E9

EA

EB

EC

ED

EE

EF

FO

FC

FD

FE

FF

Mnemonic

MOVX

MOVX

CPL

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOV

MOVX

ACALL

Operande

RI,A

R2,A

R3,A

R4,A

R5,A

R6,A

R7,A

A,@RO

A,@Rl

A,RO

A,R1

A,R2

A,R3

A,R4

A,R5

A,R6

A,R7

@DPTR,A codeaddr

@RO,A

@Rl,A

A dataaddr,A

@RO,A

@Rl~

RO,A

2-27

[email protected]

PROGRAMMER’S

AND INSTRUCTION SET

INSTRUCTION DEFINITIONS

ACALL addrll

Function:

Deaoription:

Example:

Bytw

Cyclw

AbsoluteCall

ACALL unconditionallycalls a subroutinelocated at the indicated address.The instruction incrementsthe PC twim to obtain the address of the followinginstruction, then Duaheathe

Id-bit result onto the stack (low-orderbyte fret) and incremen~ the Stack Pointer&vice.The

incrementedPC opcodebits 7-5,and the secondbyte of the instruction.The subroutinecalled must therefore start within the same2K block of the programmemoryas the fsrstbyte of the instrueticmfollowingACALL. No flagsare affected.

InitiallySP equals 07H. The label “SUBRTN”is at programmemorylocation0345H. After executingthe instruction,

ACALL SUBRTN

2

2 at location0123H, SP will contain 09H, internal IL4M locations08H and 09H will contain

25H and OIH, respectively,and the PC will contain 0345H.

Encoding:

I

alO a9 a8 1

0001

ACALL

(PC)(PC)+

2

(SP) +

(SP) + 1

((sP)) + (PC74)

(SP) +

(SP) + 1

((SP))(PC15.8)

(PClo.o)+ page address

a7 a6 a5 a4 a3 a2 al aO

2-26

in~o

M~’@.51 PROGRAMMER’S GUIDE AND INSTRUCTION SET

ADD A,<src-byte>

Function:

Description:

Add

ADD adds the bytevariableindicatedto the Acewmdator,leavingthe result in the Accumulator. The carry and awdliary-carrytlags ~e set, respectively,if there is a carry-outfrom bit 7 or bit 3, and cleared otherwise. When adding unsigned integers, the carry flag indicates an overtlowoeared.

OVis set if there is a carry-out of bit 6 but not out of bit 7, or a carry-outof bit 7 but not bit 6; otherwiseOV is cleared. When addingsigmd integera,OV indicates a negativenumber produced as the sum of two positiveoperandsjor a paitive sum from two negativeoperands.

Foursouree operandaddressingmodesare allowed:register,direcLregister-indirect,or immediate.

Example: instruction,

ADD A,RO flag and OV SWto L

ADD A,Rn

Bytes:

Cycles:

1

1

Encoding:

Operation:

0010 Irrr

ADD

(A) + (A) + @O

ADD A,direct

Bytatx cycles:

2

1

Encoding:

Operation:

0010 0101

ADD

(A) + (A) + (direct)

I

directaddress

2-29

MCS”-51 PROGRAMMER’S GUIDE AND INSTRUCTION SET

ADD A,@Ri

Bytes:

Cycles:

1

1

Encoding:

Operation:

IO O1OI Ollil

ADD

(A) (A) + ((%))

ADD &#dats

Bytes

Cycles:

Encoding:

Operation:

2

1

0010

0100

ADD

(A) (A) + #data

[ immediatedata

ADDC A,<src-byte>

Function:

Description:

Add with Carry

ADDC simultaneouslyadds the byte variableindicated, the carry tlag and the Accumulator contents, leavingthe result in the Accumulator.The carry and auxiliary-carryfiags are set, respectively,if there is a carry-out from bit 7 or bit 3, and cleared otherwise.When adding unsignedintegers,the carry tlag indicatesan overtlowOccured.

OV is set if there is a carry-out of bit 6 but not out of bit 7, or a carry-outof bit 7 but not out of bit 6; otherwiseOV is cleared. When addingsignedintegers, OV indicatssa negativenumber producedas the sum of two positiveoperandsor a positivesum from two negativeoperands.

Four souroeoperandaddressingmodesare allowed:register, direct, register-indirect,or immediate.

Example:

~ fig set. The instruction,

ADDC A,RO

Ov set to 1.

2-30

intd.

[email protected]

ADDC A,Rn

Bytes:

Cyclm

1

1

Encoding: 0011 Irrr

Operation: ADDC

(A) (A) + (0 +(%)

ADDC A,direct

Bytes:

Cycles:

Encoding:

Operation:

2

1

0011

0101

1

ADDC

(A) + (A) + (C) + (direct) directaddress

ADDC A,@Ri

Bytes:

Cycles:

1

1

Encoding: 0011

Olli

Operation: ADDC

(A) + (A) + (C) + ((IQ)

ADOC A,+dats

Bytes:

Cyclesx

2

1

Enooding:

Operation:

0011

0100

ADDC

(A) +- (A) + (C) + #data

I immediatedata

2-31

i~.

[email protected]’SGUIDE AND INSTRUCTION SET

AJMP addrll

Example

Bytas

Cycles

AbsoluteJultlp

AJMP transfers program executionto the indicated address,which ia formedat run-time by concatenatingthe high-orderfivebits of the PC (afier incrementingthe PC twice),opcodebits

7-5,and the secondbyte of the instruction. The destinationmust thereforebe withinthe same

2K block of program memoryas the first byte of the instructionfollowingAJMP.

The label “JMPADR” is at program memory location0123H.The instruction,

AJMP JMPADR is at location 0345Hand will load the PC with O123H.

.

L

2

a7 a6 a5 a4 a3 S2 al aO Encoding:

Operation: alO a9 a8 O 0001

AJMP

@’cl+

(m +

2

(PClo.o)+ page address

ANL <dest-byte>, <src-byte>

Funotion:

[email protected] for byte variables

ANL performsthe bitwiselogical-ANDoperation betweenthe variablesindicatedand storea the results in the destinationvariable. No flags are affected.

The two operandsallowsix addressingmode combinations.When the destinationis the Accumulator, the source can w register, direct, regiater-indirec~or immediateaddressing;when the destinationis a direct address, the source can be the Accumulatoror immediatedata.

Note: When this instruction is used to modify an output port, the value used as the original port data will be read from the output data latch not the input pins.

Example:

instruction,

ANL A,RO

When the destinationis a directly addressed byte, this instruction will clear combinationsof bits in SOYRAM locationor hardware register. The maskbyte determiningthe pattern of bits

to be

clearedwouldeitherbe a constantcontainedin the instructionor a valuecomputedin

the Accumulatorat run-time.The instruction,

ANL Pl, #Ol110011B will clear bits 7, 3, and 2 of output port 1.

2-32

in~.

[email protected]’SGUIDE AND INSTRUCTION SET

ANL

A,Rn

Bytes:

Cycles:

Encoding:

Operation:

1

1

0101

Irrr

ANL A,direct

Bytee:

Cycles:

Encoding:

Operation:

0101 0101

ANL

(A) ~ (A) A (direct)

ANL &@Ri

Bytes:

Cyclee:

1

1

Encoding:

Operation:

0101

ANL

Olli

(A) + (A) A (w))

ANL A,#data

Bytes:

Cycles:

2

1

Encoding:

Operation:

0101 0100

ANL

(A) + (A) A #data

ANL [email protected]

Bytas: cycles

2

1

Encoding:

Operation:

10101

00101

ANL

(direct) + (direct) A (A)

directaddress immediate date directaddress

2-33

i~.

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

ANL [email protected] #dats

Bytes: 3

Cycles: 2

Encoding:

Operation:

0101 0011

ANL

(direct) + (direct) A #data

directaddress immediatedata

ANL C,<src-bit>

Function:

Description:

Logioal-ANDfor bit variables

If the Booleanvalueof the sourcebit is a logicalOthen clear the carry flag;otherwiseleavethe carry flag in its current stste. A slash (“/”) precedingthe operandin the assemblylanguage indicatesthat the logicalcomplementof the addressedbit is used as the sourcevaluq

but the source bit itself & not affwed. No

other flsgs are affected.

Onlydirect addressingis allowedfor the source -d.

Set the carry flag if, and only if, P1.O= 1, ACC. 7 = 1, and OV = O:

MOV C,P1.O

;LOAD CARRY WITH INPUT PIN STATE

ANL ~ACC.7

ANL C,/OV

;AND CARRY WITH ACCUM. BIT 7

;AND WITH INVERSEOF OVERFLOWFLAG

ANL C,bit

Bytes:

Cycles:

2

2

Encoding:

Operation:

1000

100101

ANL

(C) ~ (C)

A (bit)

H

ANL C,/bit

Bytes:

Cycles:

.

2

Encoding:

1o11 0000

Operation:

ANL

(C) + (C)A 1

=

(bit)

2-34

[email protected]

MCS’@-51PROGRAMMER’S GUIDE AND INSTRUCTION SET

CJNE <dest-byte>,<src-byte>, rel

Function:

Description:

Compareand Jump if Not Equal.

CJNE comparesthe magnitudesof the fmt two operands,and branches if their valuesare not equal. The branch destinationis computedby addingthe signedrelative-displacementin the last instructionbyte to the PC, after incrementingthe PC to the start of the next instruction.

The carry flag is set if the unsignedinteger value of <dest-byte> is less than the unsigned integer valueof <src-byte>; otherwise,the carry is cleared. Neither operand is tided.

The first two operands allow four addressingmode combinations:the Accumulatormay be comparedwith any directlyaddressedbyte or immediateda~ and any indirectRAM location or worldngregister can be comparedwith an immediateconstant.

The Accumulator contains 34H. Register 7 contains 56H. The first instruction in the sequence

NOT—EQ:

CJNE R7,#60H, NOT-EQ

. . . . .

. . .

REoLLOw

. . . . .

; R7 = 60H.

; IF R7 < &3H.

; R7 > 60H.

sets the carry flag and branchesto the instructionat labelNOT-EQ. By testingthe carry flag, this instructiondetermines whether R7 is greater or less than 60H.

If the data being presentedto Port 1 is also 34H, then the instruction,

WAIT: CJNE A,P1,WAIT clears the carry tlag and continueswith the next instructionin sequence,sincethe Accumulator doesequal the data read from P1. (If someother valuewas beinginput on Pl, the program will loop at this point until the PI data changesto 34H.)

CJNE A,direct,rel

Bytes: 3

Cycles: 2

Encoding:

Operation:

1o11

0101

I ‘ire”addressI EiEl

(PC) (PC) + 3

IF (A) <>

(direct)

THEN

(PC) + (PC) + relativeoffket

IF (A) <

(direct)

THEN

~L~E (c) -1

(c)+ o

2-35

intel.

M&0h51 PROGRAMMERS GUIDE AND INSTRUCTION SET

CJNE A,4$data,rei

Bytee: 3

Cycles: 2

Encoding:

1o11 0100

] immediatedats I

Operation:

(-PC)+ (PC) + 3

IF (A) <> data

THEN

(PC) -

(PC)+

relative offiet

IF (A) <

data

THEN

EME (c) -1

(c) + o

! rel. address I

CJNE Rn,#dats,rel

Bytea:

3

Cyclea:

2

Encoding:

Operation:

1o11 Irrr

I

immediate data

(PC) + (Pc) + 3

IF (Rn) <>

data

THEN

(PC) + m) + relative ofiet

IF ([email protected] <

data

THEN

(c) + 1

ELSE

(c)+ o

CJNE @Ri,#data,rel

Bytea: 3

Cyclea:

2

Encoding:

Operation:

I 1o11

Olli I immediatedate I

(P(2)+ (PC) +

3

IF ((Ri)) <> data

THEN

(PC) t (PC!)

rehztive oflset

IF (@i)) <

data

THEN

ELSE (c) -1

(c) + r)

EEl

I rel.addressI

2-36

intd.

[email protected]’SGUIDE AND INSTRUCTION SET

CLR A

Function:

Description:

Example:

Clear Aecunlulator

The Aecunmlatoris cleared (all bits set on zero). No flags are affeeted.

Bytee:

Cyclea:

CLR A will leave the Accumulatorset to OOH(~

1

1

B).

Encoding:

Operation:

1110

CLR

(A) + O

0100

CLR bit

Function:

Description:

Clear

bit

The

Example:

CLR P1.2

will leave the port set to 59H (O1O11CK)1B).

CLR C

Bytea: cycle=

1

1

Encoding:

Operation:

I

1100

CLR

(c) + o

0011

CLR bit

Bytea:

Cyclea:

2

1

Encoding: 1 100

Operation:

CLR

(bit) + O

0010

I

I bitaddress I

2-37

intelo

[email protected]’SGUIDE AND INSTRUCTION SET

CPL A

Function:

Description:

ComplementAccumulator

Each bit of the Accumulatoris logicallycomplemented(one’scomplement).Bits whichpreviouslycontaineda one are changedto a zero and vice-versa.No tlags are affected.

Example:

Bytes:

Cycles:

CPL A will leave the Accumulatorset to OA3H(101OOO11B).

1

1

Enooding:

Operation:

1111

CPL

(A) -1

(A)

0100

CPL bit

Function:

Deeoription:

Complementbit

The bit variablespecifiedis complemented.A bit which had beena one is changedto zero and vice-versa.No other flagsare affected.CLR can operate on the carry or any directly addressable bit.

Note:Whenthis instructionis usedto modifyan output pin,the valueused as the originaldata will be read from the output data latch, not the input pin.

Example:

CPL P1.1

CPL P1.2

will leavethe port set to 5BH (O1O11O11B).

CPL C

Bytes:

Cycletx

1

1

Encoding:

Operation:

I

1o11

CPL

(c)+

1 (c)

0011

2-38

i~.

[email protected]’SGUIDE AND INSTRUCTION SET

CPL bit

Bytes:

Cycles:

2

1

Encoding:

Operstion:

1o11

CPL

(bit) ~l(bit)

100’01 EEiEl

DA A

Funotion:

-adjust Accumulatorfor Addition

Description:

DA A adjusts the eight-bitvaluein the Accumulatorresultingfrom the earlieradditionof two variables(each in packed-BCDformat), producingtwo four-bitdigits. Any ADD or ADDC instruction may have been usedto perform the addition.

six is added to the A ccunndatorproducingthe proper J3CDdigit in the low-ordernibble.This

internal additionwouldset the carryflag ifa carry-outof the low-orderfour-bitfieldpropagated through all high-orderbits, but it would not clear the carry tlag otherwise.

If the carry tlag is now seLor if the four high-orderbits nowexceednine (101OXXXX-1I1XXXX), thesehigh-orderbits are incrementedby six, producingthe properBCD digitin the high-order nibble.Again, this wouldset the carry flag if there was a carry-out of the high-orderbits, but wouldn’tclear the carry. The carry flag thus indicates if the sum of the original two BCD

All of this occurs during the one instruction cycle. Essentially,this instructionperforms the decimal conversionby addingOOH,06H, 60H, or 66H to the Accurnulator, depending on initial A ccurmdatorand P3W conditions.

Note:DA A cannot simplyconverta hexadecimalnumber in the Accrumdatorto BCD notation, nor does DA A apply to decimalsubtraction.

2-39

intd.

[email protected]’SGUIDE AND INSTRUCTION SET

decimal number 56. Register 3 containsthe value 67H (0110011lB)representingthe packed

BCD digits of the decimal number 67. The carry flag is set. The instructionsequence.

ADDC A,R3

DA A wdl first perform a standard twos-complementbinary addition, resultingin the value OBEH

(10111110)in the Accumulator. The carry and auxiliary carry flags will be cleared.

The Decimal Adjust instruction will then alter the Accumulator to the value 24H digitsof the decimalsum of 56,67, and the carry-in.The carry tlag willbe set by the Decimal

Adjust instruction,indicatingthat a ddnal overflowoccurred. The true sum 56,67, and 1 is

124.

BCD variablescan be incrementedor decrementedby addingOIHor 99H.If the Accumulator initially holds 30H (representingthe digitsof 30 decimal),then the instructionsequence,

ADD A#99H

Bytes

Cycles:

DA A will leave the carry set and 29H in the Accumulator,since 30 + 99 = 129.The low-order byte of the sum can be interpreted to mean 30 – 1 = 29.

1

1

Encoding:

Operstion:

1101 0100

DA

-contents of Accumulatorare BCD

IF

[[(A3-13)>91

V [(AC) =

111

THEN(A34)(A343)+ 6

AND

IF

[[(A7-4)> 9] V [(C) =

111

THEN (A74) (A74) + 6

2-40

in~.

MCS”-51 PROGRAMMER’S GUIDE AND INSTRUCTION SET

DEC byte

Function:

Description:

Exampte:

Decrement

The

variableindicatedis decrementedby 1.An originalvalueof OOHwill underilowto OFFH.

No flags are affected. Four operand addressingmodes are allowed:accumulator, register,

&[email protected] or register-indirect.

Note: When this

instruction is used to modifyan output port, the value used as the original port data willbe read from the output data latch, not the input pins.

Register Ocontains 7FH (0111111IB). Internal RAM locations7EH and 7FH contain OOH and 40H, respectively.The instructionsequence

DEC @RO

DEC RO

DEC @RO will leave registerOset to 7EH and internal RAM locations7EH and 7FH set to OFFHand

3FI-I.

DEC A

Bytes:

Cyclx

1

1

Encoding:

Operation:

0001 0100

DEC

(A) (A) – 1

DEC Rn

Bytes: cycles:

1

1

Encoding:

Operation:

0001 lrrr

DEC

(Rn) + @l) – 1

241

i~.

[email protected]’SGUIDE AND INSTRUCTION SET

DEC direct

Bytes:

Cycles:

Encoding:

Operation:

2

1

0001

0101

DEC

(direct) (direct) – 1

I

DEC @Ri

Bytes:

Cycles:

1

1

Encoding:

Operation:

10001 I Ollil

DEC

(w)) -((N)) – I

directaddress

DIV AB

Function: Divide

Description:

DIV AB divideathe unsignedeight-bitinteger in the Accumulatorby the unsignedeight-bit integer in register B. The Accumulator receivesthe integer part of the quotient; register B receivesthe integer remainder.The carry snd OV tlags will be cleared.

Exception:

ifB had originallycontainedOOH,the valuesreturned in the Accumulatorand Bregister will be undefinedand the overflowflag will be set. The carry tlag is cleared in any case.

Example: The

The instruction,

DIV AB in B, since 251 = (13 X 18) + 17.Carry and OV willboth be cleared.

Bytes: 1

Cycles: 4

Enooding:

Operation:

I

1000 0100

DIV

(A)15.8

(A)/@t)

2-42

in~.

[email protected]’SGUIDE AND INSTRUCTION SET

DJNZ <byte>, <rel-addr>

Function: DecrementandJumpif Not

=0

Description:

DJNZ decrementsthe location indicated by 1, and branchesto the address indicatedby the second operandif the resulting value is not zero. An originalvalue of OOHwill underflowto

OFFH.No tlags are at%cted.The branch destinationwouldbe computedby addingthe signed relative-displacementvaluein the last instructionbyteto the PC, after incrementingthe PC to the first byte of the followinginstruction.

Example:

The location decreznentedmaybe a register or directlyaddressedbyte.

Note: When

this

instruction is used to modfi an output port, the value used as the original port data will be read from the output data latch, not the input pins.

Internal RAM locations40H, 50~

tively. The instructionsequence, and 60H containthe values OIH, 70H, and 15H,respec-

DJNZ 40H,LABEL-1

DJNZ 50H,LABEL-2

DJNZ 60H,LABEL-3 will cause a jump to the instructionat label LABEL-2 withthe valuesOOH,6FH, and 15Hin the three W locations The first jump was not taken becausethe result was zero.

This instruction provideaa simpleway of executinga programloop a givennumberof times, or for addinga moderatetime delay (from 2 to 512machinecycles)with a singleinstruction.

The instruction sequence,

MOV

TOOOLE: CPL

DJNZ

R2,#8

P1.7

R2,TOOGLE will toggle P1.7 eight times, causing four output pukes to appear at bit 7 of output Port 1.

Each pulse will last three machinecycles;two for DJNZ and one to alter the pin.

DJNZ Rn,rel

Bytee:

cycles:

2

2

Encoding:

I

1101

11’”1

Operation:

DJNZ

(PC!)(PC) + 2 m) -(w w ~~~

– 1

0 or ([email protected] < t)

EEl

(PC)+ (PC)+ rd

2-43

int&

MCS”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

DJNZ [email protected]

Byte=

Cycles

3

2

Encoding:

Operation:

1101

0101

DJNZ

(PC) + (PC) + 2

(direct) + (direct) – 1

IF (direot) >0 or (direct) <0

THEN

(PC) -(PC) + ml

I ‘irw’addressI EiEl

INC <byte>

Function:

Description:

Incmsnent

INC incrementsthe indicatedvariableby 1. An originalvalueof OFFHwill overflowto OOH.

No figs are affected.Three addressingmodesare allowed:register,direct, or register-indirect.

Note.”When this instruction is used to modifyan output port, the value used ss the original port data will be read from the output data latch, not the input pins.

Exsmple: RegisterOcontains7EH

and 40H, respectively.The instructionsequence,

INC @RO

INC RO

INC @RO will leaveregisterOset to 7FH and internal RAM locations7EH and 7FH holding(respectively) (XIHand 41H.

INC A

Bytes: cycles:

1

1

Encoding:

Operstion:

0000 0100

INC

(A) + (A) + 1

2-44

i~e

M=”-51 PROGRAMMER’S GUIDE AND INSTRUCTION SET

INC Rn

Bytes: cycles

Encoding:

Operation:

1

1

0000

Irrr

INC m)+ w) + 1

INC direct

Bytee:

Cycles:

Encoding:

Operation:

2

1

0000

0101

INC

(direct) ~ (direct) + 1

INC @Ri

Bytes:

Cycles:

Encoding:

Operation:

1

1

0000

Olli

INC

(m)) + (m)) + 1

1 directaddress

INC DPTR

Function:

Description:

Example:

Bytes:

Cycle=

Increment Dsta Pointer

Increment the id-bit data pointer by 1. A id-bit increment (modulo216)is performed;an overflowof the low-orderbyte of the data pointer (DPL) from OFFHto COHwill increment the high-orderbyte (DPH). No tlsgs are sfkted.

This is the only id-bit register whichcan be incremented.

RegistersDPH and DPL contsin 12Hsnd OFEH,respectively.The instruction sequence,

INC DPTR

INC DFTR

INC DPTR will chsnge DPH and DPL to 13Hsnd OIH.

1

2

Encoding:

Operation:

1o1o 0011

INC

(DPTR) (DFITl) + 1

245

i~.

[email protected] PROGRAMMER’SGUIDE AND INSTRUCTION SET

JB bityrei

Function:

Description:

Bytes:

Cycierx

Jump if Bit set

If the indicated bit is a one,jump to the [email protected] otherwiseproceedwith the next the third instruction byte to the PC, after incrementingthe PC to the fnt byte of the next instruction. The

bit tested k nor modified. No tlags are affected.

The data

instructionsequence,

JB P1.2,LABEL1

JB ACC.2,LABEL2 will causeprogram executionto branch to the instruction at label LABEL2.

3

2

Encoding:

Operstion:

0010

1004 EEzEEl

JB

(PC)+ (PC)+

3

IF (bit) = 1

THEN

(PC) +- (PC) + rel

EizEl

JBC bitrei

Function: lump if Bit is setand Clearbit

Description:

If the indicated bit is one, branch to the address indicated; otherwiseproceedwith the next instruction. 17re

bit wili not be cleared ~~itis already a zero. The

branch destinationis computed by adding the signedrelative-displacementin the third instruction byte to the PC, after incrementingthe PC to the tlrst byte of the next instruction. No flags are affected.

Note:When this instructionis used to test an output pin, the value used as the original data will be read from the output data latch, not the input pin.

Exempie: The

Accumulatorholds 56H (01010110B).The instruction sequence,

JBC ACC.3,LABELI

3BC ACC.2,LABEL2 will cause program executionto continueat the instruction identifiedby the label LABEL2, with the Accumulator modifiedto 52H (OIO1OO1OB).

2-46

M=”-51 programmers GUIDE AND INSTRUCTION SET

Bytes:

Cycles:

3

2

Encoding:

Operation:

I“” ”’l” ”””1 DEEl

JBc

(PC) (PC) + 3

IF (bit) = 1

THEN

(bit) * O

(PC) ~ (PC) + rel

EiEiEl

JC rel

Function:

Daacription:

Exsmple:

Bytes cycles:

Encoding:

Operation:

Jump if Carry is set

If the carry flag is set, branch to the addreas indicated; otherwise proceed with the next instruction.The branch destinationis computedby addingthe signedrelative-displacementin the secondinstructionbyte to the PC, after incrementingthe PC twice. No flagsare afkted.

The carry flagis clesred. The instruction sequence,

JC LABEL1

CPL C

JC LABEL2

2

2 will set the carry and cause program executionto continueat the instructionidentifiedby the label LABEL2.

0100 0000

=

JC

(PC)+ (PC)+

2

IF (C) = 1

THEN

(PC) ~ (PC) + rel

2-47

[email protected]

[email protected]’SGUIDE AND INSTRUCTION SET

JMP @A+DPIR

Function:

]ump indirect

Add the eight-bitunsignedcontentsof the Accurnulator with the sixteen-bitdata pointer, and load the resultingsum to the programcounter.This willbe the addressfor subsequentinstruction fetches.Sixteen-bitaddition is performed(modrdo216):a camy-outfrom the low-order eight bits propagatesthrough the higher-orderbits. Neither the Accumulator nor the Data

Pointer is altered.No tlags are affected.

An evennumberfromOto 6 is in the Accumulator.The followingsequenceof instructionswill branch to one of four AJMP instructionsin a jump table starting at JMP-TBL:

Bytex

Oycies:

JMP-TBL:

MOV

DPTRj#JMP-TBL

JMP @A+DPTR

AJMP LABEL.O

AJMP LABEL1

AJMP LABEL2

AJMP LABEL3

If the Accumulatorequals 04H when starting this sequence,execution will jump to label

LABEL2.Rememberthat AJMP is a two-byteinstruction,so the jump instructions start at every other address.

1

2

Encoding:

Opersliorx

10111

JMP

W)+

00111

(A) +

WW

2-48

[email protected]’SGUIDE AND INSTRUCTION SH

JNB bi~rel

Function:

Jump if Bit Not set

If the indicatedbit is a zero, branch to the indicatedaddress;otherwiseproceedwith the next instruction.The branch destinationis computedby addingthe signedrelative-displacementin the third instruction byte to the PC, after incrementingthe PC to the first byte of the next instruction. The

bit tested is not modt~ed. No

flags are affected.

Example:

Bytes:

Cycles:

Encoding:

Operation:

instruction sequence,

JNB P1.3,LABEL1

JNB ACC.3,LABEL2 will cause program executionto continueat the instructionat label LABEL2.

3

2

0011

100001

JNB

$W:)y; +

3

LGzEl

THEN (PC) t (PC) + rel.

EEl

JNC rel

Function:

Description:

Jump if Carry not set

If the carry tlag is a zero, branch to the addreas indicated;otherwiseproceed with the next instruction.The branch destinationis computedby addingthe signedrelative-displacementin the second instruction byte to the PC, after incrementingthe PC twice to point to the next inatruetion.The carry tlag is not moditled.

Example: The carrytlag

is set. The instructionsequence,

JNC LABEL1

CPL C

JNc LABEL2

Bytes

Cycles: 2

will clear the carry and cause program executionto continueat the instruction identitkd by the label LABEL2.

2

Encoding:

0101

100001 -

Operation: JNC

(PC) (PC) + 2

IF (C) = O

THEN (PC) t (PC) + rel

2-49

i~.

[email protected]’SGUIDE AND INSTRUCTION SET

JNZ rel

Function:

Example:

Bytea:

Cyclea:

Jump if AccumulatorNot Zero

If any bit of the Accumulator is a one, branch to the indicatedaddress;otherwiseproceedwith the next instruction. The branch destination is computedby adding the signed relativedisplacement in the second instruction byte to the PC, after incrementingthe PC twice. The

Accumulator is not modified.No tlags are affected.

The Accumulator originallyholdsOOH.The instructionsequence,

JNZ LABEL1

INC A

JNZ LAEEL2 will set the Accumulatorto OIH and continueat label LABEL2.

2

2

Encoding:

Operation:

0111

10’001 EiEl

JNz

(PC)+ (PC) + 2

IF (A) # O

THEN (PC) ~ (PC) + rel

JZ rel

Function:

Daaoription:

Bytea:

Cycles:

Jump if AccumulatorZero

If all bits of the Accumulatorare zero, branch to the [email protected] otherwiseproceedwith the

next

instruction. The branch destination is computedby adding the signed relative-displacement in the second instruction byte to the PC, after incrementingthe PC twice. The

Accumulator is not modified.No flags are affected.

The Accumulator originallycontainsOIH. The instruction sequen~

JZ LABELI

DEC A

JZ LABEL2 will change the Aec.umulator to OOHand cause programexeeutionto continueat the instruction identifiedby the label LABEL2.

.4

2

E“ncodirrg:

I

0110

Operation:

0000

[ rel. addreee

(PCJ)

2

IF (A) = O

THEN (PC) t @C) + rel

2-50

in~.

M=”-51 programmers GUIDE AND INSTRUCTION SET

LCALL addr16

Function:

Description:

Example:

Longcall

LCALLcalls a subroutineIooatedat the indicatedaddress. The instructionadds three to the program counter to generate the address of the next instruction and then pushes the Id-bit result onto the stack (low byte first), incrementingthe Stack Pointer by two. The high-order and low-orderbytesof the PC are then loaded,respectively,with the secondand third bytes of the LCALLinstruction.Programexeoutionrxmtinueswith the instructionat this address.The

subroutinemaythereforebeginanywherein the full 64K-byteprogrammemoryaddress space.

No ilags are affeeted.

Initiallythe Stack Pointer equals07H.The label “SUBRTN”is assignedto programmemory location 1234H.After exeoutingthe instruction,

LCALL SUBRTN

Bytes:

Cycles:

at location0123H,the Stack Pointer will contain09H, internal IL4M Iccations08H and 09H will contain26H and OIH, and the PC will contain 1234H.

3

2

Encoding:

Operation:

0001 0010

LCALL

(PC) + (PC) +

(SP) + (SP) + 1

3

((sP)) (PC74)

(SP) (SP) + 1

((sP)) (PC15.8)

(PC) ~ addr15~

I addr’’-add’ I EEEiEl

UMP addr16

Function:

Description:

Example:

Long

Jump

LJMP causesan unconditionalbranch to the indiested address,by loadingthe high-orderand low-orderbytes of the PC (respectively)with the second and third instruction bytes. The destinationmay therefore be anywherein the full 64K program memoryaddress sparx. No flags are affected.

The label“JMPADR” is assignedto the instructionat programmemorylocation 1234H.The

instruction

LJMP JMPADR at location0123Hwill load the programcounter with 1234H.

Cycles:

Enooding: operation:

2-51

i~.

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

MOV <dest-byte>, <erc-byte>

Function:

Oeacription:

Movebyte vmiable

The byte variableindicatedby the secondoperandis copiedinto the locationspecifiedby the first operand.The source byte is not affeeted.No other register or flag is at%eted.

Example:

This is by far the mmt flexible operation. Fifteen combinationsof source and destination addressingmodes are allowed.

Internal RAM location 30H holds 40H. The value of RAM location 40H is 10H.The data

MOV RO,#30H ;RO < = 30H

MOV A,@RO

;A < = 40H

MOV R1,A

MOV B,@Rl

;Rl < = 40H

;B < = 10H

MOV @Rl,Pl

;RAM (4X-I)< = OCAH

MOV P2,PI ;P2 #OCAH leavesthe value30H in register O,40Hin both the Aecumulator and register 1, 10Hitsregister

MOV A,Rn

Bytes:

Cycles:

1

1

Encoding:

Operation:

*MOV A,direct

Bytes:

Cycles:

2

1

1110

MOV

(A) + (RIO

lrrr

Encoding:

Operation:

1110 0101

MOV

(A) + (direct)

MOV~ACC

ie not a valid instruction.

direct address

2-52

intd.

[email protected]’SGUIDE AND INSTRUCTION SH

MOV A,@Ri

Bytes:

Cycles:

Encoding:

Operation:

1.

1

1110

MOV

(A) (~))

Olli

MOV A,#data

Bytes:

Cycles:

2

1

Encoding:

Operation:

0111

MOV

(A) + #data

0100

MOV Ftn,A

Bytes:

Cycles:

1

1

Encoding:

Operation:

I 1111

MOV

~) t (A)

I Irrrl

I immediatedata

MOV Rn,direot

Bytee:

Cyclea:

Encoding:

Operation:

.

L

2

I

1010

Ilr’rl -

MOV

([email protected] + (direct)

MOV Rn, #data

Bytes: cycles:

.

1

Encoding:

Operation:

0111

MOV

([email protected] #dsts

lrrr immediatedata

2-53

irrtd.

[email protected] PROGRAMMER’SGUIDE AND INSTRUCTION SET

MOV directJl

Bytetx

Cycle$x

2

1

Encoding:

Operation:

1111

MOV

MOV [email protected]

Bytes:

Cyciee:

2

2

Encoding:

Operation:

1000

MOV

0101

Irrr

MOV directjdirect

Bytw 3

Cycie= 2

Encoding:

Operation:

I

1000 0101

MOV

(direct) +- (direct)

MOV [email protected]

Bytes:

Cycles:

2

2

Encoding:

Operation:

I

1000 Olli

MOV

(MM) + (w))

MOV direc$xdats

%yte= 3

Cycle= 2

Encoding:

Operation:

0111 0101

MOV

(direct) + #date

directaddress directaddress

I

dir.addr. (src) directaddress dir.addr. (dest) immediatedata

I

2-54

intd.

[email protected] AND INSTRUCTION SET

MOV @Ri&

Bcycles:

.

1

1

Encoding:

Operation:

1111

MOV

(@i)) + (A)

Olli

MOV @Ri,direct

Bytes:

Cycles:

2

2

Encoding:

Operation: llOIOIOllil

MOV

(@i)) + (direct)

MOV @Ri,#data

Bytes:

Cycles:

2

.

1

Encoding:

Operation:

0111 Olli

MOV

((RI)) + #data

I

I directaddr. I immediate data

MOV <cleat-bit>, <erc-bit>

Function: Move

Description: The

Booleanvariableindicatedby the second operand is copiedinto the locationspecitkd by the first operand. One of the operandsmust be the carry flag; the other may be any directly addressablebit. No other registeror flag is affected.

Example: The carry tlag is originallyset. The data

MOV P1.3,C

MOV C,P3.3

MOV P1.2,C will

leavethecarry

cleared and changePort 1 to 39H (OO111OO1B).

2-55

I

int&

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

MOV C,blt

Bytes:

Cycles:

2

1

Enooding:

Operstion:

1o1o

MOV

(~+(bit)

1“0’01

MOV bi&C

Bytes:

Cycles:

.

L

2

Enooding:

Operstion:

1001

MOV

(bit) + (C)

1“0’01

EiEl

E

MOV DPTR,#dsts16

Function:

Description:

Example:

Bytesx

Cycles:

Load Data Pointer with a Id-bit constant

The Data Pointer is loaded with the Id-bit constant indicated.The id-bit constant is loaded into the second and third bytes of the instruction. The secondbyte (DPH) is the high-order byte, while the third byte (DPL) holds the low-orderbyte. No tlags are atTeeted.

This is the only instruction whichmovea 16bits of tits at once.

The instruction,

MOV DPTR, # 1234H willload the value 1234Hinto the Data Pointer: DPH willhold 12Hand DPL will hold 34H.

3

.

L

I immed.data7-O

Encoding:

Operation:

1001 0000

I immed. dsts15-6

MOV

(DPTR) ~ #data154

DPH ❑ DPL + #&ltS15.8❑ #data73

I

2-56

intd.

[email protected]’SGUIDE AND INSTRUCTION SET

MOVC A,@A+<baas-reg>

Function:

Description:

Example:

MoveCode byte

The MOVCinatmctionsload the Accumulatorwith a oode byte, or constant from program memory.The addressof the byte fetchedis the sum of the originalunsignedeight-bitAccumulator contents and the contents of a sixteen-bitbase register, which may be either the Data

Pointer or the PC. In the latter case, the PC is incrementedto the addressof the following instruction before being added with the Accumulator; otherwise the base register is not altered. Sixteen-bitaddition is performed so a carry-out from the low-ordereight bits may propagatethrough higha-order bits. No flags are affected.

A valuebetweenOand 3 is in the Accumulator.The followinginstructionswill translate the valuein the Accumulatorto one of four valuesdefimedby the DB (definebyte) directive.

REL-PC: INC A

MOVC A,@A+PC

RET

DB

DB

DB

66H

77H

DB

88H

99H

If the subroutineis called with the Accumulatorequal to OIH, it will return with 77H in the

Auxmmlator. The INCA beforethe MOVCinstruction is neededto “get around” the RET instructionabovethe table. If severalbytes of code separated the MOVCfrom the table, the correspondingnumber wouldbe added to the Accumulator instead.

MOVC [email protected]+

DPTR

Bytes:

1

Cycles:

2

Encoding:

Operation:

MOVC A,@A + Pc

Bytes:

Cycles:

1

2

11001 10011

MOVC

(A) + ((A) + (D~))

I

Encoding:

Operation:

1000 0011

MOVC

(PC) + (PC) + 1

(A) ((A) + (PC))

2-57

int&

[email protected]’SGUIDE AND INSTRUCTION SET

MOVX <dest-byte>, <sin-byte>

Function: Move External

Deaoription: The MOVX

instructions transfer data betweenthe Accumulator and a byte of exa data memory,hence the “X” appendedto MOV.There are two types of instructions,differingin whetherthey providean eight-bitor sixteen-bitindirect address to the externrddata RAM.

In the first typq the contents of ROor R] in the current register bank providean eight-bit address multiplexedwith data on PO.Eight bits are sufficient for external 1/0 expansion decodingor for a relativelysmall RAM array. For somewhatlarger arrays, any output port pins can be used to output higher-orderaddress bits. These pins wouldbe controlled by an output instructionprecedingthe MOVX.

In the secondtype of MOVXinstruction,the Data Pointer generatesa sixteen-bitaddress. P2 outputsthe high-ordereight addressbits (the contents of DPH) whilePOmultiplexesthe loworder eightbits (DPL) with data. The P2 SpecialFunction Register retains its previouscontents whilethe P2 ouQut buffers are emitting the contents of DPH. This form is faster and more efticientwhen accessingvery large data arrays (up to 64K bytes), since no additional instructionsare neededto set up the output ports.

Example:

It is possiblein some situations to mix the two MOVX types. A large R4M array with its high~rder address lines driven by P2 can be addressed via the Data Pointer,or with code to output high-orderaddress bits to P2 followedby a MOVX instructionusingROor RI.

An external256 byte RAM using

address/&talines(e.g.,an Mel

8155UM/

I/Oflimer) is connected to the 8051Port O. Port 3 provides control lines for the external

W.

Ports 1 and 2 are used for normal 1/0. Registers O and 1 contain 12H and 34H.

Location34H of the extemsJ RAM holdsthe value 56H. The instructionsequence,

MOVX [email protected]

MOVX

@RO,A copiesthe value 56H into both the Accumulatorand external RAM location 12H.

2-58

i~o

[email protected] PROGRAMMER’SGUIDE AND INSTRUCTION SET

MOVX &@Ri

Bytes:

Cycles:

1

2

Encoding:

Operation:

MOVX

[email protected]

Bytes:

Cycles:

1

2

1110

MOVX

(A) (~))

OOli

Encoding:

Operation:

1110 0000

MOVX @Ri,A

Bytes:

Cycles:

1

2

Encoding:

Operation:

1111

MOVX

OOli

MOVX @DPIR#l

Bytes: cycles:

1

2

Encoding:

Operation:

1111 0000

MOVX

(DPTR) (A)

2-59

i~e

MCS”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

MUL AB

Deeoriptiors:

Example

Multiply

MUL AB multipliesthe unsignedeight-bit integers its the Accumulator and register B. The

Iow-orderbyteof the sixteen-bitproduct is left in the Accumulator,and the high-orderbyte in

B. If the product is greater than 255 (OPPH)the ovcrtlowflag is set; otherwiseit is cleared.

The carry fiag is alwayscleared.

Originallythe Accumulatorholds the value 80 (50H).RegisterB holds the value 160(OAOH).

The instruction,

MuLAB

Bytes:

Cycles:

tor is cleared. The overflowflag is set, carry is cleared.

1

4

Encoding:

Operation:

I 101 OIO1OOI

MUL

(A)74 + (A) X (B)

(B)15-8

NOP

Function:

Description:

Example:

No Operation

Executioncontinuesat the followinginstruction. Other than the PC, no registersor flagsare affected.

It is desired to producea low-goingouQut pulse on bit 7 of Port 2 lasting exactly5 cycles.A

simple SETB/CLR sequencewould generatea one-cyclepulse,so four additionalcyclesmust be inserted. This may be done (ssauming no interrupts are enabled) with the instruction

SeqUenee,

Bytes

Cycles:

CLR P2.7

NOP

NOP

NOP

NOP

SETB P2.7

1

1

Encoding: 000010000

Operation:

NOP

+

1

2-00

in~.

[email protected]’SGUIDE AND INSTRUCTION SET

ORL <dest-btie> <src-byte>

Funotion:

Logicsl-ORfor byte variables

ORL performs the bitwiselogical-ORoperationbetweenthe indicated variables,storing the results in the destinationbyte. No flags are affected.

The two operandsallowsixaddressingmodecombinations.Whenthe destinationis the Accumulator, the source can use register, direct, register-indirect,or immediateaddressing;when the destinationis a direct addreas,the source can be the Accumulatoror immediatedata.

Note.-When this instructionis used to modifyan output port, the value used as the original port dats will be resd from the output data latch, not the input pins.

Example:

struction,

ORL A,RO will leave the Accumulatorholdingthe value OD7H(110101llB).

When the destinationis a directlyaddreasedbyte, the instructioncan set combinationsof bits in any RAM location or hardware register. The pattern of bits to be set is determinedby a mask byte, whichmaybe eithera constantdata valuein the instructionor a variablecomputed in the Aecunndator at rim-time.The instruction,

ORL P1,#OOllOOIOB will set bits 5,4, and 1 of output Port 1.

ORL &Rn

Bytes:

Cycles:

1

1

Encoding:

Operstion:

0100 lrrr

ORL

(A) +- (A) V K)

2-61

i~e M=a-sl

INSTRUCTION SET

ORL &direct

Bytes:

Cycles:

2

1

Encoding:

Operation:

1010010101

ORL

(A) + (A) V (direct)

I

ORL &@Ri

Bytes:

Cycles:

1

1

0100 Olli

Encoding:

Operation: directaddress

ORL A,#dets

Bytes:

Cycles:

2

1

Encoding:

Operation:

Iolool O1oo1

ORL

(A) (A) V #dsts

immediatedata

ORL direct,A

Bytes:

Cyclea:

1

directaddress Encoding:

Operation:

0100 0010

ORL

(direct) ~(direct)

V (A)

ORL direcQ*data

Bytes: 3

Cycles: 2

Encoding:

Orwstion:

0100

0011

I

ORL

(direct)+ (direct) V #data

EEEl immediate date

I

2-62

in~.

[email protected]’S GUIDE AND INSTRUCTION SET

ORL C,<src-bit>

Function:

Description:

Example:

Logical-ORfor bit variables

*t

the carry

flag if

the

Booleanvalue is a logical 1; leave the carry in its current state otherwise. A slash (“/”) precedingthe operand in the assemblylanguageindicatesthat the logicalcomplementof the addressedbit is used as the source value,but the sourcebit itself is not at%cted.No other tlags are afkcted.

Set the carry flag if and only ifP1.O = 1, ACC. 7 = 1, or OV = O:

MOV CPI.O

;LOAD CARRY WITH INPUT PIN P1O

ORL C,ACC.7 ;OR CARRY WITH THE ACC. BIT 7

ORL Wov

;OR CARRY WITH THE INVERSEOF OV.

ORL C,bit

Bytes:

Cycles:

2

2

Encoding:

Operation:

0111

IOO1OI EEl

ORL C,/bit

Bytes:

Cycles:

.

2

Encoding:

Operation:

I

1010

100001

ORL

(c)+ (c) v

@=)

EEEl

2-63

i~.

M~eI-51 programmers GUIDE AND INSTRUCTION SET

POP direot

mrsctiom

Pop from stack.

Example:

The contents of the internal RAM location addressedby the Stack Pointer is read, and the

Stack Pointer is decrementedby one. The value read is then transferred to the directly addressedbyte indicated.No flags are affected.

The Stack Pointer originally contains the value 32H, and internal RAM locations 30H through 32H contain the values 20H, 23H, and OIH, respectively.The instructionsequen~

Bytea:

Cycla$s

POP DPH

POP DPL willleavethe Stsck Pointer equal to the value30Hand the Data Pointer set to 0123H.At this point the instruction,

POP SP will leave the Stick Pointer set to 20H. Note that in this special case the Stack Pointer was

*remented to 2FH beforebeing loaded with the value popped

(20H).

2

2 directaddress Encoding:

Operation:

I

1101 0000

POP

(direct) + ((sP))

(SP) 4-(SP) – 1

PUSH direct

Function:

Description:

push onto stack

The StackPointeris incrementedby one. The contentsof the indicatedvariableis then copied into the internal RAM locationaddressedby the Stack Pointer. Otherwiseno flagsare affected.

On entaing an interrupt routine the Stack Pointercontains09H. The Data Pointer holds the value O123H.The instruction sequence,

PUSH DPL

PUSH DPH

Bytes:

Cycletx

2

2 will leave the Stack Pointer set to OBHand store 23H and OIH in internal FL4Mlocations

OAHand OBH,respectively.

Enooding:

Operation:

1100

0000

PUSH

(SP) + (SP) + 1

((SP))(direct)

I

directaddreaa

2-04

int&

M~tV-51 PROGRAMMER’SGUIDEANDINSTRUCTIONSET

RET

Function:

Description:

Example:

Bytm cycles:

Encoding:

Operation:

Return tlom subroutine

RET pops the high-and low-orderbytes of the PC successivelyfrom the staclGdecrementing the Stack Pointer by two. Program executioncontinuesat the resultingaddress,generallythe instruction immediatelyfollowingan ACALL or LCALL. No tlags are affected.

The Stack Pointer originallycontains the valueOBH.Internal RAM locationsOAHand OBH contain the value-a23H and OIH, respectively.The instruction,

RET will leave the Stack Pointer equal to the value 09H. Program executionwill continue at

Ioeation0123H.

1

2

10010100101

RET

+-

((sP))

(SP) +(SP) – 1

(PC74) + ((sP))

(SP) + (SP) -1

RETI

Function:

Description:

Exemple:

Return from interrupt

RETI pops the high- and low-orderbytes of the PC successivelyfrom the stack, and reatores the interrupt logic to accept additional interrupts at the same priority level as the one just processed.The Stack Pointer is left decrementrdby two. No other registersare aik%sd; the

PSW is not automaticallyrestored to its pre-interruptstatus. Program executioncontinuesat the resultingaddress, which is generallythe instructionimmediatelyafter the point at which the interrupt requestwas detected. Ifa lower-or same-levelinterrupt had beenpendingwhen the RETI instruction is executed, that one instruction will be executedbefore the pending interrupt is processed.

The Stack Pointer originally contains the value OBH.An interrupt was detected during the instruction ending at location 0122H. Internal RAM locations OAHand OBHcontain the values 23H and OIH, reapeotively.The instruction,

RETI wilt leave the Stack Pointer equat to O$IHand return program executionto locationO123H.

Bytes:

Cyclee:

1

2

Encoding:

Operation:

10011 I 00101

(PCls.s)

((sP))

(sP)+ (SP) -1

(PC74) + ((sP))

(SP) -(SP) -1

2-65

intd.

M=”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

RL A

Function:

Description:

Rotate Aecurnulator Left

The eight bits in the Aeeurmdatorare rotated one bit to the left. Bit 7 is rotated into the bit O position.No flagsare akted.

Example:

RLA

Bytes:

Cycle=

L

1

Encoding:

Operation:

0010 0011

I

RL

(~ +

1) -

(AO)+ (A7)

(An) n = O –

6

RLC A

Function:

Description:

Rotate Accumulator L-et?through the Carry flag

The eightbits in the Aeeumulator and the carry tlag are togetherrotated onebit to the left. Bit

7 movesinto the carry flag;the originalstate of the carry tlag movesinto the bit Oposition.No

other flags are affeeted.

Example:

RLC A

Bytes:

Cycle=

Encoding:

Operation:

1

1

0011

0011

RLc

(An+ 1)~ (An) n = O –

6

(AO) + (C)

(C) +- (A7)

2-66

intd.

[email protected] PROGRAMMER’S GUIDE AND INSTRUCTION SET

RR A

Functiorx

Description:

Rotate AccumulatorRight

The eight bits in the Aeoumulatorare rotated onebit to the right. Bit Ois rotated into the bit 7 position.No flags are affected.

Example:

RRA

Bytes: cycles:

1

1

Encoding:

Operation:

0000 0011

RR

(An) + (An + 1) n = O – 6

(A7) (AO)

RRC A

Description:

Rotate Aeeumulator Right through Carry flag

The

eight

bits in the Accumulatorand the carry flag are togetherrotated one bit to the right.

Bit O moves into the carry tlag; the originrd value of the carry flag moves into the bit 7 position.No other figs are affected.

Example:

RRC A

Bytes: cycles:

1

1

Encoding:

Operation:

0001

0011

RRc

(An) + (h +

(A7) (C)

(C) + (AO)

1) n = O – 6

2-67

i~e

M(3[email protected] PROGRAMMER~SGUIDE AND INSTRUCTION SET

SETB <bit>

Function:

Set Bit

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

Example:

instructions,

SETE C

SETB PI.O

will leave the carry tlag set to 1 and changethe data output on Port 1 to 35H (OO11O1O1B).

SETB C

Bytes: cycles:

1

1

Encoding:

Operation:

11101

SETB

(c) + 1

10011

SETB bit

Bytes: cycles:

2

1

Encoding:

Operation:

1101

SETB

(bit)+ 1

100101

I

EiEEl

2-68

i~.

[email protected]’S GUIDE AND INSTRUCTION SET

SJMP rel

Function:

Deaoription:

Example:

Bytes:

Cycles:

Short JurnP

Programcontrol branchss unconditionallyto the address indicated.The branch destinationis computedby adding the signed displacementin the second instructionbyte to the PC, after incrementingthe PC twice. Therefore, the range of destinationsallowedis from 128bytes precedingthis instruction to 127bytes followingit.

The label“RELADR” is assignedto an instruction at program memorylocation0123H.The

instruction,

SJMP RELADR will assembleinto location O1OOH.

the value0123H.

(Norc Under the aboveconditionsthe instruction followingSJMPwillbeat 102H.Therefore, another way,an SJMP with a displacementof OFEHwouldbe a one-instructioninfiniteloop.)

2

2

Encoding:

Operation:

1000

100”01

SJMP

(PC) + (PC) +

2

(PC) (PC) + rel

EEl

2-69

[email protected]

SUBB A<sro-byte>

Function:

Deeoription:

Subtract with bOrrOW

SUBBsubtracts the indicated variable and the carry tlag together from the Accumulator, lesvingthe result in the Accumulator.SUBBsets the carry (borrow)tlag if a borrowis needed for bit 7, and cleam C otherwise. (H c was set

bqfors executing

a SUBBinstruction, this neededfor the previousstepin a multipleprecisionsubtraction,so the csrry is subtracted from the Accumulatoralong with the source operand.)AC is set if a borrowis neededfor bit 3, and clearedotherwise.OVis set ifa borrowis neededinto bit 6, but not into bit 7, or into bit 7, but not bit 6.

value is subtracted from a positive value, or a positive result when a positive number is subtractedfrom a negativenumber.

The sourceoperandallowsfour addressingmodes:register,direct, register-indirecLor immediate.

flag is set. The instruction,

SUBB A,R2

SUBB A,Rn

Bytes:

Cycles:

1

1 but OVset.

Notice that OC9Hminus 54H is 75H.The differencebetweemthis and the aboveresult is due to the carry (borrow)flag beingset beforethe operation.If the state of the carry is not known before starting a singleor multiple-precisionsubtraction, it should be explicitlycleared by a

CLR C instruction.

Encoding:

Operation:

I

1001 Irrr

SUBB

(A) (A) - (C) - (IQ

2-70

intel.

MCS”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

SUBB ~direct

Bytes: cycles:

2

1

Encoding:

Operation:

I

1001

0101

SUBB

(A) (A) – (C) – (direct)

I

direct

address

SUBB [email protected]

Bytes: cycles:

1

1

Encoding:

Operation:

I1OO1 IOllil

SUBB

(A) (A) - (C) - ((M))

SUBB A,4$dats

Bytes:

Cycles:

.f

1

Encoding:

Operation:

1001 0100

SUBB

(A) (A) - (C) – #data

I immediate data

SWAP A

Function:

Description:

Swapnibbleswithinthe Accumulator

SWAP A interchange the low- and high-ordernibblea(four-bit fields) of the Accumulator

(bits 3-0md bits 7-4).The operationcan ako be thoughtof as a four-bitrotate instruction.No

flags are affected.

Example:

Bytes:

Cycles:

SWAP A leavesthe Accumulatorholdingthe value 5CH (O1O111OOB).

1

1

Encoding:

Operation:

1100 0100

SWAP

(A3-0)~ (A7-4)

2-71

intd.

XCH Aj<byte>

Function:

Description:

Example:

BxchangeAccumulatorwith byte variable

XCH leads the Accumulatorwith the contents of the indicated variable, at the same time writing the originalAccumulator operand ean w register,direet, or register-indirectaddressing.

source/destination

ROcontains the address20H. The Accumulatorholds the value 3FH (OO1lllllB). Internal

RAM location20H holds the value 75H (01110101B).The instruction,

X3-I A,@RO the accumulator.

XCH

A,Rn

Bytee:

Cycles:

1

1

Encoding:

Operation:

1100

XCH

(A) z ([email protected]

Irrr

XCH A,direct

Bytes:

2

Cycles: 1

Encoding:

Operation:

1100 0101

XCH

(A) z (direet)

XCH

A,@Ri

Bytes: cycles:

1

1

Encoding:

Operation:

1100

XCH

(A) ~ (@))

Olli

I directaddress

2-72

i~.

MCS”-51 programmers GUIDE AND INSTRUCTION SET

XCHD A,@Ri

Funotion:

Exchange

Digit

XCHD exchangesthe low-ordernibbleof the Accumulator(bits 3-O),generallyrepresentinga hexadecimalor BCD digit,withthat of the internal IGUkilocationindirectlyaddressedby the sapp~ti=gister.

me high-ordernibbles(bits 7-4) of each register are not af%cted.No tlsgs

Example:

W location 20H holdsthe value 75H (O111O1O1B).

XCHD A,@RO

Bytes: cycles:

Accumulator.

1

1

Encoding:

Operation:

1101 Olli

XCHD

(A~~) Z ((lti~~))

XRL <cleat-byte>, <src-byte>

Function: Logical

Exclusive-ORfor byte vsriablea

Description:

XRL performs the bitwiselogicalExcIusive-ORoperation between the indicated variables, storing the results in the destination.No flags are affected.

The two operandsallowsixaddressingmode combinations.Whenthe destinationis the Accumulator, the source can use register,direcL register-indirect,or immediateaddressing;when the destinationis a direct address,the source can be the Accumulatoror immediate data.

(Note When this instructionis used to modifyan output port, the value used as the original port dats will be read from the output data latch, not the input pins.)

Example:

the instruction,

XRL A,RO will leavethe Accumulator

holdingthe vatue 69H (O11OIOOIB).

When the destinationis a directly addressedbyte this instructioncan complementcombina-

tionsofbitsin anyMM locationor hardwareregister.Thepatternofbitsto becomplement-

variable

ed by a maskbyte eithera constsntcontainedin the instructionor a at run-time.Theinstruction,

XRL

Pl,#OOllOOOIB will complementbits 5, 4, and Oof output Port 1.

2-73

intJ

MCS”-51 PROGRAMMER’SGUIDE AND INSTRUCTION SET

I(RL A,ml

Bytes:

Cycles;

1

1

Encoding: 0110 Irrr

Operation: XRL

(4+(4 ~ (W

XRL

A,direct

Bytes

Cycles:

2

1

Encoding:

Operation:

10110101011

XRL

(A) + (A) V (direct)

XRL A,@Ri

Bytes:

Cycles:

Enwding:

Operation:

1

1

0110 Olli

] directaddress I

XRL

A,#data

Bytes:

Cycles:

2

1

Encoding: 0110

01001

Operation: XRL

(A) + (A) V #data

XRL [email protected]

Bytes: cycles

2

1

Encoding:

Operation:

0110 0010

XRL

(dinzt) + (direct) V (A)

I immediatedats I direct address

2-74

[email protected]’SGUIDE AND INSTRUCTION SET

XRL [email protected] #date

Bytea:

3

Cydea:

2

Encoding:

Operation:

0110 0011

I

XRL

(direct)+ (direct) Y #data direct address immediate date

2-75

8

Hardware Description

5

3

8051,8052 and 80C51

Hardware Description

CONTENTS

PAGE

CONTENTS

PAGE

INTRODUCTION ........................................ 3-3

Special Function Registers ......................... 3-3

PORT STRUCTURES AND

OPERATION........................................... 3-6

[/0 Configurations....................................... 3-7

Writing to a Port .......................................... 3-7

Port Loading and Interfacing ...................... 3-8

Read-Modify-Write Feature ........................ 3-9

ACCESSING EXTERNAL MEMORY.........3-9

TIMEWCOUNTERS ................................... 3-9

Timer Oand Timer 1.................................. 3-10

Timer 2...................................................... 3-12

SERIAL INTERFACE ............................... 3-13

Multiprocessor Communications .............. 3-14

Serial Port Control Register ...................... 3-14

Baud Rates...............................................3-15

More About Mode O.................................. 3-17

More About Mode 1 .................................. 3-17

More About Modes 2 and 3 ...................... 3-20

INTERRUPTS ........................................... 3-23

Priority Level Structure ............................. 3-24

How Interrupts Are Handled ..................... 3-24

External Interrupts .................................... 3-25

Response Time. ........................................ 3-25

SINGLE-STEP OPERATION.................... 3-26

RESET...................................................... 3-26

POWER-ON RESET................................. 3-27

POWER-SAVING MODES OF

OPERATfON ......................................... 3-27

CHMOS Power Reduction Modes ............ 3-27

EPROM VERSIONS .................................3-29

Exposure to Light...................................... 3-29

Program Memory Locks ........................... 3-29

ONCE Mode ............................................. 3-30

THE ON-CHIP OSCILLATORS ................3-30

HMOS Versions ........................................ 3-30

CHMOS Versions ..................................... 3-32

INTERNAL TIMING .................................. 3-33

3-1

8051, 8052 AND 80C51

HARDWARE DESCRIPTION

INTRODUCTION

the on-chip hardware featuresof the [email protected] Includedin this descriptionare

The port drivers and how they function both as ports and, for Ports Oand 2, in bus operations

The Timer/Counters

The Serial Interface

The Interrupt System

Reset

. The ReducedPower Modesin the CHMOSdevices

The EPROM versionsof the 8051AH, 8052AHand

80C51BH

The devicesunder considerationare listed in Table 1.

As it becomesunwieldyto be constantly referring to each of these devicesby their individualnam~ we will adopt a convcmtionof referring to them genericallyas

8051sand 8052s,unlessa specificmemberof the group is beingreferred to, in which case it willbe specifically named. The “8051s” include the 8051AH, 80C51BH, and their ROMlessand EPROM versions.The “8052s” are the 8052AH,8032AHand 8752BH.

Figure 1showsa functionalblockdiagramof the 8051s and 8052s.

[

Devioe ROMleaa

1

Name

I

Version

8051AH 8031AH

8052AH 8032AH

80C51BH 80C31BH

Table 1.The

MCS-51 Family of Mien

EPROM

Veraion

8751H, 8751BH

8752BH

87C51

ROM

Bytes

4K

8K

4K ontroiiera m

SpecialFunctionRegisters

A map of the on-chipmemoryarea called SFR (SpecialFunctionRegister)spaceis shownin Figure2. SFRSmarked by parentheses are residentin the 8052sbut not in the 8051s.

3-3

i~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

PO.O-PQ.7

P2.O-P2.7

I

I

/

v

I

REG%TER mm?

r

I I [

I

I

I

I

I

Ee

WA

ALE

RST g

I

I

/

‘=

[ –-–––

XTAL1 li~

X7AL2

mmi

DRIVERS

P3,0-P1.7

——————

4&JJ

=

PORTANDTIMER

BLOCKS

I

Figure 1. MCS-51 Architectural Block Diagram

REGISTER

BUFFER

mAo~:AAt

B

INCRE%[email protected] w

PORT3

LATCH

P

Pom3

ORWERS

P3,0-P3.7

. .

—— ——— —,

‘Rddenli. 805s/s0320mJy.

270252-1

3-4

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

8

Bytes

F8

FO

E8

EO lx

Do

C8 m

S8

BO

AS

AO

98

90

88

80

B

ACC

Psw

(T2CON)

I

,,

Ps

IE m

S&N

PI

T&N

Po

1.

(RCAP2L)

I

(RCAP2H)

I

(-m)

,

1

(TH2)

[

,

1

[

I I 1

1 I i

SBUF

I

,

I

I

I

1

I

I

I

,

I

TMOD TLO TL1 THO THI

I

SP DPL DPH

I

Figure 2. SFR Map. (...

) Indicates Resident in 8052s, not in 8051s

1

I

1

PCON

to hold a 16-bitaddress. It may be manimdatedas a id-bit register or as two ind~-dent 8-bit-registers.

Note that not all of the addressesare occupied.Unoccupied addreaaea are not implementedon the chip.

Read accemesto theae addresseawill in general return random [email protected] and write accesseswillhave no effect.

User software should not

write

1s to these unimplemented locations, since they may be used in future

MCS-51producta to invokenew features. In that case the reset or inactive values of the newbits will always be O,and their active values willbe 1.

The fi.mctionsof the SFRSare outlinedbelow.

ACCUMULATOR

ACC is the Accumulator register.The mnemonicsfor

Accmnulator-Speciticinstructions, however, refer to the Accumulatorsimply as A.

B REGISTER

The

B register is used during multiplyand divideoperations.For other instructionsit can be treated as another scratch pad register.

PROGRAM STATUS WORD

The PSWregister contains program

status information as

detailedin Figure 3.

STACKPOINTER

The

Stack

Pointer Register is

8 bitswide.It is incrementedbefore data is stored duringPUSH and CALL executions.Whilethe stack mayresideanywherein onchip RAM, the Stack Pointer is initializedto 07H after a reset. This causes the stack to beginat location08H.

DATA POiNTER

The Data Pointer (IXTR) consists of a high byte

(DPH) and a low byte (DPL). Its intendedftmction is

PORTS O TO 3

PO,Pl, P2 and P3 are

the SFR latches of Ports O,1,2 and 3, respectively.

SERiAL DATA BUFFER

The Serial Data ButTeris actually two separate registers, a transmit butTerand a receive butTerregister.

When &ta is movedto SBUF, it goes to the transmit buffer where it is held for aerial transmission.(Moving a byte to SBUF is what initiatea the transmission.)

When data is moved from SBUF, it comes from the receivebuffer.

BF

B7

AF

A7

9F

97

8F

87

DF

D7

CF c?

FF

F7

EF

E7

TIMER REGiSTERS

Register pairs (THO,TLO), (TH1, TL1), and (TI-D,

TL2) are the id-bit Countingregistersfor Timer/Counters O, 1, and 2, reqectively.

CAPTURE REGiSTERS

The register pair (RCAP2H RCAP2L) are the Capture registetxfor the Timer 2 “Capture Mcde.” In this mode, in responseto a transition at the

8052’sT2EX pin, TH2 and TL2 are copied into RCAP2H and

RCAP2L.

Timer 2 also has

a

16-bitauto-reloadmode, and RCAP2H and RCAP2L hold the reload valuefor this mode. More about Timer 2’s festures in a later section.

CONTROL REGiSTERS

Special Function Registers 1P, IE, TMOD, TCON,

T2CON,SCON,and PC(3Ncontain control and status bits for the interrupt system,the Timer/Count~ and the serial port. They are describedin later sections.

3-5

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

I

(MSB)

CY

I

AC FO Rsl

I

RSO

Ov —

(LSB)

P

1 symbol

PoeJtlOn

CY

AC

PSW.7

Calwflaa.

PSW.6

Ausii~-&yfleg.

FO

RSI

RSO

(For SCD~rafiLWs.)

PSW.5

FlagO

(Availabletofhe uaerforgenersl

Pm-.)

PSW.4

lWater bsnk edectsontrol b~ I &

PSW.3

O.

Set/cleared tyadhssreto dstermineworking mgisterbank (see

Note).

Symbol PoaStlon Name and Slgnifiaanee

Ov

P

PSW.2

Overflow

Psw.1

Uaerd&fneMe flag.

Psw.o

Parifyfleg.

Saflclesred by hardwsm eaeh insfmfion cycle to indicatean odd/ swannumber of “one” bits in the

Aecumulatw, i.e., even parity.

NOTE:

The contents of (RS1, RSO) enable the working register banks as follows:

(0.0)-Bank O

(0.1)-Senk

(1.0)-Bank

(1.1)-sank

1

2

3

(OOH-07H)

(08 H-OFH)

(1OH-17H)

(18H-lFH)

Figure 3. PSW: Program Status Word Register

AODR/OATA

READ

LATCH

INT.BuS

WRITE

TO

LATCH

REAO

PIN

270252-3

2702S2-2

A.

Porf

OBit

P.oon

CONTROL

Vcc

READ

LATCH

B. Port 1 Bit

ALTERNATE

OUTPUT

FUNCTION

INT.BuS

WRITE

TO

LATCH d

REAO

PIN

-.

FUNCTION

270252-4

C.

Port

2 Bit

D. Port 3 Bit

Figure 4.8051 Port Bit Latches and 1/0 Buffers

*See

Figure5

for

detailsof the internal pultup.

PORT STRUCTURESAND

OPERATION

AUfour ports in the 8051are bidirectional.Each consists of a latch (SpecialFunction

Regietera PO through

P3), en output driver, and an input buflkr.

The output driversof Ports Oand 2, and the input butFera of Port O,are used in ameaaesto external memory.

In this application,Port Ooutputs the low byte of the

270252-5

external memory addres3, time-multiplexedwith the byte beingwritten or read. Port 2 outputs the highbyte of the external memoryaddress when the address is 16 bits wide. Otherwisethe Port 2 pine continue

to emit the

P2 SFR content.

All the Port 3 pina,and (in the 8052)two Port 1 pins are multifunctional.They are not onfy port pins, but afao serve the functionsof various special featurea as listed on the followingpage.

3-6

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Port Pin

“P1.o

*P1.1

P3.O

P3.1

P3.2

P3.3

P3.4

P3.5

P3.6

P3.7

Alternate Function

T2

(Timer/Counter2 externalinput)

T2EX(Timer/Counter2

Capture/Reloadtrigger)

RXD (serialinputport)

TXD (serialoutputport)

INTO(externalinterrupt)

~ (externalinterrupt)

TO (Timer/CounterOexternal input)

T1 (Timer/Counter I external input)

~ (externalData Memory write

strobe)

~

(external

DataMemory readstrobe)

●P1.Oand P1.1 serve these aftemate fuctions onlyon the 8052.

The alternate functionscan only be activatedif the correspondingbit latch in the pm-tSFR containsa 1.0therwise the port pin is stuck at O.

ADDIVDATA BUS).To be usedas an input, the port bit latch must contain a 1, which turns off the output driver FBT. Then, for Ports 1, 2, and 3, the pin is pulled high by the internal puflup,but can be pulfed low by an external source.

Port Odiffersin not havinginternsdpullups.The ptiup

FBT in the POoutput driver (seeFigure4) is used onfy when the Port is ernitdng 1s during external memory accasea otherwise the pullupFET is off. Conaequent-

Iy POlima that are being used as output port lines are open drain. Writing a 1 to the bit latch leaves both output FETs off, so the pin floats. In that conditionit can be used a high-impedanceinput.

BecausePorts 1, 2, and 3 have fixed internaf pullups they are sometimescalled “qussi-bidirectional”porta.

Whets eontigured as inputs they pull high and will sourcecurrent (IIL, in the data sheets)whenextemafly pulled low. Port O, on the other hand, is considered

“true” bidirectional,[email protected] as an input it floats.

Affthe port latches itsthe 8051have 1swritten to them by the reset function.If a Ois subsequentlywritten to a port latch, it can be reconfiguredas an input by writing a 1 to it.

1/0 Configurations

Figure 4 shows a fictional diagram of a typical bit latch and 1/0 buffer in each of the four ports. The bit latch (one bit its the port’s SFR) is represented as a

Type D tlipflop, which will clock in a value from the internal bus in response to a “write to latch” signal from the CPU. The Q output of the tlipflop is placed on the intersttdbus its responseto a “read latch” signal from the CPU. The levelof the port pin itself is placed on the internal bus in response to a “read pin” signal from the CPU. Someinstructionsthat read a port activate the “read latch” signal, and others activate the

“read pin” signal.More about that later.

Writingto a Port

In the executionof an instructionthat changesthe value in a port latch, the new value arrives at the latch during S6P2of the final cycleof the instruction. However, port latches are in fact sampledby their output buffers

O~Y

during Phase 1 of SSlyclock period. @IKittg Phase 2 the output buffer holds the value it saw during the previous Phase 1). Consequently,the new value in the port latch won’t actually appear at the output pin until the next Phase 1,whichwillbe at SIP1 of the next machinecycle.SeeFigure39 in the Internal

Timingsection.

As shownin Figure4, the output drivers of Ports Oand

2 are switchableto an istternrdADDR and ADDR/

DATA bus by an internal CONTROLsignalfor w its external memoryaccesam.During external memoryaccesses,the P2 SFR rcsrm“nsunchanged,but the POSFR gets 1s written to it.

Nso shownin Figure4, is that ifa P3 bit latch contains a 1, then the output level is controlled by the signal labeled “alternate output function.” The actual P3.X

pin levelis afwaysavailableto the pin’salternate input function, if any.

Ports 1,2, and 3 have internal puUups.Port Ohas open drain outputs.Each I/O line ean be independentlyused as an input or an output. (Ports O and 2 may not be used as general purpose I/O whetsbeing used as the

3-7

If the changerequiresa O-to-1transitionin Port 1,2, or

3, art additional pullup is turned on during SIP1 and done to increasethe transition speed.The extra pullup can sourceabout 100timesthe current that the normal pullup can. It shouldbe noted that the internal pttllups are field-effecttransistors, not linear resistors.Tlseptdlup

-CInCntS are

shownin Figure 5.

In HMOS veraionsof the 8051,the fixed part of the pullup is a depletion-modetransistor with the gate wiredto the source.This transistorwillallowthe pin

to

source about 0.25 mA when shorted to ground. In parallel with the fixed pullupis assenhancement-mode transistor, which is activated during S1 wheneverthe port bit doesa O-to-1transition.Duringthis intervaf,if the port pin is shorted to ground,this extra transistor will allowthe pin to sourcean additional30 sttA.

intd.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Vcc

Vv,,

A.

HMOS Configuration. The enhancement mode transistor is turned on for 2 OSC.periods after~ makes a O-to-1 transition.

‘JCc

WC

%c

270252-6

2 OSC.PERIODS

PI b n

1’‘

6 D

FROMPORT

LATCH

=-’@-’@

D-J

“AD

PORTPIN

B. CHMOS Configuration. pFET 1 is turned on for 2 OSC.periods after~ makes a O-to-1transition. During this time, pFET 1 also turns on pFET 3 through the inverter to form a latch whioh holds the 1. pFET 2 is also on.

270262-7

Figure 5. Porta 1 And 3 HMOS And CHMOS Internal Pullup Configurations.

Port 2 is Similar Exoept That It Holds The Strong Pullup On While Emitting

1s That Are Address Bits. (See Text, “Acceaaing External Memory”.)

In the CHMOS versions,the pullup consists of three

DFETs. It shordd be noted that an n-channel FET

@ET) is turned on wherea logical 1 is applied to its gate, and is turned off whena logicalOis appliedto its gate. A p-channelFET (pFET) is the opposite:it is on when its gate seesa O,and off when its gate sees a 1.

pFETl in Figure5 is the transistor that is turned on for

2 oscillatorperiodsafter a O-to-1transition in the port latch. While it’s on, it turns on PFET3 (a weak pull-

UP),throughthe inverter.This inverterand pFET form a latch whichhold the 1.

Note that if the pin is emittinga 1, a negativeglitch on the pin from someexternal sourceean turn off PFET3, causingthe pin to go into a float state. pFET2 is a very weak pullup whichis on wheneverthe nFET is off, in traditional CMOSstyle.It’s onlyabout ‘/10the strength of pFET3. Its functionis to restorea 1 to the pin in the event the pin had a 1 and lost it to a glitch.

Port

Loadingand Interfacing

The output buffersof Porta 1,2, and 3 ean each drive4

LS TTL inputs. These porta on HMOSversionscan be drivenin a normal manner by any ITL or NMOS cirenit. Both HMOS and CHMOS

@lS can be dliVell

by open-collectorand open-drainoutputs, but note that Oto-1transitions will not be fast. In the HMOSdevi~ if the pin is driven by an open-cdleetor output, a O-to-1 transition will have to be drivenby the relativelyweak depletionmode FET in Figure 5(A). In the CHMOS device,sssinput OtllmSOffpldklppFET3, kwislg

Only the very weak

pullup pFET2 to drive the transition.

In external bus mode, Port Ooutput buffers can each drive8 L3 ITL inputs. As port pins,they require external pultups to drive any inputs.

3-8

i~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Read-Modify-WriteFeature

Someinstructions that read a port read the latch and others read the pin. Whichonesdo which?The instructionsthat read the latch rather than the pin are the ones that read a value possiblychangeit, and then rewrite it to the latch. These are called “read-modify-write”instructions.The instructionslisted beloware read-modify-writeinstructions. When the destinationoperand is a wrt, or a PII bit, these instructions read the latch rather than the pin:

ANL

ORL

(logicalAND, e.g., ANL PI, A)

(logicalOR, e.g., ORL P2, A)

XRL

JBC

CPL

INC

DEC

DJNZ

(logicalEXIOR,e.g., XRL P3, A)

(jump if bit = 1 and clear bit, e.g.,

JBC P1.1, LABEL)

(complementbit, e.g., CPL P3.0)

(increment,e.g., INC P2)

(decrement,e.g., DEC P2)

(decrernent and jump if not zero, e.g.,

DJNZ P3, LABEL)

MOV,PX.Y, C (movecarry bit to bit Y of Port X)

CLR PX.Y

(clear bit Y of Port X)

SETBPX.Y

(set bit Y of Port X)

It is not obviousthat the fast three instructions in this list are read-modify-writeinstructions, but they are.

Theyread the port byt%all 8 bits, modifythe addressed bit, then write the new byte back to the latch.

The reason that read-modify-writeinstructions are directed to the latch rather than the pin is to avoid a possiblemisinterpretation of the voltage level at the pin. For example,a port bit mightbe used to drive the base of a transistor. When a 1 is written to the bit, the transistor is turned on. If the CPU then reads the same port bit at the pin rather than the latch, it will read the base voltage of the transistor and interpret it as a O.

Reading the latch rather than the pin will return the correct vafue of 1.

ACCESSING EXTERNAL MEMORY

Accessesto external memoryare of two types: accewes

to

external Program Memoryand amesaes to external

Data Memory. Accessesto external program Memory use signal PSEN (program store enable) as the read strobe. Accesses to external Data Memory use ~ or

~ (alternate functionsof P3.7and P3.6) to strobe the memory.Refer to Figures36through38 in the Internal

Tintingsection.

Fetches from externrdProgram Memory always use a

16bit address. Accessesto external Data Memory can use either a l~bit address (MOVX @DPTR) or an

8-bitaddress (MOVX @w).

3-9

Whenevera id-bit addressis used, the high byte of the address comes out on Port 2, where it is held for the duration of the read or write cycle.Note that the Port 2 drivers use the strong pullups during the entire time that they are emittingaddress bits that are 1s. This is duringthe executionof a [email protected]

Duringthis time the Port 2 latch (the SpecialFunction

Register)does not haveto contain 1s,and the contents of the Port 2 SFR are not modified,If the external memory cycle is not immediatelyfoflowedby another external memorycycle,the undisturbedcontentsof the

Port 2 SFR will reappearin the next cycle.

If an 8-bit address is being used (MOVX @Ri), the contents of the Port 2 SFR remain at the Port 2 pins throughoutthe externafmemorycycle.This will facilitate paging.

In any case, the low byte of the address is time-mukiplexed with the data byte on Port O. The ADDR/

DATA signal drives both FETs in the Port O output buffers.Thus, in this applicationthe Port Opins me not open-drainoutputs, and do not require external pullups. Signal ALE (Address Latch Enable) shoufd be usedto capture the addressbyte into an external latch.

The address byte is valid at the negativetransition of

ALE. Then, in a write cycle,the data byte to be written appears on

Port Ojust brrm ~ is

activated,and remains there until after WR is deactivated. In a read cycle, the incomingbyte is accepted at Port Ojust before the read strobe is deactivated.

Duringany accessto externalmemory,the CPU writes

OFFHto the Port Olatch (the SpecialFunction Register), thus obliteratingwhateverinformationthe Port O

SFR may havebeenholding.If the user writeato Port O during an external memory fetch, the incomingcode byte is corrupted. Therefore,do not write to Port O if external program memoryis used.

External Program Memoryis amessedunder two conditions:

1) Wheneversignal= is active; or

2) Whenever the program counter (PC) contains a number that is larger than OFFFH(WFFH for the

8052).

This requiresthat the ROMleasversionshave~ wired

lowto enablethe lower4K (8Kforthe 8032)program

bytes to be fetched from extemafmemory.

When the CPU is executingout of external Program

Memory,all 8 bits of Port 2 are dedicatedto an output fimctionand may not be used for generalpurposeI/O.

During external program fetches they output the high byte of the PC. Duringthis time the Port 2 drivers use the strong pullups to emit PC bits that are 1s.

TIMER/COUNTERS

The 8051has two 16-bitTimer/Counterregisters:Timer O and Timer 1. The 8052 has these two plus one

int&

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

more:Timer 2. AUthree can be ccmflgurecito operate either as timers or event counters.

In the “Timer” function, the register is incremented everymachinecycle.Thw onecan think of it as countingmachinecycles.Sincea machinecycleconsistsof 12 oscillatorperiods,the count rate is 1/,, of the oscillator frequency.

In the “Counter” timction, the register is incremented in responseto a l-to-Otransition at its corresponding externrdinput pin, TO,T1 or (in the 8052)T2. In this timction,the

externalinput

is sampledduring S5P2of everymachine cycle.When the samplesshowa high in onecycleand a lowin the nextcycle,the countis incremented. The new count value appeara in the register duringS3P1of the cyclefollowingthe one in whichthe transitionwas detected.Sinceit takes 2 machinecycles

(24 oscillator periods)to recognizea l-to-Otransition, the maxiMuMcount rate is 2/24of the oaciliator frequency.There are no restrictions on the duty cycle of the external input signaf, but to ensure that a given level is sampled at least once before it changes, it shouldbe held for at least one full machinecycle.

In addition to the “Timer” or “Counter” selection,

Timer Oand Timer 1 have four operatingmodesfrom whichto select. Timer 2, in the 8052,has three modes of operation: “Capture,“ “Auto-Relrxid”and “baud rate generator.” four operatingmod- which are selectedby bit-pairs

(M1. MO)in TMOD. Modes O, 1, and 2 are the same for both Timer/Counters.Mode 3 is different.The four operatingmodesare describedits the followingtext.

MODEO

EitherTimerin Mode

O is an 8-bit Counter with a divide-by-32preacaler. This 13-bit timer is MCS-48 compatible.Figure 7 showsthe Mode Ooperationas it appliesto Timer 1.

In this mode, the Timer regiater is configured as a

13-Bitregister.As the count rolls over fromail 1sto ail

0s, it sets the Timer interrupt flag TF1. The cmnted input is enabledto the Timer whenTR1 = 1and either

GATE = Oor ~ = 1. (SettingGATE = 1 aflows the Timer to be controlledby externafinput INT1, to facilitate pulse width measurements.)TRl is a control bit in the SpeciafFunction Register TCON (Figure 8).

GATE is in TMOD.

The 13-Bitregister consistsof ail 8 bits of THl and the lower 5 bits of TL1. The upper 3 bits of TLl are ittdeterminate and shouIdbe ignored. Settingthe run flag

(’TR1)doesnot clear the registers.

ModeOoperationis the same for Timer Oas for Timer

1. SubstituteTRO,TFOand ~ for the corresponding Timer 1 sigmdsin Figure 7. There are two dif%rent

GATE bia one for Timer 1 (TMOD.7) and one for

Timer O(TMOD.3).

TimerOand Timer 1

TheaeTimer/Counteraarepreaent in both the 8051and the 8052.The “Timerr’or “Counter” functionis aelected by control bits Cfl in the SpeciaiFunctionRegister

TMOD (Figure 6). These two Timer/Countem have

MODE 1

Mode

1 is the same as Mode O,except that the Tima registeris beingrun with all 16bits. -

(MSB)

GATE C/T I Ml I MO I GATE

A

Timer 1

WI o cmlywhilempin set

“7Rx” is hiohand “TRx’”mntrol pin is

When

Timaf “x” is anabledwharfaver

eontrolbitkeat.

Timaror CounterSalaetor daaradfor Timer opwstiOn

(inwtfromifttmelwetafn

Won ebek). sattorcountar

(inputfrom “Tx” inputpin).

o

1

1

1

C/7 I Ml

(LSB)

MO

MO

0

0

1

1

Timer O

1

Opamtfng Mode

S-bitlimar/@ntar’’THX” with .<TIJ,, as ~it prese%r.

IS-bil T!mar/Ccunter 4“THx’,and 4.TIX am cascadad; there is no ~r.

S-bitauto-reloadTimSr/~ntar “THx” holdsa value whichis toba reloadad info“TLx” asch time it OYWIIOWS.

(i_knwO)TLOisanS-bitTimer/Counter mntrolled by the [email protected] Timar Ocontrolbti.

isanB-bit

Ms.

flimerl) 7imer/Ccunter 1 stcopad.

Figure

6.

TMOD: Timer/Counter Mode Control Register

3-1o

i~.

Osc

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

[A I

INTERRUPT

ICOJTROL’(5%

270252-9

Figure 7. Timer/Counter 1 Mode O:13-Bit Counter

[

(MSB]

TFl TRl TFo TRO IE1 IT1 IEO

(LSB)

ITO symbol

POaltlon

TF1 TCON.7

TR1

TFo

TRO

TmN.6

TCON.5

TCON.4

[email protected] llner 1 overflowFlag. Set by hardware on Tw/Counter overflow.

Cleared byherdwerewtten procveetorsto intemuptroutine.

l%ner 1 Run eontml biLSet/cleared by sottwsreto tum Tkn6f/Counte?WI

off.

Timer Oovsrfiow Flag.Set by herdwsreon Timef/Camter overflow.

Cleared byhsrdware whan pmmee.or

veetorsto intemuptmutine.

Timer O Runcontml ML SatJcleared byeoftwareto tum Timer/Counter on/ off,

-1

IE1

IT1

IEO

ITO

Posltlon

Tc%+J.3

TCON.2

TU)N.1

TCON.O

Neme mdslgnlffcenm

Interrupt1 Edgs flsg. Sstbyhardwsre when external intenupt~ge deteeted. Cfesmdwhen interrupt prmeesed.

Intenupt 1 Type mntrd bk Set/ elearadbyaofttnr etoapecifyfsiiing sdgdbw level biggwadesternel interrupts.

lntenuptO Edgsfleg. Set byhsrdwsre when external intsfruptedge detected. Cleared * interrupt

~.

InterruptOTyPSmntrol biL Set/ cleared by sdtwereto speeifyfslling [email protected] [email protected] interrupt

Figure 8.TCON: Timer/Counter Control Register

MODE 2

Timer O in Mode 3 establieheaTLOand THOas two separate counters.The logicfor Mode 3 on Timer Ois

Mode2 configures in Figure10.TLO&estheTimerOcontrolbits: ter

(’TLl)with

automatic reload, as

shownin Figure 9.

OverfiowfromTL1 not only sets TFl, but also reloads

Cfi, GATE,TRO,INTO,and TFO.THOis lockedinto a timer function

(counting machine

cycles)and takes

TL1 with the contentsof THl, which is preset by aoftware. The reload leav~ THI unchanged.

over the useof TR1 and TFl fromTimer 1.Thus THO now controlsthe “Timer 1“ interrupt.

Mode 2 operationis the same for Timer/Counter O.

MODE 3

Timer 1 in Mode3 simplyholds its count.The effeet is the ssrne as setting TRl = O.

3-11

Mode 3 is providedfor applicationsrequiringan extra

8-bit timer or counter. With Timer o in Mode 3, gIL

8051ean

looklike it has three Timer/Counte~ and an

8052, like it has four. When Timer O is in Mode 3.

Tim~ 1 een be tinned on and off by switchingit out of and into its own Mode 3, or esn still be used by the serial DOrtae s baud rate mnerstor, or in fact, in

any

appli~tion not requiring& iaterru~t.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

CIT. o

.,

PINJ*”

M

INTERRUPT

270252-10

Figure9. Timer/Counter1

Mode 2: 8-Bit

Auto-Reload

EI--EI-’’”SC”SC

11121~’~

.PIN~fi=l

I

/t

1 ‘

CONTROL

INTERRUPT

1/12 1“’~

Id’

~

I CONTROL

_ INTERRUPT

270252-11

Figure 10. Timer/Counter OMode 3: Two 6-Bit Countere

Timer2

Timer 2 is a 16-bit Timer/Counter which is present only in the 8052.Like Timers Oand 1, it can operate either as a timer or as an eventcounter. Thisis selected by bit Cm in the SpecialFunction Register T2C0N

(Figure 11).It haa three operating modes: “capture,”

“autdoad”

and “baud rate generator,” which are se-

lectedbybitsin T2CONas shownin Table2.

Table 2. Timer 2 Operating Modea

IRCLK + TCLKlCPI~lTR21

o

o

1

Mode

0

1 16-bitAuto-Reload

1

1 16-bitCapture

x 1

Baud Rate Generator

3-12

i~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

(MSB)

TF2 EXF2

I

RCLK TCLK EXEN2

I

TR2 cm

(Lss) cPlm

1

TF2

EXF2

RCLK

TCLK

EXEN2

TR2

CII’2 cP/m

T2CX3N.7

T2CON.6

T2CON.5

T2CON.4

T2CON.3

T2mN.2

T2CZ)N.1

T2c0N.o

Named Signllkenw

Timer 20vedlowflag ~bya Tiir2 ovarflowand mustbe cleeredbyaoffwara.

TF2will not be astwtsen [email protected] = 1 orTCLK = 1.

limer2exfemal flag eetwheneifhar a eapfura orraload iseaumd bya negative t~SifiOn on T2EX and EXEN2 = 1. When Tirrwr2 interruptiaenablad, EXF2 = 1 will eauaafha CPU toveeforte tha T}mer2 intarruptrwtine. EXF2 must be cfeared trysoftware.

Raeeivecloek ffsg.When eat, eausesthe aerfal porttouee Tirnw2 overflow pulseaforits raceiva clookin Modaa 1 and 3. RCLK = Oeauaaa Timer 1 ovarlfow to be @ ferfha raeeive Clock.

Transmitclock flag.Whenaat, eaueeethe aafisl port to uee Timw2 overflow puleeafwitat ranemit deck in modes 1 and 3. TCLK = O caueeaTmer 1 overflcws to ba uaad for fhefranamif deck.

Tirnar2 external enebleffag. When set, allows aeapfure o+raleedtoooeures a result ofa negativatranaifiemon T2EX ifllnar2 is not beinguaadto eiockthe til PM. EXEN2 = Ocausea Timar2 to ignoreevenfset T2EX.

Start/atop cmItrolfor Timar2. A logic 1 afarta Usatimer.

Timarorcountaraalect flimer2)

O = Internaltimar (OSC/12)

1 = ~1 event muntar (fallingedgetrfggered).

Captwe/RaloadflW.

Wheneet ~tureawillr rccuronnagstivet renaifions et

T2EX if EXEN2 = I.When eiaarad, aufo.ralosdswill occuraifherwithTimer2 overflowsor nSgatiVetranaifiorreatT2EX wlwn EXEN2 = 1. When eifher RCLK

= 1 or TCLK = 1, this bfi is ignciad and the timer is foreed foeute-rafoedem

Timar20verflew.

-.

. . ———-..

—.

.-

Figure 11. TZCON: Timer/Counter 2 Control

Register

In the Capture Mode there are two options which are selected by bit EXEN2 in T2CON. If EXEN2 = O, then Timer 2 is a Id-bit timer or counter which upon overtlowingeeta bit TF2, the Timer 2 overflowbit, which can be used to generatean interrupt. If EXEN2

= 1, then Timer 2 still does the above, but with the added feature that a l-to-Otransition at external input

T2EX causesthe current valuein the Timer 2 registers,

TL2 and TH2, to be captured into registers RCAP2L and RCAP2H, respectively.(RCAP2L and RCAP2H are new Special Function Registers in the 8052.) In addition, the transition at T2EX causes bit EXF2 in

T2CON to be set, and EXF2,like TF2, an generateen interrupt.

The Capture Modeis illustrated in Figure 12.

In the auto-reloadmcdethereare againtwo options,

which are selected by bit EXEN2 in T2CON. If

EXEN2 = O,then whenTimer 2 rolla over it not only sets TF2 but also causes the Timer 2 registers to be reloaded with the l~bit va2uein registera RCAP2L and RCAP2H,whichare presetby software.If EXEN2

= 1, then Timer 2 still does the above, but with the added feature that a l-to-o transition at external irmfrt

T2EX will alaotrigger the id-bit reload and set E&2.

The auto-reloadmede is ilfuetratedin Figure 13.

The baud rate generatormodeis selectedby RCLK =

1 and/or TCLK = 1.

Itwill describedin ecmjunction with the aerial port.

SERIAL INTERFACE

The seriaf port is full duplex,meaningit can transmit and receive eimultarseously.It is aleo receivebutTered, meaning it can commencereception of a second byte before a previouslyreceivedbyte has beersresd

from

the reeeive register. (However,if the tirat byte still

hasn’tbeenreadby the time receptionof the second

byte is completq one of the bytes wilf be lost). The serial port receive end transmit registers are both acceeaedat SpeeialFunctionRegister SBUF.Writing to

SBUF loada the transmit register, and reading SBUF aeceeeeaa physieaflyseparatereceiveregister.

3-13

irrtd.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Sxlins

270252-12

Figure

12. Timer

2

in Capture

Mode

The serial port can operatein 4 modes:

Mode O: Serial date enters end exits through RXD.

TXD outputs the shift clock.8 bits are tranamittext/received:8 date bits (LSBftrat).The baud rate is tixed at

1/12 the oscillator frequency.

- Mode 1: 10bits are transmitted (through TXD) or received(through RXD): a start bit (0), 8 data bits (LSB first), and a stop bit (l). On receive+the stop bit goes into RB8 in Special Function Register SCON. The baud rate is variable.

Mode 2: 11 bits are transmitted (through TXD) or received(through RXD): a start bit (0), 8 data bits (LSB fret), a programmeble 9th data bit, and a stop bit (l).

On Transmit, the 9th data bit (TB8 in SCON)can be eaaignedthe valueof Oor 1.Or, for example,the parity bit (P, in the PSW) coufdbe moved into TB8. On receive,the 9th data bit goesinto RB8 in SpecialFuncton

RegisterSCON,whilethe stop bit is ignored.The baud rate is programmableto either ‘/”2or ‘\e4the oscillator frequency.

Mode 3: 11bits are transmitted (through TXD) or received(through IUD): a start bit (0), 8 data bits (LSB first), a programmable9th data bit and a stop bit (l). In fac~ Mode

3 is thesamees

Mode

2 in

all reapeeta except the baud rate. The baud rate in Mode 3 is veriable.

In all four modes, transmissionis initiated by any instruction that uses SBUFes a destinationregister.Reception is initiated in ModeOby the conditionRI = O and REN = 1. Reception is initiated in the other modesby the incomingstart bit if RBN = 1.

MultiprocessorCommunications

Modes 2 end 3 have a special provisionfor muMproceasorcommunications.In these mod- 9 data bita are received.The 9th one goea into RB8. Then comes a stop bit. The port can be programmedsuch that when the stop bit is received,the aerialPrt interrupt will be activated only if RB8 = 1. This feature is enabled by setting multiprocessorsystems is 22folfows.

Whenthe master proceaaor wantsto trananu“ta blockof data to one of several slaves, it firat sends out an address byte which identifiesthe target slave.An address byte differsfroma data byte in that the 9tb bit is 1in en eddress byte and Oin a data byte.With SM2 = 1, no slave will be interrupted by a date byte. An eddreas byte, however, will interrupt elf slav= so that each alevecan exsmine the receivedbyteend see ifit is being eddreaaed.The addressed slave will clear ita SM2 bit end prepare to remive the data bytesthat will be coming. The slaves that

SM2Sset and go on about their business,ignoringthe comingdata bytes.

SM2 has no effect in Mode O,and in Mode 1 can be used to check the validityof the stop bit. In a Mode 1 reception,ifSM2 = 1,

[email protected] interruptwillnotbe

activated unlessa vatid atop bit is received.

SerialPortControlRegister

The serialport control end status registeris the Speciaf

Function Register SCON, shown in Figure 14. This register mntains not only the mode selectionbits, but also the 9th data bit for transmit and receive(TB8and

RB8), and the aerial port interrupt bits (TTand RI).

3-14

intd.

l++

+12

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

TR2 nEmAO

-R 2 llslEmnlWr

Max PfN axaNa

Figure 13. Timer 2 in Auto-Reload Mode

270252-13

(MSB)

SMO SM1 SM2

REN I TB8 I RSS ] n I

(LSB)

RI

Where SMO, SM1 epeeify the aefial pommode, as follows:

SMO aMl s

o o

1

1

SM2

REN

0

1 o

1 mode

0

1

2

Deeerfpnorl

Shiftragiatar

S-bifUART

9-bit UART

Scud Rate f=flz vadable f-/s4

9-btuARTvenable or f=,/32

3 enebleethe muftipromaeor communieatfonfeature in Modes 2 and 3.InM*20r3, if SM2isaetto

1 than RI will not baactf.mtad if the received 3th date bit (R*) iaO. In

Mode 1, if SM2 = 1 then RI will not baatited ifavalid stop bhwea not recefvad. In Mode O,SM2 ahouldbe o.

enableeaeriel reqstion. %by eoftwareto enable raoaption.Clear

byeoftwaretodieeble raee+stkm

TSS

RSS

TI

RI ie the Sthdate bifthetwill be bansin Modaa2 end3. % or dear byaoftwareaa rtaairad.

in Modes 2and 3, iatha Sthdata bit thatwes received. In Mode 1, ifSM2

= O, RSS iethe atopbitthet wea received. In MOdeO,RS3 is rrotuaed.

iewenemif irstarruptflag.Set by hardsrareatthe end ofttw8th bittime in M*O, oratthe beginningof the

*P bit in the offwrrnodes,in any aerieffmnamieaion.Muetbecleared

byaoftware.

is receive irsferruptflag.Sat by herdware atthe end of thesth bit time in Mode O,or helfweythrcrughthe atop b4ttirrwin the other modes,in any serial recefdkm (exoepta8a SM2).

Muaf be Cia byeoftwere.

—.

.

----. . — — —

Figure 14. SCON: Serial Port Control Register

The baud rate in Mode Ois tlxed:

Mode 2

2SMOD

BaudRate= ~X(Oscillator

Frequency)

OscillatorFrequency

ModeOBaud Rate =

12 In the 8051.the baud ratea in Modes1 and 3 are deter-

The baud rate in Mode 2 dependeon the value of bit minedby the Timer 1 overflowrate. In the 8052,these baud ratea earsbe determinedby Timer 1, or by Timer

SMODin SpecialFunction RegisterPCON. If SMOD

2, or by both (one for transmit end the other for re-

= O(whichis the valueon reset),the baud rate % the eeive).

oaeillatorfrequency.If SMOD = 1, the baud rate ie

%2 the oscillatorfrequency.

3-15

i~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

UsingTimer

1 to Generate Baud Rates

When Timer 1 is used as the baud rate generator, the baud rates in Modes 1 and 3 are determined by the

Timer 1 overflowrate and the valueof SMOD as follows:

ModesL 3

2SMOD

BaudRate = —

32

X (Timer 1OverflowRate)

The Timer 1 interrupt shouldbe disabledin this application. The Timer itself can be configuredfor either

“timer” or “cormter” operation, and in any of its 3 running modes. In the most typioaiaprdication~ it is contl~ed for “timer” operati6n, in ‘the auto-reload the baud rate is givenby the formula

Modes 1, 3 2SMOD~ OscillatorFrequency

BaudRate = —

32 L% [256-

(THI)I

One ean achievevery low baud leavingthe Timer 1 interrupt enabl~ and mntlguring the Timer to run as a 16-bit timer (hish nibble of do a lti-bit softwarereload.

Figure 15 lists variouseommordyused baud rates and how they can be obtsined from Timer 1.

I

Saud Rate

I

f~c SMOD

Mode OMax:1 MHZ 12 MHZ

Mode2 Msx:375K 12 MHZ

Modes 1,3: 62.5K

19.2K

12 MHZ x

1

1

11.059 MHZ 1

9.6K

4.8K

11.059 MHZ

11.059 MHZ o o

2.4K

1.2K

137.5

110

110

11.059 MHZ o

11.059 MHZ o

11.986 MHZ o

6 MHZ

12 MHZ o o

Cfl

T

0

0

0

0 x o

0

0

0

0

Timer

1

Mode

Reload

Value

2

2

2

1

2

2

2

x x

2

2 x x

FFH

FDH

FDH

FAH

F4H

E8H lDH

72H

FEEBH

Figure 15.Timer 1 Ganerated Commonly Ueed Baud Rates

Using Timer 2 to Generate

SaudRates

11).

Note then the baud rates for transmit and reoeive can be simultaneouslydifferent.SettingRCLK and/or

In the 8052,Timer 2 is selectedas the baud rate generaTCLK puts Timer 2 into its baud rate generatormode, tor by setting TCLK rind/or RCLKin T2CON (Figure as shownin Figure 16.

piol?:lxcmm ls-

Svam’rlz r=

““-=’

L.z.———

-—

Inm Mm

.,”

. ,,

--

.W,

+2 r+l

“ i

---amo

“o-

---

-----k.

+,’ mx-

‘1’ XCLOCK

270252-14

Figure 16. Timer 2 in Saud

RateGeneratorMode

3-16

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

The baud rate generatormode is similar to the auto-reloadmcde, in that a rolloverin TH2 causesthe Timer 2 registerstObe reloadedwith the Id-bit vahsein registers

RCAP2Hand RCAP2L,which are preset by software.

Now, the baud rates in Modes 1 and 3 are determined by Timer 2’soverflowrate as follows:

Modes 1,3 BaudRate =

Timer 2

@clfiow Rate

16

The Tim= can be configured for either “timer” or

“counter” operation.In the most typicalapplications,it is configuredfor “timer” operation(C/T2 = O).“Timer” operationis a fittle different for Timer 2 when it’s being used as a baud rate generator. Normally, as a timer it wouldincrement every machine cycle(thus at

Y,, the

mdlator

frequency).

baud rate generator, however,it incrementsevery state time (thus at ~, the oscillatorfrequency).In that case the baud rate is given by the formula

Mcdes 1,3

OscillatorFrequency

‘aud ‘te = 32x [65536– (RCAP2H,RCAP2L)1 where (RCAP2H, RCAF2L) is the content of

RCAP2H and RCAP2L taken as a Id-bit unsignedinteger.

Timer 2 as a baud rate generatoris shownin Figure 16.

This Figure is valid only if RCLK + TCLK = 1 in

T2CON.Note that a rolloverin TH2 doesnot set TP2, and willnot generatean interrupt. Therefore,the Timer

2 interrupt doesnot have to be disabledwhenTimer 2 is in the baud rate generator mode. Note too, that if

EXEN2 is set, a l-to-O transition in T2EX will set

EXF2 but will not cause a reload from (RCAP2H,

RCAP2L)to (TH2,TL2). Thus whenTimer 2 is in use as a baud rate generator,T2EX can be usedas an extra external interrupt, if desired.

It shouldbe noted that when Timer 2 is running(TR2

= 1) in “timer” function in the baud rate generator mod~ one shouldnot try to read or write TH2 or TL2.

Under these conditionsthe Timer is beingincremented everystate time, and the results of a read or write may not be accurate.The RCAP rcgistm may be read, but shouldn’tbe written to, becausea write mightoverlapa reload and cause write and/or reload errors. Turn the

Timer off (clear TR2) before ruessing the Timer 2 or

RCAP registers,in this case.

MoreAboutModeO

puts the shifl clock. 8 bits are tranarnitted/received:8 data bits (LSBfwst).The baud rate is fixedat !/,2 the oscillatorfrequency.

Figure 17showsa simplifiedfunctioneddiagramof the serial port in ModeO,and associatedtiming.

Trsnamissionis initiated by any instruction that uses

SBUF as a destinationregister. The “write to SBUF’ signalat S6P2also loadsa 1 into the 9th positionof the transmit shift registerand tells the TX Controlblockto commencea transmission.The internal timing is such that one till machine cycle will elapse between“write to SBUF,” and activationof SEND.

SEND enables the output of the shift register to the alternate output functionline of P3.0, and sdsoenables

SHIFf CLOCKto the alternate output functionline of

P3.1. SHIPT CLOCK is

low

during S3, S4, and S5 of everymachinecycle,and high during S6,S1and S2.At

S6P2of everymachinecycle in which SEND is active, the contents of the transmit shift register are shiftedto the right one position.

As data bits shift out to the right, zeroescomein from the left. Whenthe MSBof the data byte is at the output positionof the shift register, then the 1that was initial-

Iy loaded into the 9th position,is just to the left of the

MSB,and all positionsto the left of that containzeroes

This condition flags the TX Control block to do one last shitl and then deactivateSEND and set TL Bothof these actions occur at SIP1 of the loth machinecycle after “write to SBUF.”

Receptionis initiated by the condition REN = 1 and

R1 = O.At S6P2 of the next machine cyclq the RX

Control unit writes the bits 11111110to the receive shift register,and in the next clock phaseactivatesRE-

CEIVE.

RECEIVE enables SHIFT CLOCK to the alterstate output function line of P3.1. SHIIW

CLOCK makes transitions

at S3P1 and S6P1 of every machine cycle.

At S6P2of everymachinecycle in which RECEIVEis active,the contentsof the receiveshift registerare shifted to the left one position. The value that comes in from the right is the vrduethat was sampledat the P3.O

pin at S5P2of the same machine cycle.

As &ta bits comein from the righL 1sshift out to the left. When the Othat was initiallyloadedinto the rightmost positionarrivesat the leftmostpositionin the shift register, it flags the RX Control block to do one last shift and load SBUF. At SIP1 of the Klth machine cycle after the write to SCON that cleared RI, RE-

CEIVE is cleared and RI is set.

3-17

MoreAboutMode 1

Ten bits are transmitted (through TXD), or received

(through RXD): a start bit (0), 8 data bits (LSBtirst), and a stop bit (l). on receive, the stop bit gces into

RBg in SCON.In the 8051the baud rate is determined by the Timer 1 overflowrate. In the 8052it is determinedeither by the Timer 1 overtlowratej or the Timer

2 overtlowrate or both (one for transmit and the other for receive).

Figure 18 showsa simplitlsdfunctionaldiagramof the serial port in Mode 1, and associatedtimingsfor trsns-

mit

receive.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

WRITE

TO

SBUF

Tx CONTROL

SHIFT

REN

R

26

SERIAL

PORT

INTERRUPT

REAO

SBUF

~T”

u

I

SeuF

1

RXD

PS.OALT

OUTPUT

FUNCTION

RX(I

. . ...

INPUT

FUNCTION l-m

P3.1 ALT

OUTPUT

FUNCTION nwRrTEToseuF

SEND -

SNIFT

W

II

1

01

n

x

MD {DATAOUTI \

Tli6i6\ n

am n

WRITE T08CON(CUAR Ill)

RECEIVE

I

SNm n

RXD(DATAIN)

L

M mmwmaocm n

“m lx?

n

.Ds

,

n

w

n

1 M

I-I

.0s

n

“m

n

x m n

.0s

I

n

06 n

.06

n

1 07 \

n

I

I

n

D?

Figure 17. 8erial Port Mode O

TRANSMIT

RECEIVE

270252-15

3-18

i~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

TSS

20s1INTERNALBUS

TIMER2

TIMER 1

OVERFLOW

OVERFLOW

=0

SMOD

+2

SMOD

=1

!?

WRITS

TO —

SBUF

TXD

RCLK----

IFFH

RXD

LOAD

SBUF

SSUF

READ

SSUF

*

lx

@oclq

I

IWWTSTOSSUF

I

~L sEND

OATA

SIPF r sNln

1!

1

I 00 z m

STARTSIT

I

-lsnEsm

I

I

1 0

I

1 m r 03 1 0s 1 D5 r 0s 1 n7 1

+1’1

.S

RXO

RECEIVE

TM=-—=

Blwf

l-++++++:

MT”

STOPBtl rRANsMrT

STOPOIT

270262-16

Figure 18. Serial Port Mode 1. TCLK, RCLK and TTmer2 are Preaent in the

8052/8032

Only.

Trammission is initiated by any instruction that oses timesare synchronisedto the divide-by-16counter, not

SBUF as a destinationregister. The “write to SBUF” to the “write to SBUF” signal).

sid * IOSdSa 1 into the 9th bit position of the transmit shift register and flags the TX Control unit next rolloverin the divide-by-16counter. (Thus,the bit

The transmission begins with activation of SEND, that a transmissionis requested.Tmnsmission aotually which puts the start bit at TXD. One bit time later, commencesat SIP1 of the machinecycle followingthe

DATA is activated, whichenablesthe output bit of the transmit shift register to TXD. The first shift pulse cccurs one bit time after that.

3-19

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

As data bita shift out to the right, zeroesare clockedin from the left. When the MSBof the data byte is at the output positionof the shift register,then the 1 that was initiallyloadedinto the 9th positionisjust to the left of the MSB, and all positionsto the left of that contain zeroes. This conditiontlags the TX Control unit to do one last shift and then deactivate SEND and set TI.

This occurs at the loth divide-by-16rollover after

“write to SBUF.”

Receptionis initiated by a detected l-to-Otransition at

RXD. For this purposeRXD is sampledat a rate of 16 times whateverbaud rate has been established.When a transitionis detected,the divide-by-16counter is immediately reaet, and IFFH is written into the input shift register. Reaetting the divide-by-16counter aligns its rolloverswith the boundariesof the incomingbit titnea.

The 16 states of the counter divide each bit time into

16ths.At the 7th, 8th, and 9th counterstates of each bit time, the bit detector sampleathe value of RXD. The value

acceptedis the

valuethat was seen in at least 2 of the 3 samples. This is done for noise rejection. If the value accepted during the first bit time is not O, the receivecircuits are reset and the unit goeaback to looking for another l-to-Otransition. This is to providerejection of false start bita. If the start bit proves valid, it is shifted into the input shift register, and reception of the rest of the thrne will proceed.

As data bits come in from the right, 1s shift out to the left. When the start bit arrives at the leftmost position in the shift register, (which in mode 1 is a 9-bit register), it figs the RX Controlblock to do one last shift, load SBUF and RB8, and set RL The signal to led

SBUFand RB8, and to set RI, will be generatedif, and only if, the followingconditionsare met at the time the final shifl pulse is generat.d

1)

RI = O, and

2) EitherSM2 = O,orthereceivedstopbit = 1

If either of these two conditionsis not met, the received frame is irretrievably lost. If both conditionsare met, the stop bit goes into RB8, the 8 data bits go into

SBUF, and RI is activated. At this time, whether the

aboveconditionsare met or not,

the unit goes bsek to lookingfor a l-to-Otransition in RXD.

MoreAbout Modes2 and 3

Elevenbita are transmitted (throughTXD), or received

(throughRXD): a start bit (0),8 data bits (LSBfit), a programmable9th data bit, and a stop bit (l). On transmit, the 9th data bit (TB8)can be assignedthe value of

Oor 1. On receivejthe 9th data bit goes into RB8 in

SCON.The baud rate is programmableto either Y&or

%.

the

oscillatorfrequencyin Mcde

2.

Mode

3 may havea variablebaud rate generatedfromeither Timer 1 or 2 dependingon the state of TCLK and RCLK.

Figurca 19 and 20 show a fictional diagram of the serial port in Modes 2 and 3. The receive portion is exactly the same as in Mode 1. The transmit portion differsfrom Mode 1 only in the 9th bit of the transmit shift register.

Transmissionis initiated by any instruction that uses

SBUF as a destinationregister. The “write to SBUF” signal also bads TB8 into the 9th bit position of the transmit shift register and flags the TX Control unit that a transmiasion is requested. Transmissioncommencesat SIP1 of the machinecyclefollowingthe next rollover in the divide-by-16counter. (Thus, the bit timesare synchronizedto the divide-by-16counter,not to the “write to SBUF”signal.)

The transmission begins with activation of SEND, which puts the start bit at TXD. One bit time later,

DATA is activated,whichenablesthe outputbit of the transmit shift registerto TXD. The first shitl pulse occurs one bit time after that. The first shift clocks a 1

(the stop bit) into the 9th bit positionof the W register. Thereafter, ordy seroes are clocked in. Thus, as data bits shift out to the right, zeroes are clocked in fromthe left. WhenTB8is at the output positionof the shitl register, then the stop bit isjust to the left of TB8, and all positionsto the left of that containzeroes.This

conditionflagsthe TX Controlunit to do one last shift and then deactivate SEND and set TL This occurs at the llth divide-by-16rolloverafter “write to SBUF.”

Receptionis initiated by a detected 1-W3transition at

RXD. For this purposeRXD is sampledat a rate of 16 timeswhateverbaud rate has been established.When a transitionis detect~ the divide-by-16counteris immediately reaet, and lFFH is written to the input shift register.

At the 7th, 8tb and 9th counter ststes of each bit time the bit detector samplesthe vrdueof RXD. The value acceptedis the valuethat was seen in at least 2 of the 3 samplea.If the value acceptedduring the first bit time is

notO,the receivecircuitsare resetandthe unitgoes

back to looking for another l-to-O transition. If the start bit provea valid, it is shifted into the input shift register,and receptionof the rest of the frame will proeecd.

3-20

i~.

HARDWARE DESCRIPTlON OF THE 8051,8052 AND 80C51

TSS

S0S1INTERNAL BUS

PHASE 2 CLOCK

(% fosc)

MOOE 2

WRITE

S~tF

START

STOP 91T

GEN,

‘H’mDATA

TX CLOCK

TX CONTROL

TI

Sm

TXD

LOAO +

IFFH

RxD

LOAD

SBUF

~LOC~

1

I WRITE TO SBUF n t n n n R 1 n n n

OATA sNIPr n

TI

RECEIVE

I

STOPRl~ lSRESET

ICLOCK 1

Rxo

1

B17DETEcToR15’m’~/

SAMPLE TIMES m

SHIT 1 n a n 11 n

I o

I n

TRANSMIT m

!4!4

n n 8

I D1 1 02 m

W n n n

I

D3 I

1

Im n

M m n n r

06

Es n r o

I m u n n m

1 07

1 ma m n

M n

1 k.4.pP

270252-17

Figure 19. Serial Port Mode 2

3-21

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

TIMER 1

OVERFLOW

TIME

OVEI .Ow

S051INTSRNALBUS

II

/

LOAD+

IFFH v

-

READ

SBUF

*

*

Tx

&LOCl$ n

I WRITE TO S8UF

DATA

SHIFT

-r,

STOP SIT

‘1

Figure20.5enalPortMode3. TCLK,RCLK,andTimer2 arePresentinthe6052/8032Only.

3-22

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

As data bits come in from the right, 1sshift out to the left. Whenthe start bit arrives at the leftmost position in the shift register (whichin Modes 2 and 3 is a 9-bit register), it flags the RX Control block to do one last shit%load SBUF and RIM, and set RI. The signal to load SBUFand RB8, and to set RI, willbe generatedif, and onlyif, the followingconditionsare met at the time the final shift pulse is generated:

1)RI= O,artd

2) EitherSM2= Oor the received9thdata bit = I

If either of these conditions is not met, the received three is irretrievably lost, and RI is not set. If both conditionsare met, the received9th data bit goes into

RB8, and the tiret 8 &ta bits go into SBUF. One bit time later, whether the aboveconditionswere met or not, the unit goesback to lookingfor a l-tQ-Otransition at the RXD input.

Note that the value of the receivedstop bit is irrelevant to SBUF,RB8, or RI.

INTERRUPTS

The

8051

provides 5 interrupt sources. The 8052provides6. These are shown in Figure 21.

The External Interrupts ~ and INT1 cars each be either level-activatedor transition-activate&depending on bita ~ and ITl in RegisterTCON. The tlags that actuallygenerate these interrupts are bits IEQand IE1 in TCON.Whetsen externalinterrupt is generated,the tlag that generated it is cleared by the hardware when the serviceroutine is vectoredto only if the interrupt

m m

.J?--#GJ,

D

I

[email protected]+=

P

was transition-activated.If the interrupt was [email protected] then the externalrequestingsource is what controls the requestflag,rather than the on-chiphardware.

The Timer Oand Timer 1 Interrupts are generatedby

TFO and TFl, which are set by a rollover in their respectiveTimer/Counterregkters (exceptseeTimerOin

Mode 3). Whena tinter interrupt is generated,the flag that generated it is cleared by the on-chip hardware when the serviceroutine is vectoredto.

The SerialPort Interrupt is generatedby the logicalOR of RI and TI. Neither of these flags is cleared by hardware when the cervix routine ia vectored to. In fact, the service routine will normally have to determine whether it was RI or TI that generated the interrupt, and the bit will have to be cleared in software.

In the 8052,the Timer 2 Interrupt is generatedby the logicalOR of TF2 and EXF2. Neither of these flags is cleared by hardware when the service routine is vectored to. In fact, the serviceroutine may have

to

determine whether it wee TF2 or EXF2 that generatedthe interrupL and the bit will have to be cleared in software.

All of the bite that generate interrupt can be cleared by software,with the same result as though it had beenset or clearedby hardware.That is, interrupts can be generatedor pendinginterrupts can be canceled

in

software.

(MSS)

(LSB) m] — I E72 I ES I ~1 I EXl I ETO ] EXO

Enable S4 = 1 enaMss the infwrupt

Ensble Sit = O dieebles it symbol

EA

Position

IE.7

Function

&eek4es sII interrupts.If EA = 0, no intemuptwillbeeeknowledged. If EA

= I,eeehinterrupt solneeie indbiduskyenebled wdissbled by settingorclearing meaaeble bit.

ET2

ES

El-l

Exl

ETo

IE.6

IE.5

IE.4

IE.3

IE2

IE.t

resewed.

litnw2 intenupf enable bit

Serial P&t infamuptenebletit.

ITmer 1 imenupl ensbfe bit.

Extarrsalinterrupt1 ertablebt

Timw O ikttanuptenablsbit.

Exo IE.O

ExterrKaintenuptO eneblebit

Usersotiwaraslwuld navarwrits Istourtimplamwfad bits,since

~MSYbausad in futureMCS-51 @ueta

Figure22.IE:InterruptEnableRsgister exn (mssOMLo

-J

270252-19

Figurs 21. [email protected] Sources

3-23

infd.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Each of these interrupt sourcescan be itldividdy enabled or disabledby settingor clearing a bit in Special

Function Register IE (Figure 22). IE contains also a global disablebit, EA, which disables all interrupts at once.

Note in Figure 22 that bit position IE.6 is unimplemented. In the 8051s bit positionIE.5 is also tmimplemented. User softwareshouldnot write 1s to these bit positions, since they may be used in future MCS-51 products.

PriorityLevelStructure

grammed to one of two priority levels by setting or clearing a bit in SpecialFunction Register 1P (Figure

23). A low-priorityinterrupt can itself be interrupted by a high-priorityinterrup~but not by another low-pri-

ority interrupt.

A

high-priority interrupt can’t be inter-

rupted by ~y other-int&rupt-aource. ceivedsimultaneously,an internal pollingsequencedetermines which request is serviced. Thus within each priority levelthere is a second priority structure determined by the pollingsequence,as follows:

Priority Within Level

(highest) 1.

2.

3.

4.

Source

IEO

TFO

IE1

TF1

5.

RI +Tl

6.

TF2 + EXF2 (lowest)

Note that the “prioritywithin level” structureis only usedto

resolve

m“muitaneous ty level.

The

1P register contains a numbes of unimplemented bits. IP.7 and IP.6 are vacant in the 8052s,and in the

8051sthese and IP.5 are vacant. User softwareshould not write 1s to these bit positions,since they may be used in future MCS-51products.

(MSB)

(LSB)

— PT2 PS PTl Pxl PTo Pxo

Riwity bit = 1 assigns high priortty.

Priorftybit = O sssigns low priority.

Symbol

PT2

Ps

PTl

Pxl

MO

Poeitforl

IP.7

IP.6

IP.5

IP.4

IP.3

IP.2

IP.1

Funefion reserved resewed

Tmer2 intemuptprie+ftybit.

Swisl Port intenupt prioritybl

Timer 1 intenupt primityMt.

Externalintenupt 1 pttofitybit lim6r0 interruptpttoiitybit.

Pxo IP.O

Extemsl intenupt O prioritybit

User soffwareshould neverwite 1$ to unimplementedbits,since theYmbe used ifIfufurs [email protected] P+oducts.

Figure 23. 1P:Interrupt Priority Register

If two requests of dikent simultaneously,the request

of higher priority level is serviced.

If requests of the same priority level are re-

How InterruptsAre HandIed

The

interrupt flags are sampled at S5P2 of every machine cycle. The samplesare polled during the following machine cycle.The 8052’sTimer 2 interrupt cycle is ditkrent as describedin the ResponseTime Section.

Hone of the ilagswasin a set conditionat S5P2of the

P~

“ g cycle the polling cycle will find it and the interrupt systemwillgeneratean L-CALLto the appropriate serviceroutine,providedthis hardwere-generated LCALL is not blockedby any of the followingconditions:

1. An interrupt of equal or higher priority level is already in progress.

2. The current (polling)cycle is not the final cycle in the executionof the instruction in progress.

3. The instructionin progressis RETI or any write to the IE or 1P registers.

Any of these three conditionswill blockthe generation of the LCALL to the interrupt serviceroutine. tXmdition 2 cn3urcethat the instruction in progress wilt be

ISEP21 % I m

INTERRUPT INTERRUPT

GOES

LATCHEO

ACTWE

‘:

INTERRU~

AREPOLLSO

A

LONGCALLTO

IM’ERRUPT

VECTORAOOQESS

A

. . .. .

INIERRUPTHOUllNE

270252-20

Ttisisthefeetestpossible reeponee vhn C2isthefinel cydeofaninettuctien ottwrthert RETI oranaeaesto IEorlP.

Ftgure

24. Interrupt

ResponseTimingDisgrem

3-24

intdo

HARDWARE DESCRIPllON OF THE 8051,8052 AND 80C51

completedbeforevectoringto any serviceroutine.Condition 3 ensures that if the instruction in progress is

RETI or any accessto IE or 1P, then at least

one more

instruction wiffbe executedbefore any interrupt is vectored to.

The

polfing

cycleis repeated with each machinecycl~ and the valuespolledare the valuesthat werepresentat

S5P2 of the previousmachine cycle. Note then that if an interrupt flagis activebut not beingrespondedto for one of the aboveconditions,and is not

still active

when the blockingconditionis removed,the deniedinterrupt will not be serviced.In other wor& the fact that the interrupt tlag was once active but not servicedis not remembemd.Everypoflingcycle is new.

The pofling cycle/LCALL sequence is illustrated in

Figure 24.

Note that if an interrupt of higher priority Ievefgoes active prior to S5P2of the machine cyclelabeledC3 in

Figure 24, then in accordance with the aboverules it

@ be

Vectored to

during C5 and cd, without Stlyinstruction of the lowerpriority routine havingbeenexecuted.

Thus the procesaor acknowledgesan interrupt request by executinga hardware-generatedLCALL to the ap propriate servicingroutine. In some cases it also clears the flag that generatedthe interrupt, and in other cases it doesn’t. It never clears the Serial Port or Timer 2 flags. This has to be done in the user’s software. It clears an external interrupt flag (IEOor IEl) only if it was transition-activated. The hardware-generated

LCALL pushes the contents of the Program Counter onto the stack (but loads the PC with an address that depends on the source of the interrupt being vectoredto, as ahownbelow.

Vector

8ource

Address

IEO

TFO

IE1

TF1

RI + TI

TF2 + EXF2

OO03H

OOOBH

O013H

OOIBH

O023H

O02BH

ExternalInterrupts

The externalsourcescan be programmedto be level-activated or transition-activatedby setting or clearing bit

ITI or ITOin Register TCON. If ITx = O, extemaf interrupt x is triggered by a detectedlow at the INTx pin. If ITx = 1, external interrupt x is edge-tiered.

In this mode if successive samples of the INTx pin show a high in one cycle and a low in the next CYCIG interrupt requeatflag IEx in TCONis set. Flag bit IEx then requeststhe interrupt.

Sincethe extemaf interrupt pinsare sampledonce each machinecycle, an input high or lowshould hold for at least 12 oscillator periods to ensure sampfing. If the external interrupt is transition-activated,the external sourcehas to hold the requeatpin high for at least one machine cycle, and then hold it low for at least one machine cycle to ensure that the transition is seen so that interrupt request flag IEx will be set. IEx will be automatically cleared by the CPU when the service routine is called.

If the external interrupt is level-activated,the external sourcehas to hold the requestactiveuntil the

requested

interrupt is actually generated.Then it has to deactivate the request before the interrupt service routine is complet~ or else another interrupt will be generated.

ResponseTime

The ~ and INT1 levels are inverted and latched into the interrupt tlags IEOand IEl

at

S5P2 of every machine Cycle.Similarly,the Timer 2 flag EXF2 and the Serial Port flags RI and TI are set at S5P2. The valuesare not actually polledby the circuitry until the next machinecycle.

The TimerOand Timer 1flags,TFOand TFl, are set at

S5P2 of the cycle in which the timers overflow.The

vafuesare then polledby the circuitryin the next cycle.

However,the Timer 2 flag TF2 is set at S2P2 and is polledin the same cycle in whichthe timer overtlows.

Executionproceedsfromthat locationuntilthe RETI instructionis encountered.

formsthe processo

The RETI instructioninr

that this

interruptroutineis no

longerin progr~ then popsthe top twobyteafromthe stack and reloads the program Counter. Executionof the interrupted program continues from where it left off.

Note that a simple RET instruction would also have returned executionto the interrupted progmrn,but it would have left the interrupt control system thinking an interrupt was stiIl in progress.

If a requeatis active and conditionsare right for it to be acknowledged,a hardware subroutinecd to the requestedserviceroutine wittbe the nextinstructionto be executed.The call itself takes two cycles.Thus, a minimum

ofthreecompletemachinecycleselapsebetween

activation of an external interrupt request and the beginningof executionof the first instructionof the aervice routine.Figure 24 showsinterruptresponsetimings.

3-25

A longer response time woufdresult if the request is blockedby one of the 3 previouslyfisted conditions.If

an interrupt of equal or higherpriority level is already in progress,the additionalwait time obviouslydepends on the nature of the other interrupt’sserviceroutine. If the instruction in progressis not in its final cycl~ the additionalwait time cannotbe morethan 3 cycles,since the longest instructions (MUL and DIV) are only 4

intel.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

cycles long, and if the instructionin progress is RET2 or an access to IE or 1P, the additionalwait time cannot be more than 5 cycles (a maximumof one more cycle to complete the instruction in progress, plus 4 cyclesto completethe next instructionif the instruction is MUL or DIV).

Thus, in a single-interruptsystenLthe responsetime is rdwaysmore than 3 cyclesand less than 9 cycles.

SINGLE-STEPOPERATION

The 8051interrupt structure allowssingle-stepexecution with very little software overhead.As previously noted, an interrupt request will not be responded to whilean interrupt of equal prioritylevelis still in progress, nor will it be respondedto after RETI until at least one other instruction has been executed. Thus, once an interrupt routine has beenentered,it cannot be reentered until at least one instructionof the interrupted programis executed.One wayto use this feature for single-stopoperationis to programone of the external interrupts (say, INTO)to be level-activated.The service routine for the interrupt willterminatewith the following cude:

JNB P3.2,$ ;Wait Here Till~Goes High

JB P3.2,$ ;NowWait HereTill it Goes Low

RETI :Go Back and ExecuteOne Instruction

Now if the ~ pin, whichis alsothe P3.2 pin, is held normallylow, the CPU will go right into the External

Interrupt Oroutine and stay there until ~ is pulsed

(from low to high to low). Then it will execute RETI, go back to the task program, executeone instruction, and immediatelyre-enter the Extend Interrupt Oroutine to await the next pulsingof P3.2. One step of the task program is executedeach time P3.2 is puked.

RESET

The reset input is the RST pin, whichis the input to a

SchmittTrigger.

A reset is accomplishedby holdingthe RST pin high for at least two machine cycles(24 oscillator periods),

while the asciIlator h rwnning. The

CPU responds by generatingan internal [email protected] with the timing shown in

Figure 25.

The externalreset signalis asynchronousto the internal clock. The RST pin is sampledduring State 5 Phase 2 of every machine cycle. The port pins will maintain their current [email protected] 19 oscillatorperiods after a logic 1 has been sampledat the RST pin; that is, for 19 to 31 oscillator periods after the external reset signal has been applied to the RST pin.

Whilethe RST pin is high, ALE and PSEN are weakly pulledhigh. Mer RST is pulledlow,it will take 1 to 2 machine cycles for ALE and PSEN to start clocking.

For this reason, other devicescan not be synchronized to the internal timingsof the 8051.

Driving the ALE and PSEN pins to O while reset is active could cause the deviceto go into an indeterminate state.

The internal reset algorithm writes 0s to all the SFRS except the port latch= the Stack Pointer, and SBUF.

The port latches are initialized to FFH, the Stack

Pointer to 07H, and SBUF is indeterminate. Table 3 lists the SFRSand their reset values.

The internal R4M is not affectedby reset. On power up the ILkM content is indeterminate

~t2 OSC. PERIODS ~

RST:

I//l/l/l///w

SAMPti, RST

SAMPLE RST

,

I

IN7ERNAL RESETSIGNAL

~:

Po:

!(

—11

INST

1

I I

~1

I

I [

I I ,, t

1

I

OSC. PERIODS —

,

270252-33

Figure 25. Reset Timing

3-26

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51 i~o

I

Table 3. Reset Values of the SFRS

Pc

SFR Name Reset

Value

OOOOH

ACC

B

Psw

SP

I

DPTR

I

PO-P3 I

I

OOH

OOH

OOH

07H

OOOOH

FFH

1P(8051)

1P(8052)

IE [8051)

IE (8052)

1

TMOD

TCON

[

THO

TLO

TH1

I

TL1

TH2 (8052)

TL2

(8052)

RCAP2H(8052)

RCAP2L(8052)

SCON

SBUF

PCON (HMOS)

PCON (CHMOS)

I

I

XXXOOOOOB

XXOOOOOOB

OXXOOOOOB

OXOOOOOOB

OOH

OOH

OOH

OOH

OOH

OOH

OOH

OOH

OOH

OOH

OOH

Indeterminate

OXXXXXXXB

OXXXOOOOB

I

J

I

I

POWER-ONRESET

For HMOSdeviceswhenVCCis turned on an automatic reset can be obtainedby connectingthe RST pin to

V~ througha 10pF capacitor and to Vss throughan

8.2 Kf2 reeistor (Figure 26). The CHMOSdeviceado not require this resistor although its presencedoea no harm. In fact, for CHMOSdevicesthe externalresistor can be removedbecausethey havean internalpulldown on the RST pin. The capacitor valuecould then be rduced to 1 pF.

Whenpoweris turned on, the circuit holdsthe RST pin high for an amount of time that dependson the capacitor value and the rate at whichit charges.To ensure a valid reset the RST pin must be held high long enough to allow the oscillator to stsrt up plus two machine cycles.

On power up, VCCshould rise within approximately ten milliseconds.The oscillator start-up time will dependon the oscillatorfrequency.Fora 10MHz crystal, the start-up timeis typically 1 rns.For a 1MHz crystal, the start-up time is typically 10ms.

With the givencircui~ reducingVW quicklyto Ocauses the RST pin voltageto momentarilyfall below OV.

However,this voltageis internzdlylimitedand will not harm the device.

NOTE:

The port pins will be in a random state until the oscillatorhas started and the internal reset algorithmhas written 1s to them.

Powering up the device without a valid reset could cause the CPU to start executinginstructionsfrom an indeterrninatelocation. This is becausethe SFRs, apecitically the Program Counter, may not get properly initialized.

,.”,l

=

UKIL k

ST

Isa

Sml

Figure25. PoweronResetCircuit

‘cc

270252-21

3

POWER-SAVINGMODESOF

OPERATION

For applicationswhere power consumptionis critical the CHMOSversionprovideapowerreducedmodesof operationas a standard feature. The powerdownmode in HMOS

devicesis being

phased

OUt.

no

longera standardfeatureandis

CHMOSPowerReductionModes

3-27

CHMOS versions have two power-reducingmodes,

Idle and PowerDown.The input throughwhichbackup power is suppliedduring these operationsis VCC.

Figure 27 shows the internal circuitry which implements these features. In the Idle mode(IDL = 1), the oscillator continuea to run and the Interrupt, Serial

Port, and Timer blockscontinueto be clocked,but the

intel.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

clock signal is gated off to the CPU. In Power Down

(PD = 1), the oscillator is frozen.The Idle and Power

Down modes are activated by setting bits in Special

Function RegisterPCON. The address of this regiete.r

is 87H. Figure 26 details ita contents.

In the HMOSdeviceathe PCON registeronlycontains

SMOD. The other four bits are implementedonly in the CHMOSdevices.User softwareshouldneverwrite

1s to unimplementedbita, since they may be used in t%tureMCS-51products.

IDLE MODE

An

instructionthat sets PCON.Ocausesthat to be the last instruction executed before going into the Idle mode. In the Idle mode, the internal clock signal is gated off to the CPU, but not to the Interrupt, Timer, and Serial Port functions.The CPU statue is preserved in its entirety: the Stack Pointer, Program Counter,

Program StatueWord, Accumulator,and all other registers maintain their data during Idle. The port pins hold the logical statea they had at the time Idle was activated. ALE and PSEN hold at logichigh levels.

There are two waysto t-ate the Idle. Activationof any enabledinterropt will cause PCON.Oto be ckared will be [email protected] and followingRETI the next instruction to be executed will be the one followingthe instruction that put the deviceinto Idle.

(MSB)

SMOO

(Lss)

I - I - I -

GF1 GFO PD IOL symbol

SMOD

PoSnIOrt

PCON.7

Natrteattd Furtotic+t

Oouble Saud rats bit.When aattoa 1 and Timer 1 is used togenerrda baud rate, andfhs SsrW .%rl is used in modes 1,2, 0r3.

PCON.6

FCON.5

(Reserved)

(Reserved)

GF1

PCON.4

PCON.3

PCX2N.2

FCX2N.I

(Reaswsd)

General-purpose flag bit

Gemaraf-pu~ flqlrit.

GFO

PD

IDL PCON.O

Powsr Down M. Satfingthisbit activates powsrdewmoperation.

Idle mode bit. Setfingthk btiactivataa idle mode opsratiort

If 1s arewrfrren to PD and IDL at the aametime, PDfskes precedence.l%areeetvaluaof PCONia(OXXXOCOO).

In tfw HMOSd-

* ~N @2taroII~contains SMOD.

Ttwofherfcurtit eareimpkmer!tsd onfyintlw CHMOSdsvioea.

User mftwsre sfwuld rwverwite Istourimplememtsd bita,ainm tfwymaybeuasdin future MCS-51 pmduote.

Figure 28.

PCON:

PowerControlRegister

The tlag bite GPO end GFI can be used to give an indiesti;n if en interrupt occurred duringnorm~ operation or during an Idle. For example, an instruction that activates Idle can also set one or both flag bita.

serviceroutine can examine the fig bita.

riOh

2rAL2

‘L...

b--

Figure 27.

Idle and Power Down Hardware

hardware reset. Since the clock oscillator is still running the hardwarereset needsto be heldactivefor only two machinecycles (24 oscillator periods)to complete the reset.

The signal at the RST pin clears the IDL bit directly and asynchronously.At this time the CPU resumes programexecutionfrom where it left off;that is, at the instruction following the one that invoked the Idle

Mode. As shown in Figure 25, two or three machine cyclesof programexecutionmay take pleee beforethe internal reset algorithm takes control. On-chip hardware inhibita access

to the internal RAM

during this time, but aeccas to the port pins is not inhibited. To eliminate the possibilityof unexpectedoutputs at the port pine,the instructionfollowingthe onethat invokes

Idle should not be one that writes to a port pin or to external Data RAM.

POWER DOWN MODE

An

instructionthat seta PCON.1 cauaeathat to be the last instruction executed before going into the Power

Down mode. In the Power Down mode, the on-chip oscillator is stopped. With the clock frozen, all func-

3-28

in~.

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

Device

Name

8051AH

80C51BH

EPROM

Version

87C51

1

8052AH 8752BH

Table4. EPROMVersionsof the 8051and8052

8751H/8751BH

EPROM

Bytes

4K

4K

8K

Ckt

Type

HMOS

CHMOS

HMOS

VPP

21.0V112.75V

12.75V

12.75V

tions are stopped, but the on-chip RAM and Special

Function Registeraare held. The port pins output the valuesheld by their reapecdveSFRS.ALE and P8EN output lows.

The only exit from Power Down for the 80C51is a hardware reset. Reset redefinesall the SPRS,but does not changethe on-chip W.

In the Power Down mode of operation, VCC can be reducedto as low as 2V. Care must be taken, however, to ensure that VCC is not reduced before the Power

Downmodeis invoked,and that VCC is restoredto its normaloperatinglevel,beforethe PowerDownmodeis terminated.The reset that terminatesPowerDownalso frees the oaeillator. The reset should not be activated before VCC is restored to its normal operating level, and must be held active long enoughto allowthe oscillator to restart and stabilise (normally less than 10 maec).

Time Required to

ProgramEntireArray

4 minutes

13 seconds

26 seconds

ProgramMemoryLocks

In somemicrocontrollerapplicationsit is desirablethat the Program Memorybe secure from software piracy.

Intel has responded to this need by implementinga

Program Memorylockingschemein someof the MCS-

51 devices.Whileit is impossiblefor anyoneto guarantee absolutesecurity againatall levelsof technological sophistication,the ProgramMemorylocksin the MCS-

51 deviceswillpresenta substantialbarrier againatillegal readout of proteetedsoftware.

One Lock Bit Scheme on 8751H

The

8751H contains a lock bit which, once programmed, denies electrical access by any external means to the on-chipProgram Memory. The etht of this lock bit is that whileit is programmedthe internal

Program Memorycan not be read out, the devicecan not be further programmed,and it

can not execute external ?%ognamMemory.

Erasing the EPROM array deactivates the lock bit and restores the device’sfull functionality.It can then be re-progratnmed.

EPROMVERSIONS

The EPROM versionsof these devieesare listedin Table 4. The 8751Hprograms at VPP = 21Vusing one

50 msec PROO pulse per byte programmed.This results in a total programmingtime (4K bytes)of approximately4 minutes.

The procedurefor programmingthe lock bit is detailed in the 8751Hdata sheet.

Two

ProgramMemoryLock

Sshemes

The 8751BH, 8752BH and 87C51 use the faster

‘@i~k-p~>> pro~gm

~gorithm. ~= de-

12.75Vusing a series of twenty-fiveIMlps PROO pulsesper byteprogrammed.

This results in a total programmingtime of approximately 26 seconds for the 8752BH (8 Kbytes) and

13seeondsfor the 87C51(4

Kbytes).

The 8751BH,8752BHand 87C51contain two Program

Memory lockingschemes:Encryptedverify and Lock

Bits.

Detailed

procedures for programming and verifying each deviceare givenin the data sheets.

Exposureto Light

It is good

practice to cover the EPROM windowwith an opaquelabel when the deviceis in operation.This is not so much to protect the EPROM array from inadvertent erssure but to protect the RAM and other onchip logic.Allowinglight to impingeon the silicondie whilethe deviceis operatingcan csuae logicalmalfhnetion.

EncryptionArraw

Within the EPROM is an array of encryptionbytes that are initially unprogrammCd(au l’s). The user ean program the array to encrypt the code bytes during EPROM veriftcstion. The verification procedure sequentiallyXNORS each code byte with oneof the keybytes.Whenthe last keybyte in the

-Y k reached,the verifyroutine starts over with the first byte of the array for the next code byte. If the key byteaare unprogrammed,the XNOR processleavesthe code byte unchanged.With the keybytes programmed, the code bytes are encryptedand can be read correctly only if the key bytes are known in their proper order.

Table 6 lists the number of encryptionbytrs available on the variousproducts.

Whenusingthe encryptionarray, one important factor should be considered. If a code byte has the value

3-29

[email protected]

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

OFFH,ven~g the byte will prqduce the encryption byte value. If a large block of code is letl unprogrammed,a verificationroutinewilldisplaythe encryption array contents. For this reason all unused code bytea should be progrsmmed with some

value other than OFFH,

and not all of them the same value. This will ensure maximumprogramprotection.

Prosram Lack Bita: Also included in the Program

Lack scheme are Lock Bits which csn be enabled to providevaryingdegreesof protection,Table 5 lists the

L.cckBits and their correspondingeffect on the microcontroller.Refer to Table 6 for the Lock Bits available on the variousproducts.

Erasing the EPROM also erases the EncryptionArray and the Lack Bits,returningthe part to full functionality.

Table 5. Program Lo k Bits and their Features

3ita

Protection Type

LB1 LB2

Y-

T

LB3

u u

No programlock features enabled.(Code verifywill stillbe encryptedbythe encryptionarray if programmed.)

MOVC instructions executedfromexternal programmemoryare disabledfromfetching code bytesfrom internal memory,EA is sampled and latchedon reset,and furtherprogrammingof the EPROM is disabled.

P P

u

P P

— — gremmed mogrammed

P

Same as disabled.

2, also verifyis

-

Same as 3, also external executionis disabled.

Any other combinationof the LockBits is not defied.

Device

8751BH

8752BH

87C51

Table6. ProgramProtection

LocfrBite

LB1, LB2

LB1, LB2

LB1, LB2, LB3

Enorypt Any

32 Bytes

32 Bytes

84 Bfles

When Lock Bit 1 is programm~ the logiclevelat the

~ pin is sampledand latched during react. If the device is poweredup withouta reset, the latch inidalizes

to a

random value, and holds that value until reset is activated. It is ncassary that the latched value of ~ be in agreement with the current logic levelat that pin in order for the device

to

function properly.

ROM PROTECTION

The 8051AHP and 30C51BHP are

ROM Protectrd versionsof the 3051AHand 30C51BH,respectively.To

incorporate this Protection Feature, program verification has been disabled and extcrnaf memory amessca have been limited to 4K. Refer to the data sheets on these parts for more information.

ONCETMMode

The

ONCE (“on-circuit emulation”) mode facilitates testing and debuggingof systemsusingthe devicewithout the &vice havingto be removed from the

circuit.

The

ONCE mode is invokedby:

1. Pull ALE low whilethe deviceis in react and PSEN is high;

2. Hold ALE low as RST is deactivated.

While the deviceis in ONCE modq the Port Opins go into a float state, and the other port pins and ALE and

~ are weakly pulled high. The oscillator circuit remains active. While the device is in this modq an emulator or teat CPU can be used to drive the circuit.

Normal operation is restored after a normal reset is applied.

THE ON-CHIPOSCILLATORS

HMOSVersions

The

cm-chip oscillator circuitry for the HMOS

(HMOS-Iand HMOS-11)membersof the MCS-51fsmily is a singlestage tinearinverter (Figure 29), intended for usc as a crystal-controlled,positivereactance oscillator (Figure 30). In this appficstionthe crystal is operated in ita fundsmentafresponsemode as an inductive reactarw in psralfel resonancewith capacitance-external to the crystal.

3-30

HARDWARE DESCRIPTION OF THE 8051,8052

AND80C51

in~.

01

b

ar

J&

loamm4AL

rnllo a4

ImLz

CUTS

xrALl

T

Suesl.

-

%s

270252-23

Figure29.On-ChipOsciiiatorCircuitryin the HMOS Versions of the [email protected]

-------msl

V=*”=

In general, crystals used with these devices typically have the followingspecifications:

ESR (EquivalentSeriesResistance) see Figure 31 c20(ShuntCapacitance)

7.opFmax.

CL(bid ~pr$ei~ee)

Drive Level

30pF *3 pF

1 mW

ORC6RANICRESOWIOR

0

270252-24

Figure 30. Using the HMOS On-Chip Oeciiiator

The

crvstal meeifkationa and cauacitanee values (Cl and C2-inFi&re 30)are not criti&l. 30 pF can be u&i irr these positionsat any frequencywith good quality crystals. A ceramic resonator can be used in place of the crystal in cost-sensitiveapplications. When a ceramic resonatoris used,Cl and

C2arenormally

The manufacturer of the ceramic resonator should be consulted for recmnmcndationson the

vaiucs

of thCSC capacitors.

highervaluea,

pF.

4

a

12 16

270252-34

—.

-—— -

Figure 31. ESR VSFr6!qUenOy

3-31

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51 [email protected]

Frequency,toleranceand temperaturerange are determined by the systemrequirements.

A more in-depthdiscussionof crystalspeciticstions,ceramic reaonstors,and the selectionof valuesfor Cl and

C2 can be foundin ApplicationNoteAP-155,“Oscillators for Microcontrollers,” which is included in the

Embedded Appticatwnz Handbook.

To drive the HMOS parts with an external clock source, apply the external clock signalto XTAL2, rmd ground XTAL1,as shownin Figure32.A pullup reaistor may be used (to increase noisemargin), but is optional ifVOH of the drivinggate exceedsthe VIH MIN specificationof XTAL2. --

EXTSRNAL oeenLAloR

XTAU

msl

+-!4

SIGNAL t

GATE

V&

v=

mTsu.PoLe

OUTPUT

XTAL1

270252-25

Figure32.Drivingthe [email protected]

Partewithan ExtemsdClockSource

CHMOSVersions

The on-chip oscillator circuitry for the 80C51BH, shown in Figure 33, consists of a single stage linear inverter intended for use as a crystal-controlled,positive reactance oscillator in the same manner as the

HMOSparta. However, there are some important differences.

One differenceis that the 80C51BHis able to turn off its oscillatorunder software control (by writing a 1 to the PD bit in PCON). Another differenceis that in the

80C51BHthe internal clockingcircuitry is driven by the signalat XTAL1, whereasin the HMOSversionsit is by the signalat XTAL2.

The feedbackresistor Rfin Figure 33 consistsof paralleledn- and p- channel FETs controlledby the PD bit, such that Rf is opened when PD = 1. The diodeaD1 and D2, which act as clamps to VCC and VSS, are parasitic to the Rf FETs.

The oscillatorcan be used with the same external componentsas the HMOS versio~ as shownin Figure 34.

Typically,Cl = C2 = 30 pF when the feedbackelementis a quartz crystal, and Cl = C2 = 47 pF whena ceramicreaonator is used.

To drive the CHMOS parts with ass external clock sourcq apply the external clocksignalto XTAL1, and leaveXT-=2 float, as shownin F&ssre35.

m

L

xrALl

c1

Mon

al

02 r

?“

s

In the CHMOS Versions

Q%e

270252-26 of the [email protected] Family Figure 33. On-Chip Osoillsstor Circuitry

3-32

I

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51 i~e nsaNo

70 m?lsmu

curs

%s

---—---

F5 he w

m

xrMl

xrAL2------

I w

v

1 c1

Q

=

270252-27

Figure 34.

Usingthe

CHMOS

On-ChipOscillator

I

Soeal

MC+

X-rAu

*

270252-28

Figura 35. Driving the CHMOS [email protected]’-5l

Parts with an External Clock Source

The reason for this change from the way the HMOS part is drivencan be seenby comparingFigures29 and

33. In the HMOS devices the internal timing oircuits are driven by the signal at XTAL2. In the CHMOS devicesthe internal timing circuits are driven by the signalat XTAL1.

INTERNALTIMING

Figures 36 through 39 show when the various strobe and port signals are clockedinternally.The figuresdo not showrise and fall times of the signals,nor do they showpropagationdelaysbetweenthe XTAL signaland eventsat other pins.

Rise and fall times are dependenton the external loadingthat each pin must drive.They are oftentaken to be somethingin the neighborhoodof 10 ~ measured bemveen0.8V and 2.OV.

Propagationdelays are differentfor differentpins. For a given pin they vary with pin loading temperature,

VCC, and manufacturinglot. If the XTALwaveformis taken as the timing referenee, prop delays may vary from 25 to 125nsec.

The AC Timingssectionof the data sheetsdo not reference any timing to the XTAL waveform.Rather, they relate the criticsdedges of control and input signalsto eaoh other. The timings published in the data sheets include the effects of propagation delays under the specitledtest conditions.

3-33

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

XIAk

SYATS1 STATS2 STAY53 STATS4 SYATS5 STATS6 STATS1 ~AlS2

Imlmlmlmlnlmlmlmlm lmlmlmlmlnlm,nl

ALS: ~

~: w:

4

1

DATA

+aANPLsD

8 1

OATA

I

OATA

-SAMPLSO

E

P2:

Pet’loul

Pctlour

Figure 36. External Program Memory Fetches

STATS 4 STATE 5 SYATS6

ln,mlPllmlnlml

1 SYAYE

STA= 4

SIATE

5

Mlml MlwlPllmlPl IAIF+I

Pcnoul

270252-29

XTAL

‘“: ~

~&

1

PCLOUYF

PRoGw NSNORY s axrER?4AL

FLOAT

PO:

OUT

If

P2:

PCHOR

P2am

0% ORP2SFRour

Figure37.ExtemelDateMemoryRead~cle

PCHOR

P2am

270252-20

3-34

intdo

HARDWARE DESCRIPTION OF THE 8051,8052 AND 80C51

XTAIJ

STATE4 STATE 5 2TATE 6 STATE

1 STATE

STATE 3 STATE4 STATE 5

I‘11’2 IPllP2IPI1’2I‘11’2 I‘11’2 I PI1’2I PllP2I ‘1 I ‘2 I

Irrk

“’~

~:

PO:

‘2

1

OATAOUT

1

PCLOUTF

PROGRAM MEMORV

16exramu

DPLORRI

OuT oPHoRP2amour

Figure38.

External Data Memory

WriteCycle

STATE4 STATE 6 STATE6 2TATE 1 STATE 2 STATES STAlE4 STATES

PllP21PllP21Pl lmlnlmlmlnlmlnl nlmlPllml

270252-31

“–’HpD”

NovPowr,eRc:

OLOOATA s!~

N2WOATA

x:”

+ +nxo ---

RxoeAuPLeo+

Figure 39. Port Operation

+

270252-32

3-35

i~.

HARDWARE DESCRIPTION OF THE 8051,8052

AND80C51

ADDITIONALREFERENCES

The following application notes and articles are found in the

Embedded Applications

handbook.

(Order Number:270648)

1. AP-125“DesigningMicrocontrollerSystemsfor ElectricallyNoisy Environments”.

2. AP-155“Oscillatorsfor Microcontrollers”.

3. AP-252“Designingwith the 80C51BH”.

4. AR-517“Usingthe 8051Microcontrollerwith ResonantTransducers”.

3-36

Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project