The 8051 Microcontroller and Embedded Systems Using Assembly and C [PDF]

  • 0 0 0
  • Gefällt Ihnen dieses papier und der download? Sie können Ihre eigene PDF-Datei in wenigen Minuten kostenlos online veröffentlichen! Anmelden
Datei wird geladen, bitte warten...
Zitiervorschau

Tl T1

...

"

THE 8051 MICRO CONTROLLER

AND EMBEDDED SYSTEMS Using Assembly and C SECOND EDITION

Muhammad Ali Mazidi Janice Gillispie Mazidi Rolin D. McKinlay

-PEARSON

Prentice Hall

pper

addle River, ew Jersey Columbus, Ohio

ealato ing-in-Publicalion Data tlbnryofCongrtM ~lJ.t~h.Muh.1mmad All.

g

and C / Muhammad d

I luoconlrolltr an em

bedded systems: using Assembly,

.

J

Tht: 80S m , . • Mazidi Rolin 0 McKtn ay. Ah MUldl, Janke Gillispie 1

I : ~~ 1,l.119402-X (alk. paper) d I" systems. I McKinlay, Rolin D.IL I ~rilmmi!blt conirollers.2. Embedde compu Tl\k IJ22] P76MJ78 2006

.2989

dell

2005054446

Edllor: Kale unsnar .. Edltorl.l Assistant; Lara Dimmick Production Editor: Kevin Happell o..lgn Coordlnalo" Diane Ernsberger Covar Deslgne" Bryan Huber Cover Art; Super Stock Production Managa" Matt Ollenweller Stnlor Marketing Coordinator: Liz Farrell Stnlor Marketing Managar: Ben Leonard

op)'Tlght 0 2006 by Pearson Edncation, Ine., Upper Saddle River, New Jersey 074~8.Pearson Prentice Hall. All rights Printed in the United States of America. This publication is protected by Copyright and permission should be obtaine d from the publisher prior to any prohibited reproduction, storage in a retrieval system, or tranSmission in any form or by any means, electrcmc, mechanical, photocopying, recording, or likewise. For information regarding pennission(s), write to: Rights and Pcmllssiol\s Department.

"""rved.

Pearson Prentice Hall'" is a trademark of Pearson Education, Inc.

Pearson- is a registered trademark of Pearson pic

Pr nUce Hall- is a registered trademark of Pearson Education, Inc. Peal>Ol1Education Ltd. P arson Education Singapore, Pte., Ltd. Pearson Education Canada, Ltd. Petlt!On Education-Japan

Pearson Pearson Pearson Pearsoll Pearson

Education Education Educacion Education Education

Australia PTY, Lintited North Asia Ltd. de Mexico, SA de C. V. MalaYSia, Pte. LId. lnc., Upper Saddle River, New Jersey

ISBN: o-l3-119402-X

... man's glory lieth in his knowledge, his upright conduct, his praiseworthy character, his wisdom, and not in his nationality or rank. - Baha'u'llah

CONTENTS AT A GLANCE

CHAPTERS I

0: I:

2: 3: 4:

s: 6: 7: 8: 9: Ed Ed PI

10: II:

De

12:

Co

13:

Co

14:

PI So So

IS: 16: 17:

Introduction to Computing The 8051 Microcontrollers 8051 Assembly Language Programming Jump, Loop, and Call Instructions I/O Port programming 80SI Addressing Modes Arithmetic & Logic Instructions and Programs 80SI Programming in C 80SI Hardware Connection and Intel Hex File 8051 Timer Programming in Assembly and C 80SI Serial Port Programming in Assembly and C Interrupts Programming in Assembly and C LCD and Keyboard Interfacing ADC. DAC. and Sensor Interfacing 8051 Interfacing to External Memory 8051 Interfacing with the 8255 DS12887 RTC Interfacing and Programming Motor Control: Relay, PWM. DC. and Stepper Motors

23 37 69 9 109 1'9 I I

217 2 9

277 317 51 37 411 449 467 491

APPENDICES A: B: C: 0:

E: F:

G: H:

8051 Timing and Registers . B. Instructions . asrcs of WIre Wrapping Ie Technology adS . Issues FI h n ystem DeSIgn Owe arts and Pseudocode 8051 Primer for X86 P ASCII Codes rogrammers I

,

Assemblers. Development R Data Sheets eSOurces. and Suppliers

52

56 567 7 592 593

594 596

CONTENTS CHAPTER 0: INTRODUCTION TO COMPUTING Section 0.1: Numbering and coding systems Section 0.2: Digital primer Section 0.3: Inside the computer

CHAPTER 1: THE 8051 MICROCONTROLLERS Section 1.1: Microcontrollers and embedded processors Section 1.2: Overview of the 8051 family CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING Section Section Section Section Section Section Section

2.1: 2.2: 2.3: 2.4: 2.5: 2.6: 2.7:

Inside the 8051 Introduction to 8051 Assembly programming Assembling and running an 8051 program The program counter and ROM space in the 8051 8051 data types and directives 8051 flag bits and the PSW register 8051 register banks and stack

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS Section 3.1: Loop and jump instructions Section 3.2: Call instructions Section 3.3: Time delay for various 8051 chips

CHAPTER 4: I/O PORT PROGRAMMING Section 4.1: 8051 I/O programming Section 4.2: I/O bit manipulation programming

CHAPTER 5: 8051 ADDRESSING MODES Section Section Section Section

5.1: Immediate and register addressing modes 5.2: Accessing memory using various addressing modes 5.3: Bit addresses for I/O and RAM 5.4: Extra 128-byte on-chip RAM in 8052

CHAPTER 6: ARITHMETIC & LOGIC INSTRUCTIONS AND PROGRAMS Section Section Section Section Section

-

6.1: 6.2: 6.3: 6.4: 6.5:

Arithmetic instructions Signed number concepts and arithmetic operations Logic and compare instructions Rotate instruction and data serialization BCD, ASCII, and other application programs

1 2 9 13

23 24 28 37 38 41 44 46 49 52 55

69 70 75 80

93 94 100

109 110 112 122 13\

139 140 150 155 161 :167

v

CHAPTER

7: 8051 PROGRAMMING

Section Section Section Section Section Section

7.1: 7.2: 7.3: 7.4: 7.5: 7.6:

IN C

Data types and time delay in 805 I C I/O programming in 8051 C Logic operations in 8051 C Data conversion programs in 8051 C Accessing code ROM space in 8051 C Data serialization using 8051 C

CHAPTER 8: 8051 HARDWARE INTEL HEX FILE

CONNECTION

AND

Section 8.1: Pin description of the 805 I Section 8.2: Design and test of DS89C4xO trainer Section 8.3: Explaining the Intel hex file CHAPTER 9: 8051 TIMER IN ASSEMBLY AND C

CHAPTER 10: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 10.1: 10.2: 10.3: 10.4: 10.5:

Basics of serial communication 8051 connection to RS232 8051 serial port programming in Assembly Programming the second serial port Serial port programming in C

CHAPTER II: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C Section I 1.1: 8051 interrupts Section 11.2: Programming timer interrupts Section I 1.3: Programming external hardware interrupts Section 11.4: Programming the serial communication interrupt Section I1.5: Interrupt priority in the 8051/52 Section 11.6: Interrupt programming in C CHAPTER 12: LCD AND KEYBOARD Section 12.1: LCD interfacing Section 12.2: Keyboard interfacing

INTERFACING

CHAPTER 13: ADC, DAC, AND SENSOR INTERFACING Section 13. I: Parallel and serial ADC Section 13.2: DAC interfacing Section 13.3: Sensor interfacing and signal conditioning

VI

217 218 224 232

PROGRAMMING

Section 9.1: Programming 8051 timers Section 9.2: Counter programming Section 9.3: Programming timers 0 and I in 8051 C

Section Section Section Section Section

181 182 188 194 199 204 209

239 240 255 260

277 278 285 287 300 306

317 318 322 326 333 337

340 351 352 363

373 374 398 403

CHAPTER 14: 8051 INTERFACING TO EXTERNAL MEMORY Section 14.1: Sem iconductor memory Section 14.2: Memory address decoding Section 14.3: 803 1/51 interfacing with external ROM Section 14.4: 8051 data memory space Section 14.5: Accessing external data memory in 8051 C

411 412 422 425 430 440

CHAPTER 15: 8051INTERFACING WITH THE 8255 Section 15.1: Programming the 8255 Section 15.2: 8255 interfacing Section J 5.3: 8051 C programming for the 8255

449 450 458 462

CHAPTER 16: DS12887 RTC INTERFACING AND PROGRAMMING Section 16.1: DS 12887 RTC interfacing Section 16.2: OSI2887 RTC programming in C Section 16.3: Alarm, SQW, and IRQ features of the DS 12887 chip

479

CHAPTER 17: MOTOR CONTROL: RELAY, PWM, DC, AND STEPPER MOTORS Section 17.1: Relays and optoisolators Section 17.2: Stepper motor interfacing Section 17.3: DC motor interfacing and PWM

491 492 498 507

APPENDIX A: 8051 INSTRUCTIONS, TIMING, AND REGISTERS

523

APPENDIX B: BASICS OF WIRE WRAPPING

563

APPENDIX C: IC TECHNOLOGY AND SYSTEM DESIGN ISSUES

567

APPENDIX D: FLOWCHARTS AND PSEUDOCODE

587

APPENDIX E: 8051 PRlMER FOR X86 PROGRAMMERS

592

APPENDIX F: ASCll CODES

593'

APPENDIX G: ASSEMBLERS, DEVELOPMENT RESOURCES, AND SUPPLIERS

594

APPENDIX H: DATA SHEETS

596

INDEX

617

467 468 476

vii

K .. ,ad....,

h J In III Iroduc 1(1) dlgilal 'our e. Knowledge of hIp/iii ut I n t neces ry. A hhough the book is tt lund in,~ 'mhly language programming, stupcncnce w ill be able 10 gain a ma tery of nd I.m on their proje ts right away. For the 8051 ~ k, a ha", knowledge of C programming is

.h I used to cover various aspects of 1.1II,1I"",£;e 1)1' • mrrung and interfacing. Many examples and n 10 I tI f) the concept and provide students with an din' Rev le\\ qu lions are provided at the end of each m n POlOt of lh ecuon. ver num f t m (bmary. decimal, and hex), and provides J • nd mpuier terminology. This is designed h nical engineering students, who have not \ ho need to refresh their memory on these ..",.n,·.

ICp ppr

the 0 I and feature of other 8051 famI. n ~OOO.and D 9C4xO. It also prohIp •

r hue lure 0/ the -to-run program.

0 I and explains the It also explores the

In Chapter 3 the topics of loop, jump, and call instructions are discussed, with many programming examples. Chapter 4 is dedicated to the discussion of I/O ports. This allows students who are working on a project to start experimenting with 8051 I/O interfacing and start the project as soon as possible. Chapter 5 covers the 8051 addressing modes and explains how to use the code space of the 8051 to store data, as well as how to access data. Chapter 6 is dedicated to arithmetic, logic instructions, and programs. The C programming of the 8051 is covered in Chapter 7. In Chapter 8 we discuss the hardware connection of the 8051 chip. Chapter 9 describes the 8051 timers and how to use them as event counters. Chapter 10 is dedicated to serial data communication of the 8051 and its interfacing to the RS232. It also shows 8051 communication with COM ports of the [BM PC and compatible computers. In addition, the second serial port of the DS89C4xO is also covered. Chapter 11 provides a detailed discussion of 8051 interrupts with many examples on how to write interrupt handler programs. Chapter 12 shows 8051 interfacing with real-world devices such as LCDs and keyboards. Chapter 13 shows 8051 interfacing with real-world devices such as DAC chips, ADC chips, and sensors. In Chapter 14 we cover 8031/51 interfacing with external memories, both ROM and RAM. Chapter 15 addresses the issue of adding additional ports to the 8031/51 using an 8255 chip. Chapter 16 shows how to connect and program the DS 12887 real-time clock chip. Finally, Chapter 17 shows basic interfacing to relays, optoisolators, and motors. The appendices have been designed to provide all reference material required for the topics covered in the book. Appendix A describes each 8051 instruction in detail, with examples. Appendix A also provides the Clock count for instructions, 8051 register diagrams, and RAM memory maps. Appendix B describes basics of wire wrapping. Appendix C covers IC technology and logic families, as well as 8051 I/O port interfacing and fan-out. Make sure you study this before connecting the 8051 to an external device. 1n Appendix D, the use of flowcharts and psuedocode is explored. Appendix E is for students familiar with x86 architecture who need to make a rapid transition to 8051 architecture. Appendix F provides the table of ASCII characters. Appendix G lists resources for assembler shareware, and electronics parts. Appendix H contains data sheets for the 8051 and other IC chips.

ix

ond edition .. of 0-1 program. edition is the addition A sembI languag this new 6 blyand use The biggest change inWhile Chapters I t hough r language pr _ ve both Assem ming throughou t ,the book. ith ChapterI 7, we haddition includes t h e following new . Iy, starting .ws discussed. The secon e exclusive grams for all the topic

What is new in the sec

features:

.

(Chapter 7)

8051 C programming . ers ( ection 9.3) Anew chapter 00 he 80" C programm ing of ";89O_-;6,.-. 3:;---;;B-;;jt-;A-:;d::;dc:::r:-;u'7:s7:in::g:-::3~F;;:u:-;III'A;;;:dd;;:c::r-:s __

1~1l

LSU

()

-{)o-

ddre, deCOder for 9 (binary 100 I) I he output of Ihe AND gate will be , II und only If Ihe Inpur i~ binary 100 I.

(b) Address decoder for 5 (binary 0101) The output of the AND gate will be I ifand only iflhe input is binary 0101.

OecOders 0

D

Q

II.

Ik Q (~)

Q

'rcull draglllm

-

elk No 11-

D x

0 I

x .::::: don', care

(b) BlOck diagram (c)

Truth table

/2

-

Review Questions 1. The logical operation 2. The logical operation __ 3. The logical operation __ same value .

gives a I output when all inputs are I. gives a 1 output when I or more of its inputs is I. is often used to compare if two inputs have the

. 4. A __ gate does not change the logic level of the input. 5. Name a common use for flip-flops. 6. An address is used to identify a predetermined binary address.

SECTION 0.3: INSIDE THE COMPUTER Tnthis section we provide an introduction to the organization and internal working of computers. The model used is generic, but the concepts discussed are applicable to all computers, including the IBM PC, PS/2, and compatibles. Before embarking on this subject, it will be helpful to review definitions of some of the most widely used terminology in computer literature, sueh as K, mega, giga, byte, ROM, RAM, and so on.

Some important terminology One of the most important features of a computer is how mueh memory it has. Here we review terms used to describe amounts of memory in IBM pes and compatibles. Recall from the discussion above that a bit is a binary digit that can have the value 0 or 1. A byte is defined as 8 bits. A nibble is half a byte, or 4 bits. A Bit a 0000 word is two bytes, or 16 bits. The display is Nibble 0000 0000 intended to show the relative size of these Byte Word 0000 0000 0000 0000 units. Of course, they could all be composed of any combination of zeros and ones. A kilobyte is 210 bytes, which is 1024 bytes. The abbreviation K is often used. For example, some floppy disks hold 356K bytes of data. A megabyte, or meg as some call it, is 220 bytes. That is a little over I million bytes; it is exaetly 1,048,576 bytes. Moving rapidly up the scale in size, a gigabyte is 230 bytes (over I billion), and a terabyte is 240 bytes (over 1 trillion). As an example of how some of these terms are used, suppose that a given computer has 16 megabytes of memory. That would be 16 x 220, or 24 x 220, which is 224 Therefore, 16 megabytes is 224 bytes. Two types of memory commonly used in microcomputers are RAM, which stands for "random access memory" (sometimes called read/write memory), and ROM, which stands for "read-only memory." RAM is used by the computer for temporary storage of programs that it is running. That data is lost when the COIllputer is turned off. For this reason, RAM is sometimes called volatile memory. ROM contains programs and information essential to operation of the computer. The information in ROM is permanent, cannot be changed by the user, and is not lost when the power is turned off. Therefore, it is called nonvolatile memory, CHAPTER 0: INTRODUCTION TO COMPUTING

13

Internal organization of computers The internal working of every computer can be broken down into three parts: CPU (central processing unit), memory, and I/O (input/output) devices (see Figure 0-9). The function of the CPU is to execute (process) information stored in memory. The function of I/O devices such as the keyboard and video monitor is to provide a means of communicating with the CPU. The CPU is connected to memory and I/O through strips of wire called a bus. The bus carries infomlation from place to place inside a computer just as a street bus carries people from place to place. In every computer there are three types of buses: address bus, data bus, and control bus. For a device (memory or I/O) to be recognized by the CPU, it must be assigned an address. The address assigned to a given device must be unique; no two devices are allowed to have the same address. The CPU puts the address (in binary, of course) on the address bus, and the decoding circuitry finds the device. Then the CPU uses the data bus either to get data from that device or to send data to it. The control buses are used to provide read or write signals to the device to indicate if the CPU is asking for information or sending it information. Of the three buses, the address bus and data bus determine the capability of a given CPU. Address Bus

Memory

Peripherals

(RAM, ROM)

(monitor, printer, etc.)

CPU

Data Bus Figure 0-9. Inside the Computer

More about the data bus incc data lines arc used to carry information' data lines available, the better the CPU If m and out of a CPU, the more lane, it is clear that more lanes pro id . bone thinks of data lines as highway . VI e a ettcr pathw b external devices (such as printers, RAM ROM ay etween the CPU and its same token, that increase in the b f' .' etc., see FIgure 0-10). By the M num cr 0 lanes m . rc data bu es mean a more expensive CPU an creases the cost of construction. line IScalled data bus. The avcragc si d computer. The grouping of data d 64 E e size of data b . C an . arly computers such as Apple 2 u d uses m PUs varies between 8 puters ueh as Cray use a 64-bit data bus D: an S-bit data bus, while supercomPU must use them either to receive or t~ s a~ dbusesare bidirectional, since the eomputcr IS related to the size f' en ata. The processin a time, but a 16-bit bOlts buses, since an 8-bit bu g power of a us can send OUI 2 bytes I' S can send out I byte a a lime , W hiic h iIS twice . as fast 14



.

More about the address bus Since the address bus is used to identify the devices and memory connected to the CPU, the more address buses available, the larger the number of devices that can be addressed. In other words, the number of address buses for a CPU determines the number of locations with which it can communicate. The number

I

of locations is always equal to 2x, where x is the number of address lines, regardless of the size of the data bus. For example, a CPU with 16 address lines can provide a total of 65,536 (216) or 64K bytes of addressable memory~ Each location can have a maximum of I byte of data. This is due to the fact that all general-purpose microprocessor CPUs are what is called byte addressable. As another example, the IBM PC AT uses a CPU with 24 address lines and 16 data lines. In this' case the, total accessible memory is 16 megabytes (224

=

16 megabytes). In this

224

example there would be locations, and since each location is one byte, there would be 16 megabytes of memory. The address bus is a unidirectional bus, which means that the CPU uses the address bus only to send out addresses. To summarize: The total number of memory locations addressable by a given CPU is always equal to 2x where x is the number of address bits, regardless of the size of the data bus. Address Bus

• RAM

~

ROM

Printer



Disk



Monitor



Keyboard

CPU

Data Bus Read/write

Control Bus

Figure 0-10. Internal Organlzation of Computers

CPU and its relation to RAM and ROM For the CPU to process information, the data must be stored in RAM or ROM. The function of ROM in computers is to provide information that is fixed and permanent. This is information such as tables for character patterns to be displayed on the video monitor, or programs that are essential to the working of the computer, such as programs for testing and finding the total amount of RAM installed on the system, or programs to display information on the video monitor. In contrast, RAM is used to store information that is not permanent and can change with time, such as various versions of the operating system and application packages such as word processing or tax calculation packages. These programs are loaded into RAM to be processed by the CPU. The CPU cannot get the informa-

CHAPTER 0: INTRODUCTION TO COMPUTING

15

. ., slow. In other wor d s, th e CPU first tion directly from the disk since the disk IS~~M (or ROM). Only ifit IS not there seeks the information to be processed fromdeviee such as a disk, and then It transh CPU seek it from a mass storage RAM and ROM are sometimes docs t e . RAM For this reason, Figure fers the information to . d di k are called secondary memory . .' . memOlY an IS s . h PC referred to as primary f the internal organizatIOn of t e . 0-11 shows a block diagram 0

Program Counter

Flags

Instruction Register

ALU

lnstruction decoder, timing, and control Internal buses

Register A Register B Register C Register 0 Figure

0-11.

Internal Block Diagram of a CPU

Inside CPUs A program stored in memory provides instructions to the CPU to perform an action. The action can simply be adding data such as payroll data or controlling a machine such as a robot. It is the function of the CPU to fetch these instructions from memory and execute them. To perform the actions of fetch and execute, all P s arc equipped with resources such as the following: I. Foremost among the resources at the disposal of the CPU are a number of registers. The CPU uses registers to store information temporari Iy. The information could be two values to be processed, or the address of the value needed to be fetched from memory. Registers inside the CPU can be 8-bit, 16-bit, 32-bit, or even 64-bit registers, depending on the CPU. In general, the more and bigger the registers, the better the CPU. The disadvantage of more and bigger registers is the increased cost of such a CPU. 2. The CPU also has what is called theALU (arithmetic/logic unit). The ALU section of the PU is responsible for performing arithmetic functions such as add ubtract, multiply, and divide, and logic functions such as AND, OR, and NOT: Every CPU has what is called a program COUnter. The function of the program 16

7

counter is to point to the address of the next instruction to be executed. As each instruction is executed, the program counter is incremented to point to the address of the next instruction to be executed. The contents of the program counter are placed on the address bus to find and fetch the desired instruction. In the IBM PC, the program counter is a register called IP, or the instruction pointer. . 4. The function of the instruction decoder is to interpret the instruction fetched' into the CPU. One can think of the instruction decoder as a kind of dictionary, storing the meaning of each instruction and what steps the CPU should take upon receiving a given instruction. Just as a dictionary requires more pages the more words it defines, a CPU capable of understanding more instructions requires more transistors to design. i

Internal working of computers To demonstrate some of the concepts discussed above, a step-by-step analysis of the process a CPU would go through to add three numbers is given next. Assume that an imaginary CPU has registers called A, B, C, and D. It has an 8-bit data bus and a 16-bit address bus. Therefore, the CPU can access memory from addresses 0000 to FFFFH (for a total of 10000H locations). The action to be performed by the CPU is to put hexadecimal value 21 into register A, and then add to register A values 42H and 12H. Assume that the code for the CPU to move a value to register A is 1011 0000 (BaH) and the code for adding a value to register A is 0000 a 100 (04H). The necessary steps and code to perform them are as follows.

Action Move Add Add

value value value

21H 42H 12H

into

register

to register to register

A

A A

Code

Data

BOH

21H

04H

42H 12H

04H

If the program to perform the actions listed above is stored in' memory locations starting at 1400H, the following would represent the contents for each memory address location:

Memory address

Contents of memory address

1400 1401 1402 1403 1404 1405 1406

(BO)code (21)value (04)code (42)value (04)code (12)value (F4)code

for to for to for to for

moving a value be moved adding a value be added adding a value be added halt

to register

A

to regist'er A to register

A

The actions performed by the CPU to run the program above would be as follows: 1. The CPU's program counter can have a value between 0000 and FFFFH. The program counter must be set to the value 1400H, indicating the address of the first instruction code to be executed. After the program counter has been

CHAPTER 0: INTRODUCTION TO COMPUTING

17

loaded with the address of the first instruction, the CPU is ready to execute" 2, The CPU puts 1400H on the address bus and sends it out. The memory CIrcuitry finds the location while the CPU activates the READ signal, mdleatmg to memory that it wants the byte at location 1400B. This causes the contents of memory location 1400H, which is 80, to be put on the data bus and brought into the CPU, 3, The CPU decodes the instruction 80 with the help of its instruction decoder dictionary, When it finds the definition for that instruction it knows it must bring into register A of the CPU the byte in the next memory location, Therefore, it commands its controller circuitry to do exactly that. When it brings in value 21 H from memory location 140 I, it makes sure that the doors of all registers are closed except register A, Therefore, when value 21 H comes into the CPU it will go directly into register A, After completing one instruction, the program counter points to the address of the next instruction to be executed, which in this case is 1402H, Address 1402 is sent out on the address bus to fetch the next instruction, 4, From memory location 1402H it fetches code 04H. After decoding, the CPU knows that it must add to the contents of register A the byte sitting at the next address (1403), After it brings the value (in this case 42H) into the CPU, it providcs the contents of register A along with this value to the ALU to perform the addition, It then takes the result of the addition from the ALU's output and puts u m register A, Meanwhile the program counter bceomes 1404, the address of tile next instruction, 5, Address 1404H is put on the address bus and the code is fetched into the CPU decoded, and executed, This code is again adding a value to register A, The program counter IS updated to 1406H, 6, Finally. tbc contents of address 1406 arc fetched in and executed, This HALT tells to stop incrementing the program counter and asking ' fmstrucuon th ' the CPU , or e next instruction. In the absence of the HALT tl CPU Id ' t pd ti h ,1e wou connnue I a II1g t e program counter and fetching instructions, Now suppose that address 1403H contain d I ' would the CPU distinguish between data 04 to b: adv:,~e 04 Instead of 42H. How that code 04 for this CPU means move the next val e . and code 04? Remember the PU wi II not try to decodc the next value. It si uc Into register A. Therefore, Iollowing mcmory location into reg' t A mply moves the contents of the IS er ,regardless of its value,

Review Questions I, 2. 3. 4 . 5. 6. 7,

How many bytes is 24 kilobytes? What docs "RAM" stand Cor? Ho ' , " , r W IS It u"ed ' W hat docs "ROM" stand f< ? H " s 111 computer systems? Wh ' RA or, ow IS It used i ' . Y IS M called volatile mcmor ') n computer systems? List the three major com y, What docs "CPU" t d ~onents of a computcr system ' san for? Explain it f' ' L I t the three types of b 'c ,s unction in a computer uses round 111 COl ' purpose of each type of bus nputer systems and state b ' fl 8, tate which of the followi " " ne y the ng IS unidirectional and hi h i " W IC IS bidirectional. 18

(a) data bus (b) address bus 9. If an address bus for a given computer has 16 lines, what is the maximum amount of memory it can access? 10. What does "ALU" stand for? What is its purpose? II . How are registers used in computer systems? 12. What is the purpose of the program counter? 13. What is the purpose of the instruction decoder?

SUMMARY The binary number system represents all numbers with a combination of the two binary digits, 0 and I. The use of binary systems is necessary in digital computers because only two states can be represented: on or off.' Any binary number can be coded directly into its hexadecimal equivalent for the convenience of humans. Converting from binary/hex to decimal, and vice versa, is a straightforward process that becomes easy with practice. The ASCII code is a binary code used to represent alphanumeric data internally in the computer. It is frequently used in peripheral devices for input and/or output. The logic gates AND, OR, and Inverter are the basic building blocks of simple circuits. NAND, NOR, and XOR gates are also used to implement circuit design. Diagrams of half-adders and full-adders were given as examples of the use of logic gates for circuit design. Decoders are used to detect certain addresses. Flip-flops are used to latch in data until other circuits are ready for it. The major components of any computer system are the CPU, memory, and I/O devices. "Memory" refers to temporary or permanent storage of data. In most systems, memory can be accessed as bytes or words. The terms kilobyte, megabyte, gigabyte, and terabyte are used to refer to large numbers of bytes. There are two main types of memory in computer systems: RAM and ROM. RAM (random access memory) is used for temporary storage of programs and data. ROM (read-only memory) is used for permanent storage of programs and data that the computer system must have in order to function. All components of the computer system are under the control of the CPU. Peripheral devices such as 1/0 (input/output) devices allow the CPU to communicate with humans or other computer systems. There are three types of buses in computers: address, control, and data. Control buses are used by the CPU to direct other devices. The address bus is used by the CPU to locate a device or a memory location. Data buses are used to send information back and forth between the CPU and other devices. Finally, this chapter gave an overview of digital logic.

CHAPTER 0: INTRODUCTION TO COMPUTING

7

19

PROBLEMS SECTIO

0.1: NUMBERING

AND CODING SYSTEMS

I. Convert the following decimal numbers to binary. (a) 12 (b) 123 (c) 63 (d) 128 (c) 1000 2. Convert the following binary numbers to decimal. (a) 100100 (b) 1000001 (c) 11101 (d) 1010 (e) 00100010 3. Convert the values in Problem 2 10 hexadecimal. 4. onvert the following hex numbers to binary and decimal. (a) 2891-1 (b) 1'441-1 (e) 9121-1 (d) 2BI-I (c) FFFFI-I S. onvcrt the values in Problem I to hex. 6. Find the 2 's complement of the following binary numbers. (a) 1001010 (b) 111001 (e) 10000010 (d) 111110001 7. Add the following hex values. (a) 2CI-I + 3FI-1 (b) 1'341-1+ SD61-1 (c) 200001-1 + 12FFI-I (d) FFFFI-I + 22221-1 8. Perform hex subtraction for the following. (a) 241'1-1- 1291-1 (b) FE91-1- SCCI-I (c) 2FFFFI-I - FFFFFI-I (d) 9FF2SI-I4DD991-1 9. Show the ASCII codes for numbers 0, 1,2, 3, ...,9 in both hex and binary. '10. Show the ASCII code (in hex) for the following string: "U.S.A. is a country" CR, LF "in North America" CR, LF CR is carriage return LF is line feed ECTION 0.2: DIGITAL PRIMER II. Draw a 3-input OR gate using a 2-input OR gate . • 12. Show the truth table for a 3-input OR gate. 13. Draw a 3-inpllt AND gate using a 2-input AND gate . • 14. Sho:" the truth table for a 3-input AND gate. __ IS. Design a 3-mpllt XOR gate with a 2-input XOR te Sh a 3-inpllt XOR. ga e. ow the truth table for 16. List the truth table for a 3-input NAND. '17. List the truth table for a 3-inpllt NOR. 18. how the decoder for binary 1100. 19. ~ow the decoder for binary 110 II . • 20. List the truth table for a D-FF. I E TIO

0.3: INSIDE TI-IE COMPUTER

21. Answer the follOWing: (a) How many nibbles are 16 bits? (b) How many bytes are 32 bi ? . ItS. (c) If a word is defined as 16 bits h (d) Wh . I S, ow many ds : at IS the exact value (in de' I) war S IS a 64-bit data itemry erma of I meg? . 20

(e) (t) (g) (h) (i)

How many K is 1 meg? What is the exact value (in decimal) of I giga? How many K is I giga? How many meg is I giga? If a given computer has a total of 8 megabytes of memory, how many bytes (in decimal) is this') How many kilobytes is this') 22. A given mass storage device such as a hard disk can store 2 gigabytes of information. Assuming that each page of text has 25 rows and each row has 80 columns of ASCII characters (each character = I byte), approximately how many pages of information can this disk store? 23. In a given byte-addressable computer, memory locations 10000H to 9FFFFH are available for user programs. The first location is 10000H and the last location is 9FFFFH. Calculate the following: (a) The total number of bytes available (in decimal) (b) The total number of kilobytes (in decimal) 24. A given computer has a 32-bit data bus. What is the largest number that can be carried into the CPU at a time? 25. Below are listed several computers with their data bus widths. For each computer, list the maximum value that can be brought into the CPU at a time (in both hex and decimal). (a) Apple 2 with an 8:bit data bus (b) IBM PC with a lti-bit data bus (c) IBM PC with a 32-bit data bus (d) Cray supercomputer with a 64-bit data bus . 26. Find the total amount of memory, in the units requested, for each of the following CPUs, given the size of the address buses. (a) I 6-bit address bus (in K) (b) 24-bit address bus (in megabytes) (c) 32-bit address bus (in megabytes and gigabytes) (d) 48-bit address bus (in megabytes, gigabytes, and terabytes) 27. Regarding the data bus and address bus, which is unidirectional and which is bidirectional? 28. Which register of the CPU holds the address of the instruction to be fetched? 29. Which section ofthe CPU is responsible for performing addition? 30. List the three bus types present in every CPU.

ANSWERS TO REVIEW QUESTIONS SEcrrON

0.1: NUMBERING AND CODING SYSTEMS

I.

Computers use the binary system because each bit can have one of two voltage levels: on and

2. 3.

off. 3410 = 1000102 = 2216 1101012=3516=5310

4. 5.

1110001 010100

6.

461

7.

275

CHAPTER 0: INTRODUCTION TO COMPUTING

7

21

8.

38 30 78 38 36 2043 50 55 73

SECTIO

0.2: DIGITAL PRIMER

I. AND

2. OR 3. XOR 4. BulTer 5. Storing data 6. Decoder ECTION 0.3: INSIDE THE COMPUTER I. 24,576 . 2. Random access memory; it is used for temporary storage of programs that the CPU IS running, such as the operating system, word processing programs, etc. Read-only memory; it is used for permanent programs such as Ihose that control the keyboard. etc. 4, The contents of RAM arc lost when the computer is powered 01T. 5. The CPU, memory, and 110 devices 3.

6.

Central processing unit; it can be consideredthe "brain" or the computer; it executes the pro. grams and controls all other devices in the computer.

7.

The address bus carries Ihe location (address) needed by the CPU; the data bus carries information in and out ofthe CPU; the control bus is used by the CPU 10 send signals controlling I/O devices, (aJ bidirectional (b) unidirectional 64K. or 65,536 byres Arithmetic/logic unit; it performs all arithmetic and logic operations It IS for temporary storage of information It holds the address of the next instruclion to be executed, It tells the CPU what steps to perform for each instruction,

R.

9. 10. 1I. 12. 13.

-

CHAPTER 1

THE 8051

MICROCONTROLLERS

OBJECTIVES Upon completion of this chapter, you will be able to:

» » »

» » » »

Compare and contrast microprocessors and microcontrollers Describe the advantages of microcontrollers for some applications Explain the concept of embedded systems Discuss criteria for considering a microcontroller Explain the variations of speed, packaging, memory, and cost per unit and how these affect choosing a microcontroller Compare and contrast the various members of the 8051 family Compare 8051 microcontrollers offered by various manufacturers

23

This chapter begins with a discussion of the role and importance of microcontrollers in everyday life. In Section 1.1 we also discuss cntena to consider In choosing a microcontroller, as well as the usc ofmicrocontroUers In the embedded market. Section 1.2 covers various members of the 8051 family such as the 8052 and 8031, and their features. In addition, we discuss vanous versions of the 8051 such as the 8751, AT89C51, and OS5000.

SECTION 1.1: MICROCONTROLLERS PROCESSORS

AND EMBEDDED

In this section we discuss the need for microcontrollers and contrast them with general-purpose microprocessors such as the Pentium and other x86 microprocessors. We also look at the role of microcontrollers in the embedded market. In addition, we provide some criteria on how to choose a microcontroller.

Microcontroller versus general-purpose

microprocessor

What is the difference between a microprocessor and rnicrocontrollcr? By microprocessor is meant the gencral-purpose microprocessors such as Intel's x86 family (8086,80286,80386,80486, and the Pcntium) or Motorola's 680xO family (68000,68010,68020,68030,68040, etc.). These microprocessors contain no RAM, no ROM, and no I/O ports on the chip itself. For this reason, they are commonly referred to as general-purpose microprocessors.

CPU GeneralPurpose Mieroprocessor

D ata b us

r

I

.i.

I

I

RAM

ROM

VO Port

Timer

Serial COM Port

T

I

I

I

Addresss bus

,

CPU

I/O

RAM

Timer

I

eSSor ystem Contrasted With M' Icrocontroller System A system dcsigner using a general . Pcmium or the 68040 must add RAM RO~urpose mlcroproccssor such as the makc them functional. Although th addi ' I/O ports, and timers externally to ports makes these systems bUlkier an~ ~u !tlon of external RAM, ROM, and I/O tage of versatility SUchthat the desi ch more expenSive, they have the adva and I/O esigncr can decide th nports needed to fit the t k h . on e arnounr of RAM ROM d trollers. A microcontroller has :scpa~ . This IS not the ease with mi~rocon~ amOunt of RAM ROM I/O a microprocessor) in add't' the processor, RAM ROM it~rts, and a timer all on a single chip ; Ion ~o a fixed chip; thercfore the de .' ports, and timer are all embedd d' n ot cr words, Thc fixed amo~nt of o~~ner cannot add any cxtcrnal memo e togcthcr on one trollers makcs them idea~~IP ROM, RAM, and number of 116' 110, or umer to it. or many applteations in whi h ports in mlCrocon_ 24 IC Cost and space are. Cntl' .

t

ROM

Serial COM Port

Home

Appliances Intercom Telephones Security systems Garage door openers Answering machines Fax machines Home computers TVs Cable TV tuner VCR Camcorder Remote controls Video games Cellular phones Musical instruments Sewing machines Lighting control Paging Camera Pinball machines Toys Exercise equipment Office

Telephones Computers Security systems Fax machine Microwave Copier Laser printer Color printer Paging Auto

Trip computer Engine control Air bag ABS Instrumentation Security system Transmission control Entertainment Climate control Cellular phone Keyless entry Table I-I: Some Embedded Products Using Microcontrollers

cal. In many applications, for example a TV remote control, there is no need for the computing power of a 486 or even an 8086 microprocessor. In many applications, the space it takes, the power it consumes, and the price per unit are much more critical considerations than the computing power. These applications most often require some I/O operations to read signals and tum on .'and off certain bits. For this reason some call these processors lBP, "itty-bitty processors" (see "Good Things in Small Packages Are Generating Big Product Opportunities" by Rick Grehan, BYTE magazine, September 1994; www.byte.com, for an excellent discussion of microcontrollers). It is interesting to note that some microcontroller manufacturers have gone as far as integrating an ADC (analog-to-digital converter) and other peripherals into the microcontrolJer.

Microcontrollers for embedded systems In the literature discussing microprocessors, we often see the term embedded system. Microprocessors and microcontrollers are widely used in embedded system products. An embedded product uses a microprocessor (or microcontroller) to do one task and one task only. A printer is an example of embedded system since the processor inside it performs only one task; namely, getting the data and printing it. Contrast this with a Pentium-based PC (or any x86 IBM-compatible PC). A PC can be used for any number of applications such as word processor, print server, bank teller terminal, video game player, network server, or internet terminal. Software for a variety of applications can be loaded and run. Of course the reason a PC can perform myriad tasks is that it has RAM memory and an operating system that loads the application software into RAM and lets the CPU run it. In an embedded system, there is only one application software that. is typically burned into ROM. An x86 PC contains or is connected to varIOUS embedded products such as the keyboard, printer, modem, disk controller, sound card, CD-ROM driver, mouse, and so on. Each one of these peripherals has a microcontroller inside it that performs only one task. For example, inside every mouse there is a microcontroller that performs the task of finding the mouse position and sending it to the Pc. Table I-I lists some embedded products.

X86 PC embedded applications Although microcontrollers are the preferred choice for many embedded systems, there are times that a microcontroller is . inadequate for the task. For this reason, in recent years many manufacturers of general-purpose microprocessors such as Intel, Freescale Semiconductor Inc. (formerly Motorola), AMD (Advanced Micro Devices, lnc.), and Cyrix (now a division of

CHAPTER 1: THE 8051 MICROCONTROLLERS

25

National Semiconductor, Inc.) have targeted their microprocessor for the high end of the embedded market. While Intel and AMD push their x86 processors for both the embedded and desktop PC markets, Freescale is determined to keep the 68000 family alive by targeting it mainly for the high end of embedded systems now that Apple no longer uses the 680xO in their Macintosh. In the early 1990s Apple computer began using Power PC microprocessors (604,603,620, erc.) in place of the 680xO for the Macintosh. The Power PC microprocessor is ajoint venture between IBM and Freeseale, and is targeted for the high end of the embedded market as well as the PC market. It must be noted that when a company targets a generalpurpose microprocessor for the embedded market it optimizes the processor used for embedded systems. For this reason these processors arc often called high-end embedded processors. Very often the terms embedded processor and microcon'roller arc used interchangeably. One of the most critical needs of an embedded system is to decrease power consumption and space. This can be achieved by integrating more functions into the CPU chip. All the embedded processors based on the x86 and 680xO have low po~er consumptron tn addition to some forms of I/O, COM port, and ROM all a single chip. In "high-perform anee em b e dd ed processors, the trend IS . to .Integrateon more and more functions on the CPU chip and let the designer decide which feaNorn he/she wants to use. This trend is invading PC system design as well ormally, tn designing the PC motherboard we need a CPU plus a cbi . tainmg I/O, a cache controller, a flash ROM containing BIOS and f et eonondary cache memory. New designs are erne . . . ' tna y a se g has announced that it is working on a chi t;gtn tn tndustry. For example, yrix DRAM. In other words, we arc about to :~e an contams the enure PC, except for Currently, because of MS-DOS ; e;.lre computer on a chip. embedded systems arc using x86 PC I an indows standardization many end embedded applications not onl s. n many cases using x86 PC for the hight' . Y saves money but I h nne since there is a vast II'b f f a so s ortens development W' rary 0 so tware al d . indows platforms. The fact th t W' d . rea y written for the DOS and I r. a tn ows IS a id I p auorm means that developing a Windows_ WI e Y used and well understood co t and shortens the development time bdased embedded product reduce the consi erably.

I~;

Choosing a microcontroller There arc four rna' '. Intel's 8051 Zilo ' ~or 8-blt mlerOcontrollers Th mieroeontr;lIers ~a: :8~ and PIC 16X from Microchip Freeseale's 6811, not compatible w'th nlque instruction set and reoi no ogy. Each of these I each othe P egrste- set: th f ers. There arc also 16-bit and r. rograms written for one will ere ore, they are crs, With all these dl'fIi 32-bll mleroeontrollers d not run on the oth. hoosi erent mie ma e by vari . 111 COOing one? Three . . roeontrollers, what eri' anous chIp makmeeling the eompulin entena 111 choosing mieroeo ten a do deSIgners consider (2) availability of soft g needs of the task at hand ffi ntrollers are as follows' (I) debugger, and (J) wi;are development tools sue~ lelently and cost effecti~e1 ext we elaborate limh e availability and reliable s as compilers, aSScmblers and cr on each of h ourees of the' , t e above criteria mleroController.

T~~tei

26

Criteria for choosing a microcontroller 1. The first and foremost criterion in choosing a microcontroller is that it must .meet the task at hand efficiently and cost effectively. In analyzing the needs of a microcontroller-based project, we must first see whether all 8-bit, 16-bit, or 32-bit microcontroller can best handle the computing needs of the task most effectively. Among other considerations in this category are: (a) Speed. What is the highest speed that the microcontroller supports? (b) Packaging. Does it come in a 40-pin DIP (dual inline package) or a QFP (quad flat package), or some other packaging format? This is important in terms of space, assembling, and prototyping the end product. (c) Power consumption. This is especially critical for battery-powered products. (d) The amount of RAM and ROM on chip. (e) The number of I/O pins and the timer on the chip. (f) How easy it is to upgrade to higher-performance or lower power-consumption versions. (g) Cost per unit. This is important in terms of the final cost of the product in which a microcontroller is used. For example, there are microcontrollers that cost 50 cents per unit when purchased 100,000 units at a time. 2. The second criterion in choosing a microcontroller is how easy it is to develop products around it. Key considerations include the availability of an assembler, debugger, a code-efficient C language compiler, emulator, technical support, and both in-house and outside expertise. In many cases, third-party vendor (that is, a supplier other than the chip manufacturer) support for the chip is as good as, if not better than, support from the chip manufacturer. 3. The third criterion in choosing a microcontroller is its ready availability in needed quantities both now and in the future. F6r some designers this is even more important than the first two criteria. Currently, of the leading 8-bit microcontrollers, the 8051 family has the largest number of diversified (multiple source) suppliers. By supplier is meant a producer besides the originator of the microcontroller. In the case of the 8051, which was originated by Intel, several companies also currently produce (or have produced in the past) thc 8051. These companies include: Intel, Atmel, Philips/Signetics, AMD, Infineon (formerly Siemens), Matra, and Dallas Semiconductor. See Table 1-2. Table 1-2: Some of the Companies Producing a Member of the 8051 Family . Company Intel Atmcl Philips/Signetics Infineon Dallas SemilMaxim

CHAPTER

Web Site www.intel.com/design/mcs5l www.atmel.com www.semiconductors.philips.com www.infineon.com www.maxim-ic.com

1: THE 8051 MICROCONTROLLERS

It should be noted that Freescale, Zilog, and Microchip Technology have all dedicated massive resources to ensure wide and timely availability of their product since their product is stable, mature, and single sourced. In recent years they also have begun to sell the ASIC library cell of the microcontroller.

27

Review Questions I.

True or false. Mieroeontrollers

. than microproeesare normally less expensive

. IIer an d a general-pursors. . b d based on a microcontru When companng a system oar . ? . . which one IS cheaper. h' ? pose mIcroprocessor, . h f the following devices on-e ip: 3. A mieroeontroller normally has whic 0 ) I/O (d) all of the above (a) RAM (b) ROM (C needs whieh of the following II 4. A general-purpose mlerop;oeessor norma y

2

devices lO be attached to It. ) I/O (d) all of thc above (a) RAM (b) ROM (c ? An embedded system is also called a dedIcated system. Why. 5. ? What docs the term embedded system mean. ~: Why docs having multiple sources of a given product matter?

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY In this section we first look atthc various members of the 8051 family of mjcrocontrollcrs and their internal features. Plus we see who are the different manufacturers of the 8051 and what kind of products they offer.

A brief history of the 8051 In 1981, Intel Corporation introduced an 8-bit microcontroller called the 8051. This microcontroller had 128 bytes of RAM, 4K bytes of on-chip ROM, two timers, one serial port, and four ports (each 8-bits wide) all on a single chip. At the timc it was also referred to as a "system on a chip." The 8051 is an 8-bit proecsor, meaning that the CPU can work on only 8 bits of data at a time. Data larger than 8 bits has to be broken into 8-bit pieces to be processed by the CPU. The 8051 has a total of four I/O ports, each 8 bits wide. See Figure 1-2. Although the 8051 can have a maximum of 64K bytes of on-chip ROM, many manufacturers have put only 4K bytes on the chip. This will be discussed in more detail later. The 8051 became widely popular after Intel allowed other manufacturers to make and market any flavors of the 8051 they please with the condition th t they remain code-compatible with the 8051. This has Icd to many versions of the 8051 With different speeds and amounts of on-chip ROM marketed by more than haifa dozen manufacturers. Next we review some of them It' . . . IS Imponant to note that although there arc different flavors of the 8051 in terms of speed and amount of on-chip ROM the II Table \-3: Features of the 8051 ibl . , yare a compau e with the original 8051 as far as the' IIlstruc. Feature Quantity lion arc concerned. This means that if y . ou wntc your ROM 4K bytes program for one, it will run on any of them re ardlc 128 byte the manufacturer. g ss of RAM Timer 2 8051 microcontroller I/O pins 32 Serial port I The 8051 i the original memb f 6 ily. Intel refers to it as MCS-51 T bl ~r 0 the 8051 fam. Interrupt sources '. features of the 8051. . a e -3 shows the main Note' . ROM amounlmdlcates on-chip pl"Ogram space.

28

EXTERNAL INTERRUPTS

Y

't

INTERRUPT CONTROL

1--._. ~.

'-----,-----'-

.

ON-CHIP ROM

o

o c

for __ .. program .-code

ON-CHIP

RAM

I

ETC

f-oc--} -

TIMER 0 TIMER 1 _-

IA

Z 1J

• '?-

Y

~

g] c

oJ

~

I

CPU

\ A

A

.lJ

~

BUS CONTROL

t

.~

~7

4 I/O PORTS

SERIAL PORT

f t f

I Y

PO P2 P1 P3

...... .

-

I

A

I

TXD RXD

ADDRESS/DATA

Figure 1-2. Inside the 8051 Microcontroller Block Diagram

Other members of the 8051 family There are two other members in the 8051 family of microcontrollers. They arc the 8052 and the 8031.

8052 micr.ocontroller The 8052 is another member of the 8051 family The 8052 has all the standard features of the 8051 as well as an extra 128 bytes of RAM and an extra timer. In other words, the 8052 has 256 bytes of RAM and 3 timers. It also has 8K bytes of on-chip program ROM instead of 4K bytes. See Table 1-4. Table 1-4: Comparison

of 8051 Family Members

Feature 8051 ROM (on-chip program space in bytes) 4K RAM (bytes) 128 Timers 2 I/O pins 32 Serial port 1 Interrupt sources 6

8052 8K 256

8031

OK

32

128 2 32

8

6

3

As can be seen from Table 1-4, the 8051 is a subset of the 8052; therefore, all programs written for the 8051 will run on the 8052, but the reverse is not true.

CHAPTER 1: THE 8051 MICROCONTROLLERS

29

8031 microcontroller

.

..

ft n b fthe 805J family is the 803J chip. This chip I 0 e Another mem er 0 . e it has OK bytes of on-chip ROM. To u c thl referred to as a ROM-less 8051 sme . Thi temal ROM must contain thc proI. t add external ROM to n. ISex . h c lip you mus . . h d cute Contrast that to the 8051 in which t e ~~~~hitha~~~ 8cO:nlta~~1 t~e:cpr;;ra:~o be' fetched and exceuted but is limitcd to only 4~ bytes of code. The ROM containing the program attached to the 8031 can be as large as 64K bytes. In the process of adding external ROM to the 8031, you lose two ports. That leaves only 2 ports (of the 4 ports) for I/O opcrauons, To solve this problem, you can add external I/O to the 8031. Intcrfacmg the 803 I with memory and I/O ports such as the 8255 chip is discussed m Chapter 14. There arc also various speed versions of the 8031 available from dlffcrcnt comparncs.

Various 8051 microcontrollers Although the 8051 is the most popular mcmbcr of the 8051 family, you will not see "805 I" in the part numbcr. This is bccause the 8051 is available in different memory types, such as UV-EPROM, flash, and NV-RAM, all of which have different part numbers. A discussion ofthc various types of ROM will be given in Chapter 14.The UV-EPROM version of the 8051 is the 8751. The flash ROM version is marketed by many companies including Atmel Corp. and Dallas Semiconductor. The Atrnc] Flash 8051 is called AT89C51, while Dallas Semiconductor calls theirs DS89C4xO (DS89C420/430/440). The NV-RAM version of the 8051 made by Dallas Semiconductor is called DS5000. There i al 0 an OTP (one-time programmable) version of the 8051 made by various manufac_ turers. they Nextarcweused. discuss briefly each of the above chips and describe applications where 8751 microcontroller

This 8751 chip has only 4K bytes of on-Chip UV-EPROM. Using this chip for development requires acecss to a PROM bumer, as well as a UV-EPROM eraser to crase the COntentsof UV-EPROM inside the 8751 chi b C . Beeausc the on-Chip . ROM for the 875/ is tpUV-EPROM e,ore you can program It. agarn. it takes around 20 mmutes to erase the 8751 before it can be d' ' . Id e many manUfacturers to Introduce flash and NV RAM . . programme agam. This has '11di verSions of the 8051 as ;~:~iff~~~~~~~~~~n~~re arc also various speed versions of the 875 I availa'ble

DS89C4xo from Dallas Semiconductor (MaXim)

Many popular 8051 chips have on chi . ry. The AT89C5, fromAtmel C . - tp ROM III the form of flash memoThis is idcal for fast develo orp. ISone example of an 805 I with flash ROM pment Since flash m . compared to the twenty minut emory can be erased in seconds AT 9 . es or more needed f h 8 8 C511susedinplaeeOfthe8751 j" or r e 751. For this reason the thc chip and thcreby spced up thc d t~ e IInlnate the waiting time needed to crase op a rnieroeontrOl!er_basedsyst eve °pment time. Using the AT89C5 I to devel_ hem reqUires a ROM b mcmory; owevcr, a ROM crase'" umcr that sUpports flash r IS not ncedcd. Notice that in flash mCm 30 ory you

must erase the entire contents of ROM in order to program it again. This erasing of flash is done by the PROM burner itself, which is why a separate eraser is not needed. To eliminate the need for a PROM burner, Dallas Semiconductor, now part of the Maxim Corp., has a version of the S051/52 called DSS9C4xO (DSS9C420/430/ ...) that can be programmed via the serial COM port of an IBM PC. Notice that the on-chip ROM for the DSS9C4xO is in the form of flash. The DSS9C4xO (420/430/440/450) comes with an on-chip loader, which allows the program to be loaded into the on-chip flash ROM while it is in the system. This can be done via the serial COM port of an IBM PC, This in-system program loading of the DSS9C4xO via a PC serial COM port makes it an ideal home development system. Dallas Semiconductor also has an NV-RAM version of the S051 called DS5000. The advantage ofNV-RAM is. the ability to change the ROM conI tents one byte at a time. The DS5000 also comes with a loader, allowing it to be programmed via the PC's COM port. See Table 1-5. From Table J -5, notice that the DSS9C4xO is a really an S052 chip since it has 256 bytes of RAM and 3 timers. More details of this chip are given throughout the book.

Table 1-5: Versions of 8051152Microcontroller From Dallas Semiconductor (Maxim) Part Number ROM DSS9C420/30 DSS9C440 DSS9C450 DS5000 DSSOC320 DSS7520

16K (Flash) 32K (Flash) 64K (Flash) SK (NVRAM) 0 K 16K (UVROM)

RAM 256 256 256 . 12S 256 256

I/O pins 32 32 32 32 32 32

Timers Interrupts 3 3 3 2 3 3

Source: www.maxim-ic.comlproducts/microcontrollers/S051_

6 6 6 6 6 6

Vee 5V 5V 5V 5V 5V 5V

drop_in.cfm

DS89C4xO Trainer In Chapter S, we discuss the design of DSS9C4xO Trainer extensively. The MDES051 Trainer is available from www.MicroDigitaIEd.com.This Trainer allows you to program the DSS9C4xO chip from the COM port of the xS6 IBM PC, with no need for a ROM burner.

For a DS89C4xO·based trainer see www.MicroDigitaIEd.com. AT89C51 from Atmel Corporation The Atmel Corp. has a wide selection of 8051 chips, as shown in Tables 1_ 6 and 1-7. For example, the ATS9C51 is a popular and inexpensive chip used in many small projects. It has 4K bytes of flash ROM. Notice the AT89C51-12PC, where "C" before the 51 stands for CMOS, which has a low power consumption, "12" indicates 12 MHz, "P" is for plastic DIP package, "C" is for commercial.

CHAPTER 1: THE 8051 MICROCONTROLLERS

31

· 6 V . of 8051 From Almel (All ROM Flash) Table ,-; erslOns ROM RAM I/O pins Timer Interrupt Part Number 'A'T89C51 4K 128 32 2 6 AT89LV51 4K 128 32 2 6 AT89CIOSI IK 64 15 I 3 AT89C20S1 2K 128 IS 2 6 AT89C52 8K 128 32 3 8 AT89LV52 8K 128 32 3 8 Note: "C" in thc part number indicates CMOS.

Vce

5V

3V 3V

3V 5V

3V

Table 1-7: Various Speeds of 8051 From Atmel Part Number AT89C51-12PC AT89CSI-16PC AT89C51-20PC

Speed 12 MHz 16 MHz 20 MHz

Pins 40 40 40

Packaging DIP plastic DIP plastic DIP plastic

Use commercial commercial commercial

OTP version of the 8051 There are also OTP (one-time-programmable) versions of the 805 t available from different sources. Flash and NV-RAM versions are typically used for product development. When a product is designed and absolutely finalized, thc OTP version of the 8051 is used for mass production since it is much cheaper in terms of price per unit.

8051 family from Philips Another major producer of thc 8051 family is Philips Corporation. Indeed, they havc onc of thc largest selections of 80S I mierocontrollcrs. Many of their products include features such as A-to-D converters, D-to-A converters, extended I/O, and both OTP and flash. For the list of companies producing the 8051 c. ., si . h rarrn Iy see thc We b sues m t c box below.

See the following Web sites for 8051 d f pro ucts and their eatures from various companies: WWW.8052.com/chips.phtml WWW.MicroDigilaIEd.com

2

Packaging 40 40 20 20 40 40

, ,,Review Questions

c..,V

(}t . I. Name three features of the 8051. ~

2. What is the major di fference between the 805 I and 8052 microcontrollers? 3. Give the size of RAM in each of the following. (a) 8051 (b) 8052 (c) 8031 4. Give the size of the on-chip ROM in each of the following. (a) 8051 (b) 8052 (c) 8031 5. The 8051 is a(n) -bit microprocessor. 6. State

a major difference

between

the 8751,

the AT89C5 I, and the

DS89C420/30. 7. True or false. The DS89C420/30 is really an 8052 chip. 8. True or false. The DS89C420/30 has a loader embedded to the chip, therefore eliminating the need for ROM burner. 9. The DS89C420/30 chip has bytes of on-chip ROM. 10. The DS89C420/30 chip has bytes of RAM.

SUMMARY This chapter discussed the role and importance of microcontrollers in everyday life. Microprocessors and microcontrollers were contrasted and compared. We discussed the use of microcontrolJers in the embedded market. We also discussed criteria to consider in choosing a microcontroller such as speed, memory, I/O, packaging, and cost per unit. The second section of this chapter described various family members of the 805t, such as the 8052 and 8031, and their features. In addition, we discussed various versions of the 8051 such as the AT89C51 and DS89C4xO, which are marketed by suppliers other than 1ntel.

PROBLEMS SECTION 1.1: MICROCONTROLLERS I. 2. 3. 4. 5.

True or False, A general-purpose True or False. A microcontroller True or False. A microcontrotler True or False. A microcontroller What components are normally single chip?

AND EMBEDDED PROCESSORS

microprocessor has on-chip ROM. has on-chip ROM. has on-chip I/O ports. has a fixed amount of RAM on the chip. put together with the microcontroller into a

6. 1ntel's Pentium chips used in Windows PCs need external and chips to store data and code. 7. List three embedded products attached to a PC. 8. Why would someone want to use an x86 as an embedded processor? 9. Give the name and the manufacturer of some of the most widely used 8-bit microcontrollers. 10. In Question 9, which microcontrolJer has the most manufacture sources? CHAPTER 1: THE 8051 MICROCONTROLLERS

33

II. In a battery-based embedded product, what is the most important fact r in choosing a microcontroller? . . ROM why docs the size of the ROM 12. In an embedded controller with on-chip , . ortant is it to have multiple ouree 13. matter? In choosing a microcontroller, how Imp I· ') that Clip. " ?

for

14. What does the term "third-party s~PP~rttl ~~~~'and 16-bir ver ions, which of 15. If a mierocontroller arehlteetur~ as 0 1 the following statements IStrue. . (a) The 8-bit software will run on the 16-blt system. (b) The 16-bit software will run on the 8-blt system. SECTION 1.2: OVERVIEW OF THE 8051 FAMILY 16. The 8751 has __ bytes of on-chip ROM. 17. The AT89C51 has __ bytes of on-chip RAM. 18. The 8051 has _ on-chip timer(s). 19. The 8052 has __ bytes of on-chip RAM. 20. The ROM-less version of the 8051 uses __ as the pan number. 21. The 8051 family has __ pins for I/O. 22. The 8051 family has circuitry to support __ serial ports. 23. The 8751 on-chip ROM is of type _. 24. The AT89C51 on-chip ROM is of type __ . 25. The DS5000 on-chip ROM is of type __ . 26. The DS89C420/30 on-chip ROM is of type _. 27. Give the amount of ROM and RAM for the following chips. (a) AT89C51 (b) DS89C420/30 (e) DS89C440 28. Of the 8051 family, which memory type is the most cost effective if you are using a million of them in an embedded product? 29. What is the difference between the 8031 and 805 I? 30. Of the 8051 mieroeontrollers, which one is the best for a home development environment? (You do not have access to a ROM burner.)

ANSWERS TO REVIEW QUESTIONS SE nON 1.1: MICROCONTROLLERS AND EMBEDDED PROCESSORS I. True 2.

J.

A l1licrocontrollcr.bascdsystem (d)

4.

(d)

5.

II is dediealed since it is dediealed I Embedded syslem mcam that th 'I' I. e app

6.

7 •

d .

°1lcallon , omg one Iype of job. and proc .

1- avtng mu tlplc SOurcesfor a . essor are combined into a sin' I . I . given part means g e system Important y. eompelition a"'ong Suppliers brin 'S y:u are nOI hOstage 10 one supplier. Mor~ g a Out lower Cost for that Product.

___

SECTION 1.2: OVERVIEW OF THE 8051 FAMILY I. 2. 3. 4.

128 bytes of RAM, 4K bytes of on-ehip ROM, [our 8-bit JlO pons. The 8052 has everything that the 8051 has, plus an extra timer, and the on-chip ROM is 8K bytes instead of 4K bytes. The RAM in the 8052 is 256 bytes instead of 128 bytes. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes. (a) 4K bytes (b) 8K bytes (c) OK bytes

5.

8

The main difference is the type of on-chip ROM. III the 8751 it is UV-EPROM; AT89C51 it is flash; and in the DS89C420130 it is flash with a loader on the ehip. 7. True 8. True 9. 16K 10. 256 6.

CHAPTER 1: THE 8051 MICROCONTROLLERS

...-z

_

in the

35

36

CHAPTER 2

8051 ASSEMBLY LANGUAGE PROGRAMMING OBJECTIVES Upon completion of this chapter, you will be able to:

» » » » » » »

» » » »

» »

List the registers of the 8051 microcontroller Manipulate data using the registers and MOV instructions Code simple 8051 Assembly language instructions Assemble and run an 8051 program Describe the sequence of events that occur upon 8051 power-up Examine programs in ROM code of the 805] Explain the ROM memory map of the 805] Detail the execution of 8051 Assembly language instructions Describe 8051 data types Explain the purpose of the PSW (program status word) register Discuss RAM memory space allocation in the 8051 Diagram the use of the stack in the 8051 Manipulate the register banks ofthe 8051

37

--17

_

In Section 2.1 we look at the inside of the 8051. We demonstrate some of the widely used registers of the 8051 with simple instructions such as MOV and ADD. In Section 2.2 we examine Assembly language and machine language programming and define terms such as mnemonics, opcode, operand, etc. The process of assembling and creating a ready-to-run program for the 8051 is diseu sed in Section 2.3. Step-by-step execution of an 8051 program and the role of the program counter are examined in Section 2.4. In Section 2.5 we look at some widely used Assembly language directives, pseudocode, and data types related to the 8051. In Section 2.6 we discuss the flag bits and how they are affected by arithmetic instructions. Allocation of RAM memory inside the 8051 plus the stack and register banks of the 8051 arc discussed in Section 2.7.

SECTION 2.1: INSIDE THE 8051 . In this section we examine the major registers of the 8051 and show their use with the simple instructions MOV and ADD.

Registers In the CPU, registers arc used to store information temporarily. That information could be a byte of data to be proce d or an address pomtmg to the data to be fetched. The vast rna' . es e , ters arc 8-blt registers In the 8051 th . I jonty of 8051 regis. ere IS on y one data type' 8 bits TI 8 bi f a register arc shown in the diagram from the MSB .', ' ,le It 0 LSB (least significant bit) DO With 8 bi d (most significant bit) 07 to the . 1 an - It ara type a d I must be broken into 8-bit chunk be' . ' ny ata arger than 8 bits . . s erore It IS process, d S' number 01' registers in the 8051 'II eo. 1I1eethere arc a large , we WI concentrate on f the wi general-purpose registers and cover . I . some 0 t e widely u ed A endi specia registers 111 future chapters, See pp x A.2 for a complete list of 8051 . A . registers,

r------=--~

I

I

I

B

I

RO

I

RI

\

R2

I I I l

I

Rsl

PC

I ]

[_D_PH_I

DPL

-----

I

R3 R4

DPTR

I

[

PC (program counter)

F'

Igure 2-1 (b). Some 8051 16-b't R .

]

The most widel . a\0 OOh. 7Fh

c. Ox0020 C:Ox0030 c. 0](0040

DEFINE

00 00 00 00 00 00 00 00 00 00

OIR D1Splay

(.!..l!JlU\~C;~ .....~-,.

-

....

Figure 2-10. 128-Byte Memory Space from Keil Simulator

00 00 00 00

'" ' ......•.•... ........•••.... ....•. ............•... ....•.•......•..

00 00 00 00 .......••.......

~

..

Review Questions I. What is the size of the SP register? 2. With each PUSH instruction, the stack pointer register, SP, is . (incremented, decremented) by 1. 3. With each POP instruction, the SP is (incremented, decremented) by I. . 4. On power-up, the 8051 uses RAM location . stack.

as the first location of the

5. On power-up, the 8051 uses bank _ for registers RO _ R7. 6. On power-up, the 8051 uses RAM locations to for registers RO - R7 (register bank 0). --7. Which register bank is used if we alter RSO and RSI of the PSW by the following two instructions? ' SETB

PSW. 3

SETB

PSW. 4

8. In Question 7, what RAM locations are used for register RO _ R7?

SUMMARY This chapter began with an exploration of the major registers of the 8051, including A, S, RO, RI, R2, R3, R4, R5, R6, R7, DPTR, and PC. The use of these registers was demonstrated in the 'context of programming examples. The process of creating an Assembly language program was described from writing the source file, to assembling it, linking, and executing the program. The PC (program counter) register always points to the next instruction to be executed. The way the 805 I uses program ROM space was explored because 8051 Assembly language programmers must be aware of where programs are placed in ROM, and how much memory is avai lable. An Assembly language program is composed of a series of statements that are either instructions or pseudo-instructions, also called directives, Instructions are translated by the assembler into machine code. Pseudo-instructions are not translated into machine code: They direct the assembler in how to translate instructions into machine code. Some pseudo-instructions, called data directives, are used to define data. Data is allocated in byte-size increments. The data can be in binary, hex, decimal, or ASCII formats. Flags are useful to programmers since they indicate certain conditions, such as carry or overflow, that result from execution of instructions. The stack is used to store data temporarily during execution of a program. The stack resides in the RAM space of the 8051, which was diagrammed and explained. Manipulation of tbe stack via POP and PUSH instructions was also explored.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING

63

.

ODD /, '') 1{tf+yl of iutemal RAM location JOH, and 8 to OFH arc the bit addresses of the second byte ofRAMlo~H and so on. The last byte of2FH has bit addresses of78H to 7FH. See Figure 5-1' and Example 5-/1. Note that internal RAM locations 20 _ 2FH arc both byteaddressable and bit-addressable. Example

5-11

Find out to which byte each of the following bits belongs. Give the address ofth RAM byte 111 hex. e (a) SETB 42H ; set bit 42H to 1 (d) SETB 28R ;set (b) CLR 67H ; clear bit 67 (e) CLR

(c) CLR OFH ; clear

bi t OFH

(t)

SETB1205;clear

bit bit

Solution: (a) RAM bit address of 42H belongs to 02 of RAM I . (b) RAM bit dd ocatton 28H I a ress of 67H belongs to 07 of RAM location 2CH' (e) RAM bit address ofOFH belongs to 07 of RAM I' . (d) RAM bit address 01'2811 belongs to DO of RAM loeatlon 21H. (e) RAM bit address of 12 belongs to 04 of RAM locatIon 25H. (I) RAM bit address 01'05 belongs to 05 of RAM locatton 21H. ocation 20H. 122

28H to 1 12 (decimal)

ln order to avoi d confusion regarding th e addresses 00 - 7FH, the fo 1[owing two points must b e noted.

Byte address 7F

Generalpurpose

r.

The [28 bytes of RAM have the byte addresse S of 00 - 7FH and can be accessed in byte siz e using various address ing modes such a S direct and register-indi rect, as we have seen in this chapter and previ ous chapters. These 128 bytes are accessed using byte-type instructions. 2. The 16 bytes of RAM locations 20 - 2FH also have bit addresses of 00 - 7FH since 16 x 8 = 128 (00 - 7FH). In order to access these 128 bits of RAM locations and other bit-addressable space of 8051 individually, we can usc only the single-bit instructions such as SETB. Table 5-2 provides a list

1>.,

RAM

~'1je (30 2F I 2E 2D I ?r

7F 7E 7D 7C 7B 7A 79 78 77 7~ 75 74 7< 77 71 70 6F 6E 6D 6C 6B 6A 69 68 Ih7 ~h ~" ~A h< h7 ~1 ~n "'c I SF sE "D 5C SB SA Sg SR ?B .2 57 56 55 54 53 52 51 50 2A o .2 / 2Q 14F 4E 4n 4r 4B 4A 4q 4R ~-,I 28 47 46 45 44 43 42 41 40 "'"' - '\ 27 3F 3E 3D 3C 3B 3A 39 38 ~ \ 26 37 36 35 34 33 32 31 30 ." -o / 25 2F 2E 2D 2C 2B 2A 29 28 " ,~ I 24 27 2~ as 24 21 22 ?1 ?n co 1F 1E 1D 1C 1B lA 19 18 23 117 '1-,:;...,.-.;---j-" 13 17 11 10 ?? n"---n,, nn' rir np rvtv rv o nQ \ 71 -0'7-0605 04 03 02 01 00 L-'-20 'IF Bank 3 18 Bank 2 17 10 Bank I OF 08 07 Default register bank for RO - R 7 00

'"

" "

"

I

Figure 5-1. 16 Bytes oflnternal RAM. Note: They are both bit- and byte-accessible.

of single-bit instructions. Notice that the single-bit instructions use only one addressing mode and that is direct addressing mode. In the first two sections of this chapter we showed various addressing modes of byte-addressable space of the 8051, among them indirect addressing mode. It must be noted that there is no indirect addressing mode for single-bit'instructions. Tahle 5-2: Single-Bit Instructions Instruction SETB bit CLR bit CPL bit JB bit, target JNB bit,tar et JBC bit,tar et

if bit, then clear 123

CHAPTER

5: 8051 ADDRESSING MODES

I/O port bit addresses As we discussed in Chapter 4, the 8051 has four 8-bit VO ports: PO, PI, P2, and P3. We can access either the entire 8 bits or any single bit without altering the rest. When accessing a port in a single-bit manner, we usc the syntax "SETB X. y" where X is the port number 0, 1,2, or 3, and Y is the desired bit number from o to 7 for data bits DO to 07. See Figure 5-2. For example, "SETB Pl. 5" sets high bit 5 of port J. Remember that DO is the LSB and D7 is the MSB. As we mentioned earlier in this chapter, every SFR register is assigned a byte address and ports PO P3 are part of the SFR. For example, PO is assigned byte address 80H, and PI has address of 90H as shown in Figure 5-2. While all of the SFR registers are byte-addressable some of them are also bit-addressable. The PO - P3 are among this category of SFR registers. From Figure 5-2 we see that the bit addresses for PO are 80H to 87H, and for P I arc 90H to 97H, and so on. Notice that when code such as "SETB Pl.0" is assembled, it becomes "SETB 90H" since P 1.0 has the RAM address of 90H. Also notice from Figures 5-1 and 5-2 that bit addresses 00 - 7FH belong to RAM byte addresses 20 - 2FH, and bit addresses 80 - F7H belong [a SFR of PO, TCON, PI SCON, P2, etc. The bi; addresses for PO - P3 arc shown in Table 5-3 , an d . d iscusscd next.

Byte address

Bit address

FF FO

F7 F6 F5 F4 F3 F2 Fl FO

B

EO

E7 E6 E5 E4 E3 E2 El EO

Ace

DO

D7 D6 D5 D4 D3 D2 Dl DO

psw

B8

--

BC BB 8A B9 88

IP

BO

B7 B6 85 B4 B3 82 Bl BO

P3

AS

AF

A9 A8

IE

AD

A7 A6 AS A4 A3 A2 Al AO

P2

AC AB

AA

99

not bit-addressable

SBUF

98

9F 9E 9D ge 9B 9A 99 98

seaN

90

97 96 95 94 93 92 91 90

PI

8D 8e 88 8A 89 88 87 83 82 81 80

not bit-addressable not bit·addressable not bit-addressable not bit-addressable not bit-addressable

T HO T Ll T LO T MOD

8F 8E 8D 8e 8B 8A 89 88

T eON

not bit-addressable

P eON

not bit-addressable not bit-addressable not bit-addressable 87 86 85 84 83 82 81 80

Special Function Registers Figure 5-2. SFR RA 124

T HI

M Address (Byte and Bit)

D PH D PL

sP Pa

= Bit memory map From Figures 5-1 and 5-2 and Table 5-3 once again notice the following facts. 1) The bit addresses 00 -7FH are assigned to RAM locations of20 - 2FH. 2) The bit addresses 80 - 87H are assigned to the PO port. 3) The bit addresses 88 - 8FH arc assigned to the TCON register. 4) The bit addresses 90 - 97H are assigned to the PI port. 5) The bit addresses 98 - 9FH are assigned to the SCaN register. 6) The bit addresses AO- A7H are assigned to the P2 port .: 7) The bit addresses A8 - AFH are assigned to the IE register. 8) The bit addresses BO - B7H are assigned to the P3 port. 9) The bit addresses B8 - BFH arc assigned to IP. 10) The bi t addresses CO - CFH are not assigned. 11) The bit addresses ,DO- D7H are assigned to the PSW register. 12) The bit addresses D8 - DFH are not assigned. 13) The bit addresses EO- E7H are assigned to the Accumulator register. 14) The bit addresses E8 - EFH are not assigned. 15) The bit addresses FO- F7H are assigned to the B'register. Table 5-3: Bit Addresses for All Ports

PO PO.O PO.l PO.2 POJ PO.4 PO.5 PO.6 PO.7

Addr 80 81 82 83 84 85 86 87

Addr P2 PI P2.0 PI.O 90 P2.1 P 1.1 91 P2.2 PI.2 92 P2.3 P1.3 93 PIA 94 :,

f 0

RAM

. In

h t e

~O -r~H 137

CHAPTER 5: 8051 ADDRESSJNG MODES

63. In the 8052, the SFR shares the address space with the (lower, upper) 128 bytes of RAM. 64. In Question 63, discuss if they are physically the same memory. 65. Explain what is the difference between these two instructions. (a)MOV BOH,#99H (b)MOV @RO,#99HifRO=80H 66. Which registers can be used to access the upper 128 bytes of RAM in the 8052? 67. Write a program to put 55H into RAM locations CO - CFH of upper memory. 68. Write a program to copy the contents of lower RAM locations 60 - 6FH to uppper RAM locations DO- DFH.

ANSWERS TO REVIEW QUESTIONS SECTION 5.1: IMMEDIATE I. 2. 3, 4. 5.

AND REGISTER

ADDRESSING

MODES

No MOV R3,#10000000B Source and destination registers' sizes do not match. True ' No

SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES I.

Direct; because there is no "#" sign

2. 3.

02 12H EOH RO and RI

4.

5.

SECTION

5.3: BIT ADDRESSES

FOR 1/0 AND RAM

I. Tmc 2. False 3. False 4. A, B, and PSW 5. 6.

\6 bytes are bit-addressable; MOY A,R3 JNB ACC.O

they are from byte location 20H to 2FH

7.

.

For (a). (b), and (c) usc Figure 5-1. (a) RAM byte 22H, bit D4 (b) RAM byte 24H, bit DO (c) RAM byte 22H. bit D? For (d) and (e) usc Figure 5-2. (d) SETB P 1.5 8. RAM bytes 00 - 20H, special function registers. (c) SETB ACC.6 9. True 10. True SECTION I.

2, 3. 4. 5.

5.4: EXTRA I28-BYTE ON-CHIP RAM IN 8052

Tme True False 80 - FFH MOV A,#99H MOV RO,#OF6H MOV @RO,A

138

CHAPTER 6

ARITHMETIC, LOGIC INSTRUCTIONS, AND

PROGRAMS OBJECTIVES Upon completion of this chapter, you will be able to:

»

» » » » » » » » » » »

Define the range of numbers possible in 8051 unsigned data Code addition and subtraction instructions for unsigned data Perform addition of BCD data Code 8051 unsigned data multiplication and division instructions Code 8051 Assembly language logic instructions AND, OR, and EX-OR Use 8051 logic instructions for bit manipulation Use compare and jump instructions for program control Code 8051 rotate instruction and data serialization Explain the BCD (binary coded decimal) system of data representation Contrast and compare packed and unpacked BCD data Code 8051 programs for ASCII and BCD data conversion Code 8051 programs to create and test the checksum byte

139

This chapter describes all 8051 arithmetic and logic instructions. Program examples arc given to illustrate the application of these instructions. In Section 6.1 we discuss instructions and programs related to addition, subtraction, multiplication, and division of unsigned numbers. Signed numbers are discussed in Section 6.2. In Section 6.3, we discuss the logic instructions AND, OR, and XOR, as well as the COMPARE instruction. The ROTATE instruction and data serialization arc discussed in Section 6.4. In Section 6.5 we provide some real-world applications such as BCD and ASCII conversion and checksum byte testing.

SECTION 6.1: ARITHMETIC INSTRUCTIONS Unsigned numbers are defined as data in which all the bits are used to represent data, and no bits arc set aside for the positive or negative sign. This means that the operand can be between 00 and FFH (0 to 255 decimal) for 8-bit data.

Addition of unsigned numbers In the 8051, in order to add numbers together, the accumulator register (A) must be involved. The form of the ADD instruction is ADD A, source

;A ~ A + source

The instruction ADD is used to add two operands. The destination operand is always in register A while the source operand can be a register, immediate data, or in memory. Remember that memory-to-memory arithmetic operations are never allowed in 8051 Assembly language. The instruction could change any of the AF, CF, or P bits of the flag register, depending on the operands involved. The effect of the ADD instruction on the overflow flag is discussed in Section 6.3 sine. it is used mainly in signed number operations. Look at Example 6-1. e Example 6-1

Show how the flag register is affected by the fOllowing instructions. MOV

ADD

A,#OF5H A,#OBH

;A=F5 hex ;A=F5+0B=00

Solution: F5H + OBH 100R

1111 0101 + 0000 1011 0000 0000

After the addition, register A (destination) contains 00 and th fI e ags are as follows: CY = I since there is a earry out from D7 :~ ~ ~eeause thhenumber of Is is zero (a~ even number) - smce t ere IS a earry from 03 to 04. . 140

= Addition of individual bytes Chapter 2 contained a ro ra purposely kept less than FFH Pthg m that added 5 bytes of data. The sum was calculate the sum of any ib e maximum value an 8-bit register can hold. To num er of operands th f1 h d after the addition of each 0 dE' e carry ag soul be checked peran. xarnple 6 2 R7 . the operands are added to A. - uses to accumulate carnes as. Example 6-2 Assume that RAM locations 40 - 44 have the followi . the sum of the values. At the end of the r ollowing values. Wnte a program to find and R7 the high byte All I . P ogram, register A should contain the low byte . va ues are 111 hex. 40= (7D) 41=(EB) 42=(C5) 43=(5B) 44=(30)

Solution:

AGAIN:

NEXT:

MOV MOV

RO,#40H R2,#5

;load pointer ;load counter

CLR

A

;A=O

MOV ADD

R7,A A,@RO

JNC

NEXT

;clear R7 ;add the byte pointer to A by RO ;if Cy=o don't accumulate carry ;keep track of carries ;increment pointer ;repeat until R2 is zero

R7 RO DJNZ R2 ,AGAIN INC INC

AnalysIs of Example 6-2

Three iterations of the loop are shown below. Tracing of the program is left to the reader as an exercise. I. In the first iteration of the loop, 7DH is added to A with CY = 0 and R7

=

00 ,

and the counter R2 = 04. 2. In the second iteration of the loop, EBH is added to A, which results in A = 68H and CY = I. Since a carry occurred, R7 is incremented. Now the counter R2 = 03. 3. In the third iteration, C5H is added to A, which makes A = 2DH. Again a carry occurred, so R7 is incrcmented again. Now counter R2 = 02. At the end when the loop is finished, the sum is held by registers A and R 7, where A has the low byte and R7 has the high byte.

CHAPTER

6: ARITHMETIC,

LOGIC INSTRUCTIONS,

AND PROGRAMS

141

ADDC and addition of 16·bit numbers When addin two 16-bit data operands, we need to be concerned with the g from th e Iower byte to thc higher byte. The instruction . . f a carry propagation o. carry ) IS . usc d on such occasions. For example, look at the addiADDC (add with lion of 3CE7H + 3B8DH, as shown below. 1

+

3C E7 38 8D 78 74

When the first byte is added (E7 + 8D = 74, CY = I). The carry is propagated to the higher byte, which results in 3C + 3B + I = 78 (all in hex). Example 6-J shows the above steps in an 8051 program. Example 6-3 Write a program to add two 16-bit numbers. The numbers are JCE7H Place the sum in R7 and R6; R6 should have the lower byte.

and 3B8DH.

Solution:

CLR MOV

C

A,#OE7H A,#8DH MOV R6,A MOV A,#3CH ADDC A,#3BH ADD

MOV

R7,A

;make CY=O ;load the low byte now A=E7H ;add the low byte now A=74H and CY=l ;save the low byte of the sum in R6 ;load the high byte ;add with the carry ;3B + 3C + 1 = 78(all in hex) ;save the high byte of the sum

BCD (binary coded decimal) number system BCD stands for binary coded decimal. BCD is needed because in everyday life we usc the digits a to 9 for numbers not binary or hex numbers. Binary representation of a to 9 is called BCD (see Figure 6-1). In computer literature one encounters two terms for BCD numbers, (I) unpacked BCD, and (2) packed BCD. We describe each one next.

Digit 0 1 2

3 4 5 6

Unpacked BCD

7

8

. In unpacked BCD, the lower 4 bits of the number represent the BCD number, and the rest of the bits arc a F I "0000 a " . . or examp e, . I a I and "0000 a I a I" arc unpacked BCD for 9 and p 5, res ee.lIvely. Unpacked BCD requires I byte of memory or an 8-blt register to contain it. 142

9

BCD 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001

Figure 6-1. BCD Code

Packed BCD In packed BCD, a single byte has two BCD numbers in it one in the lower 4 bits, and one in the upper 4 bits. For example, "0101 100I" is'packed BCD for 59H. It takes only I byte of memory to store the packed BCD operands. And so one reason to use packed BCD is that it is twice as efficient in storing data. There IS a problem with adding BCD numbers, which must be corrected. The problem is that after adding packed BCD numbers, the result is no longer BCD. Look at the following. MOV A,#17H ADD A,#28H

Adding these two numbers gives 00 II 1111B (3FH), which is not BCD! A BCD number can only have digits from 0000 to 1001 (or 0 to 9). In other words, adding two BCD numbers must give a BCD result. The result above should have been 17 + 28 = 45 (0 I00 0 I0 1). To correct this problem, the programmer must add 6 (0 II 0) to the low digit: 3F + 06 = 45H. The same problem could have happened in the upper digit (for example, in 52H + 87H = D9H). Again to solve this problem, 6 must be added to the Lipperdigit (D9H + 60H = 139H) to ensure that the result is BCD (52 + 87 = 139). This problem is so pervasive that most microprocessors such as the 8051 have an instruction to deal with it. In the 8051 the instruction "DA A" is designed to correct the BCD addition problem. This is disI cussed next.

DA instruction The DA (decimal adjust for addition) instruction in the 8051 is provided to correct the aforementioned problem associated with BCD addition. The mnemonic "DAn has as its only operand the accumulator "A". The DA instruction will add 6 to the lower nibble or higher nibble ifneeded; otherwise, it will leave the result alone. The following example will clarify these points. MOV MOV ADD DA

A,#47H B, #25H A,S A

;A~47H first BCD operand ;B~25 second BCD operand ;hex(binary) addition (A~6CH) ;adjust for BCD addition (A~72H)

After the program is executed, register A will contain 72H (47 + 25 = "DAn' tr ction works only on A. In other words, while the source can IDS u i register . . 72) . Th e 'ng mode the destination must bee in A in addressl d a f any , b e an t:operan DA t k It also needs to be emphasized that DA must be used after or d er ,or 0 wor . . . ddi . f BCD erands and that BCD operands can never have any digit the a Ilion a op rds A - F digits are not allowed. It IS . also Important . to wo th I greater t han 9 . n a er, . . er an ADD instruction; It will not work after the rNC note t hat DA war ks on ly aft instruction. 143

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

Summary of DA action

After an ADD or ADDC instruction, . I. If the lower nibble (4 bits) is greaterthan 9, or If AC

=

I, add 0110 to the lower

2 4If bits. the upper nibble is greater than 9, or if CY = I, add. 01 J 0 to th c upp e r 4 bits . . In reality there is no other use for the AC (auxiliary carry) flag bit except for BCD addition and correction. For example, adding 29H and 18H WIll result in 41H, which is incorrect as far as BCD is concerned. BCD

Hex 29 + +

18 41

+

---..2.

+

47

0010 1001 0001 1000 0100 0001 0110 0100 0111

Since AC = 1 after the addition, The final result is in BCD format.

"DA

A"

ACd

will add 6 to the lower nibble.

Example 6-4

Assume that 5 BCD data items are stored in RAM locations starting at 40H, as shown below. Write a program to find the sum of all the numbers. The result must be in BCD. 40~(71) 41~(1l) 42~(65) 43~ (59) 44~ (37)

Solution: MOV MOV CLR MOV

AGAIN:

ADD DA

NEXT:

RO,#40H R2,#5 A

R7,A A,@RO A NEXT

JNC INC R7 INC RO DJNZ R2 ,AGAIN

;load pointer ;load counter ;A~O ;clear R7 ;add the byte pointer to A by RO ;adjust for BCD ;if CY~O don't accumulate carry ;keep track of carries ;increment pointer ;repeat until R2 is zero

Subtraction of unsigned numbers SUBBA, source

;A ; A - source

- CY

In many microprocessors there are two different instructions for subtraction: SUB and SUBB (subtract with borrow). In the 8051 we have only SUBB. To make SUB out of SUBB, we have to make CY = 0 prior to the execution of the instruction. Therefore, there are two cases for the SUBB instruction: (I) with CY = 0, and (2) with CY = I. First we examine the case where CY = 0 prior to the execution of SUBB. Notice that we use the CY flag for the borrow. SUBB (subtract with borrow) when CY

=0

In subtraction, the 8051 microprocessors (indeed, all modem CPUs) use the 2's complement method. Although every CPU contains adder circuitry, it would be too cumbersome (and take too many transistors) to design separate subtracter circuitry, For this reason, the 8051 uses adder circuitry to perform the subtraction command, Assuming that the 8051 is executing a simple subtract instruclion and that CY = 0 prior to the execution of the instruction, one can summarize the steps of the hardware of the CPU in executing the SUBB instruction for unsigned numbers, as follows, I. Take the 2's complement of the subtrahend (source operand), 2. Add it to the minuend (A), 3. Invert the carry. These three steps are performed for every SUBB instruction by the internal hardware of the 8051 CPU, regardless of the source of the operands, provided , that the addressing mode is supported, After these three steps the result is obtained and the flags are set. Example 6-5 illustrates the three steps, Example 6-5

Show the steps involved in the following, C CLR A,#3FH MOV R3,#23H MOV SUBB A,R3

; make CY;O (A ; 3FH) ;load 3FH into A 23H) ;load 23H into R3 (R3 A - R3, place result ; subtract ;

in A

Solution: A ; R3;

3F 23 1C

0011 1111 0010 0011

0011 1111 + 11011101

(2's

1 0001 1100 CF;O (step

,3)

o

complement)

f . CY = 0 AC = 0, and the programmer must look at The flags would be set as 011ows: .'. , ' the carry flag to determine if the result IS posItive or negative. 145

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

lfthe CY = 0 after the execution ofSUBB, the result is positive; ifCY = I, the result is negative and the destination has the 2's complement of the result. Normally, the result is left in 2's complement, but the CPL (complement) and rNC instructions can be used to change it. The CPL instruction performs the I's complement of the operand; then the operand is incremented (INC) to get the 2 's complement. See Example 6-6. Example 6-6 . Analyze the following program: CLR C MOV A,#4CH ;load A with value 4CH (A=4CH) SUBB A,#6EH ;subtract 6E from A JNC NEXT ;if CY=O jump to NEXT target CPL A ;if CY=l then take l's complement INC A ;and increment to get 2's complement NEXT:MOV R1,A ;save A in R1 Solution:

Following are the 4C 6E -22 CY = 1, the

steps for "SUBE A, #6EH": 0100 1100 0110 1110 2's comp

0100 1100 1001 0010 0 1101 1110 result is negative, In 2's complement.

SUBB (SUbtract with borrow) when CY = 1

This instruction is used for multib t b . row of the lower operand If CY _ I Y c num crs and will take care of the bor. - pnor to executing the SUBB . '. a Iso subtracts I from the result . Sec Examp Ie 6 -7. instructIOn, It Example 6-7 Analyze the following program: CLR MOV SUEB MOV MOV SUEB MOV

C

A,#62H A,#96H R7,A A,#27H A,#12H R6,A

;CY = 0 ;A = 62H ;62H - 96H = CCH with CY = 1 ;save the result ;A=27H ;27H - 12H - 1 = 14H ;save the result

Solution:

After the SUBB A = 62H . '-96H = CCH ISa borrow. Since CY = and the carry flae i ". 1 = 14H. Therefore hi, when SUBB is executed the s g Isdsethigh indicating there .we ave 2762H _ 1296H = 14CCH. econ time A = 27H - 12H _ 146

UNSIGNED MULTIPLICATION AND DIVISION .In multiplying or dividing two numbers in the 8051, the use of registers A IS required since the multiplication and division instructions work only with these two registers. Wc first discuss multiplication.

and B

Multiplication of unsigned numbers The 8051 supports byte-by-byte multiplication assumed to bc unsigned data. The syntax is as follows: ;A x B,

MUL AB

only. The bytes are

place 16-bit result in B and A

In byte-by-byte multiplication, one of the operands must be in register A, and the second operand must be in register B. After multiplication, the result is in the A and B registers; the lower byte is in A, and the upper byte is in B. The following example multiplies 25H by 65H. The result is a 16-bit data that is held by the A and B registers. ;load 25H to ;load 65H in ;25H * 65H ~ ;B ~ OEB and

A,#25H B,#65H AB

MOV MOV MUL

reg. A reg. B E99 where A ~ 99H

Table 6-1: Unsigned Multiplication Summary (MUL AB) Multiplication byte x byte

Operand I A

Operand 2 B

Result A - low byte, B - high byte

Note: Multipliealion of operands larger than 8 bits takes some manipulation. It is len to the reader to experiment with.

Division of unsigned numbers In the division of unsigned numbers, the 8051 supports byte over byte only. The syntax is as follows. DIV

AB

;divide A by B

When dividing a byte by a byte, the numerator must be in register A and the denominator must be in B. After the DIV msrrucuon IS performed, the quotient is in A and the remainder is in B. See the following example. MOV MOV DIV

A,#95 B,#10 AB

;load 95 into A ;load 10 into B ,.now A ~ 09 (quotient) and ,.B ~ 05 (remainder)

147

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

Notice thc following points for instruction "DIV ABu. . . a Iways rna kcs CY = 0 and OV = 0 ifthc denominator _is not hO. I. This. mstrucnon 2. If the denominator is 0 (B = 0), OV = I indicates an error, and CY - O.T e standard practice in all microprocessors ,when dividing a number by 0 IS to indicate in some way the invalid result 01 infinity. In the 8051, the OV flag IS set to I. Table 6-2:Unsigned Division Summary (DIV AB) Division Numerator Denominator byte I byte A B (If B = 0, then OV - I indicating an error)

Quotient A

Remainder B

An application for DIV instructions There arc times when an ADC (analog-to-digital converter) is connected to a port and the ADC represents some quantity such as temperature or pressure. The 8-bit ADC provides data in hex in the range of 00 - FFI-I. This hex data must be converted to decimal. Wc do that by dividing it by 10 repeatedly, saving the remainders as shown in Example 6-8. Example 6-8 Write a program (a) to make PI an input port, (b) to get a byte of hex data in the range of 00 - FFH from PI and convert it to decimal. Save the digits in R7, R6, and R5, where the least significant digit is in R7. Solution:

MOV MOV MOV MOV DIV MOV MOV DIV MOV MOV

A,#OFFH Pl,A A,Pl

B,#10 AB

R7,B

;make PI an input port ;read data from PI ;B=OA hex (10 dec) ;divide by 10 ;save lower digit

B,#10 AB

R6,B RS,A

;divide by 10 once more ;save the next digit ;save the last digit

The input value from P I is in the hex range of 00 FF '. I 1111111. This program will not work if the in ut d - . H or In binary 00000000 to program converts from binary to decimal T P ata IS In BCD. In other words, this format, wc OR it with 30H as shown' S· 0 convert a sIngle decImal digit to ASCII In eCllons 6.4 and 6.5.

148

Example 6-9 Analyze the program in Example 6-8, assuming that P I has a value of FDH for data. Solution: To convert a binary (hex) value to decimal, we divide it by 10 repeatedly until the quotient IS less than 10. After each division the remainder is saved. In the case of an 8-bit binary such as FDH we have 253 decimal as shown below (all in hex). Quotient

FD/OA= 19/0A=

19 2

Remainder 3 (low digit) 5 (middle digit) 2 (high digit)

Therefore, we have FDH = 253. In order to display this data it must be converted to ASCIl, which is described in a later section in this chapter.

Review Questions 1. In multiplication of two bytes in the 8051, we must place one byte in register ____ and the other in register _ 2. In unsigned byte-by-byte multiplication, the product will be placed in registeres) _ 3. Is this a valid 8051 instruction? "MUL A, Rl". Explain your answer. 4. In byte/byte division, the numerator must be placed in register and the denominator in register _ 5. In unsigned bytelbyte division, the quotient will be placed ITI register and the remainder in register ____ 6. Is this a valid 8051 instruction? "DIV A, R1". Explain your answer. 7. The instruction "ADD A, source" places the sum in ---8. Why is the following ADD instruction illegal? "ADD R1, R2" 9. Rewrite the instruction above in correct form. 10. The instruction "ADDC A, source" places the sum in -----l l , Find the value of the A and CY flags in each of the following. (a) MOV A, #4FH (b) MOV A, #9CH ADD A,#OB1H ADD A,#63H 12. Show how the CPU would subtract aSH from 43H. 13. !fCY = I, A = 95H, and B = 4FH prior to the execution of"SUBB A, B", what .?

will be the contents of A after the su btraction.

149 CHAPTER 6: AIUTHMETlC, LOGIC INSTRUCTIONS, AND PROGRAMS

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETIC OPERATIONS All data items used so far have been unsigned entire 8-bit operand was used for the magnitude. Many data. In this section the concept of signed numbers is ed instructions. J f your applications do not involve bypass this section.

numbers, meaning that the applications require signed discussed along with relatsigned numbers, you can

Concept of signed numbers in computers In everyday life, numbers arc used that could be positive or negative. For example, a temperature of 5 degrees below zero can be represented as -5, and 20 degrees above zero as +20, Computers must be able to accommodate such numbers. To do that, computer scientists have devised the following arrangement for the representation of signed positive and negative numbers: The most significant bit (MSB) is set aside for the sign (+ or -), while the rest of the bits are used for the magnitude. The sign is represented by 0 for positive (+) numbers and I for negative (-) numbers. Signed byte representation is discussed below,

Signed a·bit operands In signed byte operands, 07 ,-(MSB) is the sign and DO to 06 are set aside for the magnitude of the number. If 07: 0, the operand is positive, and if 07 : I, it is negative.

Positive numbers

1sign I

magnitUde

r----t"-----

_

Figure 6-2. 8-Bit Signed Operand

The range of positive numbers that' can be represented by the format shown in Figure 6-2 IS 0 to + 127. J f a positive number is larger than + 127, a 16-bit size operand must be used. Since the 805J does not support 16-bit data we will not discuss it. '

Negative numbers

-,

a +1

0000 0000 0000 0001

+5

0000 0101

+127

0111 1111

For negative numbers, 07 is l: however th ' , its 2's complement Although the ' bl ' e magmtude IS represented in . assem er docs the con ' '. . , tanr to understand how the eonversi k T ,versIOn, It IS stlllimporwor s . 0 convert to nega tiive num b er representation (2's complement) folio onthes , w esc steps. I, Write the magnitude of the number in S-bn b' , 2. Invert eaeh bit, I mary (no sign), J. Add I to it.

ISO

Examples 6-10 , 6- 11, an d 6- I2 demonstrate these three steps: Example 6-10 Show how the 8051 would represent -5. Solution: Observe the following steps. l.

2. 3.

5 in 8-bit binary invert each bit add 1 (which becomes

0000 0101 1111 1010 1111 1011

FE in hex)

Therefore -5 = FBH, the signed number representation in 2 's complement for -5.

Example 6-11 Show how the 8051 would represent -34H. Solution: Observe the following steps. 1.

2. 3.

34H given in binary invert each bit add 1 (which is CC in hex)

0011 0100 1100 1011 1100 1100

Therefore -34

= CCH,

the signed number representation in 2's complement for -34H.

Example 6-12 Show how the 8051 would represent -128. Solution: Observe the following steps. l. 2. 3.

1000 0000 0111 1111 1000 0000

Therefore -128

128 in 8-bit binary invert each bit add 1 (which becomes

= 80H, the signed

80 in hex)

number representation in 2's complement for -128.

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

151

From the examples above it is clear that the range of byte-sized negative num b ers IS. - J t 0 - 128. The following lists byte-sized signed number ranges. Decimal

Binary

Hex

-128 -127 -126

1000 0000 1000 0001 1000 0010

80 81 82

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

a +1 +2

1111 1111 0000 0000 0000

FE FF

1110 1111 0000 0001 0010

00 01 02

......... +127

0111 1111

7F

The above explains the mystery behind the relative address of -128 to + 127 in the short jump discussed in Chapter 3.

Overflow problem in signed number operations When using signed numbers, a serious problem arises that must be dealt with. This is the overflow problem. The 805 J indicates the existence of an error by raising the OV (overflow) flag, but it is up to the programmer to take care of the erroneous result. The CPU understands only Os and Is and ignores the human convention of positive and negative numbers. What is an overflow? [f the result of an operation on signed numbers is too large for the register, an overflow has occurred and the programmer must be notified. Look at Example 6-13. Example 6-13

Examine the following code and analyze the result. MOV MOV ADD

A,#+96 R1,#+70 A,R1

Solution: +96 0110 0000 + ±lQ 0100 011Q + 166 1010 0110

;A = 0110 0000 (A = 60H) ;R1 = 0100 0110 (R1 = 46H) ;A = 1010 0110 ;A = A6H = -90 decimal, INVALID!

and OV=l

According to the CPU, the result is -90, which is wrong. The CPU sets OV cate the overflow.

=

I to indi-

In Example 6-13 +96' dd d 7 was -90 Wh ? '. IS a e to + 0 and the result according to the CPU . y. The reason IS that the result was larger than what A could contain. 152

= Like all other 8-bit registers, A could only contain up to +127. The designers of the CPU created the overflow flag specifically for the purpose of informing the programmer that the result of the signed number operation is erroneous.

When is the OV flag set? In 8-bit signed number operations, OV is set to 1 if either of the following two conditions occurs: I. There is a carry from D6 to 07 but no carry out of 07 (CY = 0). 2. There is acarry from D7 out (CY = I) but no carry from D6 to 07. In other words, the overflow flag is set to I if there is a carry from 06 to 07 or from 07 out, but not both. This means that if there is a carry both from 06 to 07 and from 07 out, OV = O. In Example 6-13, since there is only a carry from 06 to 07 and no carry from 07 out, OV = I. Study Examples 6-14, 6-15, and 6- I 6 to understand the overflow flag in signed arithmetic. Example 6-14

Observe the following, noting the role of the OV flag. MOV MOV

ADD

A,#-128 R4,#-2 A,R4

;A = 1000 0000 (A = 80H) ~R4 = 1111 1110(R4 = FEH) ,'A = 0111 1110 (A=7EH=+126, invalid)

Solution: -128 +

-2

-130

1000 0000 1111 1110 0111 1110

and OV=l

According to the CPU, the result is + 126, which is wrong (OV = 1). Example 6-15

Observe the following, noting the OV flag. MOV MOV

ADD

A,#-2 Rl,#-5 A,R1

;A=l1l1 1110· (A=FEH) 'R1=1111 1011 (R1=FBH) :A=1111 1001 (A=F9H=-7,correct,OV=01 r

Solution: -2

±-=2 -7

1111 1110 1111 1011 1111 1001

and OV = 0

' 7 which is correct (OV = 0). According to the CPU, the resu It IS - , GIC INSTRUCTIONS, AND PROGRAMS CHAPTER 6: ARITHM ETIC , LO

153

Example 6-16 Examine the following, noting the role of Ov.

MOV MOV ADD

;A;OOOO r'R1;0001 ;A;OOOI

A, #+7 R1,#+lB A,R1

0111 (A;07H) 0010(R1;12H) 1001 (A;19H;+25,

correct,OV;O)

Solution: 7 +

-lJl 25

0000 0001 0001

0111 0010 1001

and OV ; 0

According to the CPU, this is +25, which is correct (OV

=

0)

From the above examples wc conclude that in any signed number addition, OV indicates whether the result is valid or not. If OV; I, the result is erroneous; if OV = 0, the result is valid. We can state cmphatically that in unsigned number addition we must monitor the status ofCY (carry nag), and in signed number addition, the OV (overflow) nag must be monitored by the programmer. In the 8051, instructions such as JNC and JC allow the program to branch right after the addition of unsigned numbers, as we saw in Section 6.1. There is no such instruction for the OV nag. However, this can be achieved by "JB PSW. 2" or "JNB PSW. 2" since PSW, the nag register, is a bit-addressablc register. This is discussed later in this chapter.

Instructions to create 2's complement The 8051 does not have a special instruction to make the 2's complement of a number. To do that, we can use the CPL (complement) instruction and ADD, as shown next. CPL ADD

A A,#l

1'8 complement (Invert) add 1 to make 2'8 complement

Review Questions I. 2. 3. 4.

In an 8-bit operand, bit _ is used for the sign bit. Convert -16H to Its 2's complement representation. The range of byte-sizcd signed operands IS _ to + Show +9 and -9 In binary. - __

5. Explain the difference betwcen a carry and an overnow.

SECTION 6.3: lOGIC AND COMPARE INSTRUCTIONS Apart from 1/0 and arithmetic instructions, logic instructions are some of most widely used Instructions. In this section we cover Boolean logic instructions such as AND, OR, exclusive-or (XOR), and complement. We will also study the compare instruction.

AND ;dest = dest AND source

ANL destination,source

Logical AND Function

This instruction will perform a logical AND on the two operands and place the result in the des- Inputs Output tination. The destination is normally the accumulator. The source operand can be a register, in mem- ~X~=,;Y~=..;X~A~N.;,D;;;..;Y~ ory, or immediate. See Appendix A.I for more on :::O__ ~O O::- __ the addressing modes for this instruction. The ANL :::0 __ ..:.1 0::-__ instruction for byte-size operands has no effect on .:.I__ ~O ...:O~-_ any of the flags. The ANL instruction is often used ~1 __ ...:1 ~1 -to mask (set to 0) certain bits of an operand. See X X AND Y Example 6-17. Y.

=D-

Example 6-17

Show the results of the following. MOV ANL

A,#35H A, #OFH

;A = 35H ;A A AND OFH (now A

05)

Solution:

35H OFH 05H

0011

0101

0000 0000

1111 0101

05H

35H AND OFH

OR ORL destination,source

;dest

dest OR source

=

Logical OR Function

The destination and source operands are ORed and the result is placed in the destination. The ORL instruction can be used to set certain bits of an operand to l , The destination is normally the accumulator. The source operand can be a register, In memory or immediate. See Appendix A for more on the addressing modes supported by this instruction. The ORL instruction for byte-size operands has no effect on any of the flags. See Example 6-18.

Output

Inputs

x

Y

XORY

°° ° ° I

1

I

°

I

I

I I

~=r>-XORY

155 CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

Example

6-18

Show the results of the following. MOV ORL

A,#04 A, #30H

;A ;A

04 A OR 30H

(now A ; 34H)

Solution: 04H 30H 34H

0000 0100 0011 0000 0011 0100

04H OR 30H ; 34H

XOR XRL destination, source

;dest

; dest

XOR

source

This instruction will perform the XOR operation on the two operands, and place the result in the destination. The destination is normally the accumulator. The source operand can Logical XOR Function be a register, in memory, or immediate. Sec Inputs Output Appendix A.I for the addressing modes of this instruction. The XRL instruction for byte-size x Y X XOR Y operands has no effect on any of the flags. See o 0 0 Examples 6-19 and 6-20. o I I XRL can also be used to see if two registers I 0 I have the same value. "XRL A, R1" will exclusive-or I I 0 register A and register RI, and put the result in A. If both registers have the same value, 00 is placed in A. X XOR Y Then we can use the JZ instruction to make a dccision based on the result. See Example 6-20.

~=J[)-

Example 6-19 Show the results of the following. MOV XRL

A,#54H A, #78H

Solution: 54H

zaa 2CH

0101 0100 0111 1000. 0010 1100

54H XOR 78H _ 2CH

Example 6-20 The XRL instruction can be us d t I h itself. Show how "XRL A A~' 1° e ear t e Contents of a register by XORing , e ears A, assummg that A = 45H.

it with

Solution: 45H

-Wi 00

156

0100 0101 0100 0101 0000 0000

XOR a nUmber with itself

0

Example 6-21,

Read and test PII to see whether it has the value 45H. If it does, send 99H to P2; otherWise, It stays c eared. . Solution:

MOV MOV MOV MOV XRL JNZ MOV EXIT:

P2,#00 PI, #OFFH R3,#45H A,P1 A,R3

;clear P2 ;make PI an input port ;R3;45H ;read PI

EXIT

;jump if A has value.other

than 0

P2,#99H

...

In the program in Example 6-21 notice the use of the JNZ instruction. JNZ and JZ test the contents of the accumulator only. In other words, there is no such thing as a zero flag in the 80SI. I Another widely used application of XRL is to toggle bits of an operand. For example, to toggle bit 2 of register A, we could use the following code. This code causes D2 of register A to change to the opposite value, while all the other bits remain unchanged. XRL

A,#04H

;EX-OR

A with 0000 0100

CPL A (complement accumulator) This instruction complements the contents of register A. The complement action changes the Os to Is and the Is to Os.This is also called J s complement. Logical Inverter

MOV A, #55H .now A;AAH CPL A (AAH) ;01010101 becomes, 10101010

Input

To get the 2's complement, all we, have to do is to add I to the I's complement. See Example 6-22. In other words, there is no 2's complement instruction in the 8051. Notice that in comple-

Output

X

NOT X

~O :,.1

~I __ --"-0--

x --J>o-

NOT X

Example 6-22

Find the 2 's complement of the value 8SH. Solution:

MOV CPL ADD

A,#85H A A, #1

85H i 1/ S i

2 IS

compo l'S compo

;

;

1000 0101 0111 1010 + 1 0111 1011

;

7BH 157

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

menting a byte, the data must be in register A. Although the CPL instruction cannot be used to complement RO-R7, it does work on PO-P3 ports. See Appendix A to see which addressing mode is available for the CPL instruction. Compare instruction The 8051 has an instruction for the compare operation. It has the following syntax. CJNE destination, source, relative

address

In the 8051, the actions of comparing and jumping are combined into a single instruction called CINE (compare and jump ifnot equal). The CJNE instruction compares two operands, and jumps if they arc not equal. In addition, it changes the CY flag to indicate if the destination operand is larger or smaller. It is important to notice that the operands themselves remain unchanged. For exampic, after the exccution of the instruction "CJNE A, #67H, NEXT", register A still has its original valuc. This instruction compares register A with value 67H and jumps to thc target address NEXT only ifrcgister A has a value other than 67H.

Example 6-23

Examine the following code, then answer the following questions. (a) Will it jump to NEXT? (b) What is in A after the CINE instruction is executed? #55H CJNE A,#99H,NEXT

MOV

A,

NEXT: Solution:

(a) Yes, it jumps because 55H and 99H are not equal. (b) A = 55H, Its ongInal value before the comparison.

.

In CJNE, the destination operand can

be In the accumulator or in one of the Rn registers. The SOurceoperand can bC In . a . . register, In mcmory, or immediatc S A d' . ~ . ppen .IX A for the addrcssing modes ofth' II1structlOn.This instruction affects thc ca~; ~_a3g only. CY ISchanged as shown in Table

158

Table 6-3: Carry Flag Setting For CJNE Instruction Compare

Carry Flag

destination> Source CY 0 destination < source CY-I

Example 6-24

Write code to determine if register A contains the value 99H. If so make RI = FFR otherwise, make Rl = O. " Solution: MOV RI, #0 CJNE A,#99H,NEXT MOV RI,#OFFH NEXT: . OVER: .

;clear Rl ;if A not equal to 99, then jump ;they are equal, make Rl = FFH ;not equal so RI = 0

The following shows how the comparison works for all possible conditions. CJNE R5,#80,NOT_EQUAL NOT_EQUAL:

JNC

NEXT

;checK R5 for 80 ;R5=80 ;jump if R5>80 ;R5 75 Solution:

OVER:

NEXT: EXIT:

CHAPTER

MOV MOV CJNE SJMP JNC MOV SJMP MOV

PI,#OFFH A,PI A,#75,OVER EXIT NEXT RI,A EXIT R2,A

6: ARITHMETIC,

;make PI an input port ;read PI port, 'temperature 75 ;jump if A not equal to ;A=75, exit ;if CY=O then A>75 ;CY=I, A75, save it in R2

LOGIC INSTRUCTIONS,

AND PROGRAMS

159

Example 6-26

Write a program to monitor P I continuously ing only if PI = 63H.

for the value 63H.

It should stop monitor-

Solution:

MOV PI,#OFFH HERE: MOV A,PI CJNE A,#63,HERE

,'make PI an input port

;get PI ;keep monitoring unless

Example 6-27 Assume internal RAM memory locations 40H - 44H contain the daily temperature for five days, as shown below. Search to see if any of the values equals 65. If value 65 does exist in the table, give its location to R4; otherwise, make R4 = O.

40H= (76)

41H= (79)

42H= (69)

43H= (65)

44H= (62)

Solution:

BACK:

NEXT:

MOV MOV MOV MOV CJNE MOV SJMP INC DJNZ

EXIT

...

R4,#O ;R4=O RO,#40H ;load pointer R2,#05 ;load counter A,#65 ;A=65, value searched for A,@RO,NEXT;compare RAM data with 65 R4,RO ;if 65, save address EXIT ;and exit RO ;otherwise increment pointer R2,BACK ;keep checking until count=O

The compare instruction is really a subtraction, except that the values of the operands do not change. Flags are changed according to the execution of the SUBB instruction. It must be emphasized again that in the CJNE instruction, the operands are not affected, regardless of the result of the comparison. Only the CY nag is affected. This is despite the fact that CJNE uses the subtract operation to set or reset the CY flag.

Review Questions I. Find the Content of register A after the following code in each case. (a) MOV A,#37H (b) MOV A,#37H (c) MOV A, #37H

ANL A,#OCAH

ORL A,#OCAH

XRL A,#OCAH

2. To mask certain bits of the accumulator we must ANL it with 3. To set certain bits of the accumulator to I we must ORL it with--4. XRLing an operand with itself results in _ 5. True or false. The CJNE instruction altcr~c

con;ents of its operands.

6.

What value must R4 have in order for the following instruction CJNE

not to jump?

R4,#53,OVER

7. Find the contents of register A after execution of the following code. CLR

A

ORL

A, #99H

CPL

A

SECTION 6.4: ROTATE INSTRUCTION AND DATA SERIALIZATION In many applications there is a need to perform a bitwise rotation of an operand. In the 8051 the rotation instructions RL, RR, RLC, and RRC are designed specifically for that purpose. They allow a program to rotate the accumulator right or left. We explore the rotate instructions next since they are widely used in many different applications. In the 8051, to rotate a byte the operand must be in register A. There arc two type of rotations. One is a simple rotation of the bits of A, and the other is a rotation through the carry. Each is explained below.

Rotating the bits of A right or left RR

;rotate right A

A

In rotate right, the 8 bits of the accumulator are rotated right one bit, and bit DO exits from the least significant bit and enters into D7 (most significant bit). See the

[I

MSB _.

LSB ~

code and diagram. MOV

A,#36H

;A=OOl1

0110

RR

A

;A=OOOl

1011

RR

A

;A=lOOO

1101

RR

A

; A=1100

0110

RR

A

; A=0110

0011

RL

A

;rotate left A

In rotate left, the 8 bits of the accumulator are rotated left one bit, and bit 07 exits from the MSB (most significant bit) and enters into DO (least significant bit). See the code and diagram. MOV

A,#72H

RL

A

;A=0111 'A=1110

0010 0100

'A=1100

1001

'

. . h RR d RL instructions that no flags are a ffected ecte . Notice III t e an

RLA'

. OGIC INSTRUCTIONS, AND PROGRAMS CHAPTER 6: ARITHMETIC, L

161

Rotating through the carry

There are two more rotate instructions flag. Each is shown next. RRC A

t e

J

.

They involve the carry

;rotate ric_lhtthrough carry

In RRC A, as bits are rotated from left to right, they exit the LSB to the earry flag, and the carry flag enters the MSB. In other words, in RRC A the LSB is moved to CY and CY IS moved to the MSB. In reahty,. the carry flag acts as ifit is part of register A, making it a 9-bit register. CLR C

. h 805 In

[,

MSB -~~

LSB

1--. cv

MOV A, #26H

;make CY=O ,'A=0010 OUO

RRC A RRC A RRC A

,'A=OOOl 0011 CY=O ;A=OOOO 1001 CY=l ,'A=1000 0100 CY=l

RLC A

;rotate left through carry

In RLC A, as bits are shifted from right to left they exit the MSB

L

and enter the carry flag, and the CY carry flag enters the LSB. In other words, in RCL the MSB is moved to CY (carry flag) and CY is moved to the LSB. See the following code and diagram.

SETB

C

;make CY=l

MOV

A,#lSH

RLC RLC RLC RLC

A

;A=OOOl ;A=0010 ;A=0101 ;A=1010 ;A=0101

A A A

0101 1011 0110 1100 1000

-J MSB ..... -

I

0---

LSB

]

]I .

CY=O CY=O CY=O CY=l

Serializing data Serializing data is a way of sending a byte of data one bit at a time through aally: single pin of microcontroller. There are two ways to transfer a byte of data seri1. Using the serial port. In using the serial port, programmers have very limited control over the sequence of data transfer. The detai Is of serial port data transfer are discussed in Chapter 10. 2. The second method of serializing data is to transfer data one bit at a time and 162

control erations devices board.

the sequence of data and spaces in between them. In many new genof devices such as LCD, ADC, and ROM, the serial versions of these are becoming popular since they take less space on a printed circuit Wc discuss this important topic next.

Serializing a byte of data Serializing data is one of the most widely used applications of the rotate instruction. Wc shewed in Chapter 5 how the CY flag status can be moved to any pin of ports PO - P3. Using that concept and the rotate instruction, we transfer a byte of data serially (one bit at a time). Repeating the following sequence 8 times will transfer an entire byte, as shown in Example 6-28. RRC

A

MOV

Pl. 3, C

;move the bit to CY ;output carry as data bit

Example 6-29 shows how to bring in a byte of data serially one bit at a time. We will see how to usc these concepts in Chapter 13 for a serial ADC chip.

Example 6-28 Write a program to transfer value 41H serially (one bit at a time) via pin P2.1. Put two highs at the start and end of the data. Send the byte LSB first. Solution: MOV A,#41H

SETB P2.1 SETB P2.1 MOV RS, #8 HERE:RRC A MOV P2 .1,C DJNZ RS, HERE SETB P2.1 SETB P2.1

;high ;high

;send the carry bit to P2.1 ;high ;high

PIN

DI--"'~ E ll--·~ , D 1...-_---REG

A

P2.1 ,

DO

07

CHAPTER6:A

RlTHMETIC '

LOGIC INSTRUCTIONS, AND PROGRAMS

163

Example 6-29

. .. d Write a program to bring in a byte of data sena. IIyon e bit at a time Via pm P2.7 an save .. In regis. t er R2 . The byte comes in with the LSB first. It Solution: MOV R5, #8 HERE:MOV C,P2. 7 RRC A DJNZ R5, HERE MOV R2,A

bring in bit

;save it

PIN

I p2.7I-~·~El--·~D ...__...

R_EG_A

07

D DO

Single-bit operations with CY Aside from the fact that the carry flag (CY) is altercd by arithmetic and logic instructions, in the 8051 there are also several instructions by which the CY flag can be manipulatcd directly. These instructions are listed in Table 6-4. Of the instructions in Table 6-4, we have shown the usc of lNC, CLR, and SETB in many examples in the last fcw chaptcrs. The next few examples give simple applications of the instructions in Table 6-4, including some dealing with the logic operations AND and OR. Example 6-30 Write a program to save the status of bits PI.2 and PI.3 on RAM bit locations 6 and 7, respectively. Solution: MOV C,PI.2 MOV 06,C MOV C, Pl.3 MOV 07,C 164

;save ;save ;save ;save

status of PI.2 on Cy carry in RAM bit location 06 status of PI.3 on CY carry in RAM bit location 07

s Table 6-4: Carry Bit-Relat ed Instruchons . I nstruction SETS C CLR C CPL C MOY MOY bCb , INC target JC target ANL C ,bit ANL C ,fbit .

Function make CY = I clear carry bit (CY = 0) complement carry bit. coPY carry status to btt. location (CY = b) coPY bit location status to carry (b = CY) lump to target if CY = 0 jump to target if CY = I AND CY WIt . h biIt and save it on CY AND CY WIt . h Inverted . bit. and save it on CY

ORL

ORCY wit. h iInverted bit and save it on CY

C

, Cfbit

Example 6-31 Assume that bit P2.2 is used to control an outdoor light and bit P2.5 a light inside a building, Show how to turn on the outside light and turn off the inside one. Solution: ;CY = 1 iCY = P2.2 ORed with CY

SETB C C,P2.2 ORL P2.2,C MOV CLR C

ANL MOV

;turn it "on" if not alr-eady "on"

C,P2.5 P2.5,C

;CY iCY

= o = P2 .5 ANDed wi th

CY

;turn it off if not already off

Example 6-32 Write a program that finds the number of Is in a given byte. Solution:

AGAIN:

NEXT:

MOV MOV MOV RLC JNC INC DJNZ

Rl,#O R7,#8 A, #97H A

NEXT Rl R7,AGAIN

;Rl keeps the number of Is ;counter = 08 rotate 8 times ;find the number of Is in 97H ;rotate it through the CY once ;check for CY ;if CY=1 then add one to count ;go through this 8 times

SWAP A Another useful instruction is the SWAP instruction. It works only on the accumulator (A). It swaps the lower nibble and the higher nibble. In other words, CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

165

the lower 4 bits arc put into the higher 4 bits, and the higher 4 bits arc put into the lower 4 bits. See the diagrams below and Example 6-33.

before:

I

07 - 04

before:

I

0111

II

03 - 00

"

0010

I

Sa~~p

after: SWAP

I

03 - 00

II

07 - 04

0010

"

0111

I

Example 6-33 (a) Find the contents of register A in the following code. (b) In the absence ofa SWAP instruction, how would you exchange the nibbles? Write a simple program to show the process. Solution: (a) MOV

A,#72H

;A

= 72H

SWAP A

;A

=

MOV

A, #72H

RL RL RL

A A A

;A=Olll ;A=lllO ;A=llOO ;A=lOOl

RL

A

;A=OOlO 0111

27H

(b) 0010 0100 1001 0011

Review Questions I. What is the value of register A after each of the f II '. . MOV A, #25H 0 owing instructions? RR RR RR RR

A

A A

A

2. W~~~iS t~c, ~~~~ of register A after each of the following instructions? RL RL RL RL

A A A A

CHA

3. WhatCLR is theAvalue of register Aft· . a er each of the following. instructions? SETB RRC SETB RRC

C A C A

4. Why does . an error in the 805 I? . . "RLC R I" give 5. What IS in register A after the execution of the following code? MOV

A, #8SH

.

SWAP A

ANL

A,#OFOH

6. Find the status of the CY flag after the following code. CLR A ADD A,#OFFH JNC

OVER

CPL

C

OVER:

7. Find the status of the CY flag after the following code. CLR C JNC

OVER

SETB C OVER:

8. Find the status of the CY flag after the following code. CLR C JC

OVER

CPL

C

OVER:

9. Show how to save the status of P2.? in RAM bit location 31. 1O. Show how to move the status of RAM bit location 09 to P 1.4.

SECTION 6.5: BCD, ASCII, AND OTHER APPLICATION PROGRAMS In this section we provide some real-world examples on how to use arithmetic and logic instructions. We will see their applications in real-world devices covered in future chapters. For example, many newer microcontrollers have a real time clock (RTC), where the time and date are kept even when the power is off. These microcontrollers provide the time and date in BCD. However, to display them they must be converted to ASCII. Next, we show the application of logic and rotate instructions in the conversion of BCD and ASCII.

:HAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

167

Table 6-5: ASCn Code for Digits 0 - 9 Key 0 1 2 3 4 5 6 7 8 9

ASCII (hex) 30 31 32 33 34 35 36 37 38 39

Binary 011 0000 Oil 0001 0110010 01100lJ 011 0100 0110101 0110110 011 0111 Oil 1000 011 1001

BCD (unpacked) 00000000 00000001 00000010 0000001 J 00000100 00000101 00000110 00000111 00001000 00001001

ASCII numbers On ASCII keyboards, when the key "0" is activated, "0 II 0000" (30/-1) is provided to the computer. Similarly, 31H (01 J 000 I) is provided for the key" I", and so on, as shown in Table 6-5. It must be noted that although ASCII is standard in the United States (and many other countries), BCD numbers are universal. Since the keyboard, printers, and monitors all usc ASCII, how does data get converted from ASCII to BCD, and vice versa? These are the subjects covered next. Packed BCD to ASCII conversion Many systems have what is called a real-time clock (RTC). The RTC provides the time of day (hour, minute, second) and the date (year, month, day) continuously, regardless of whether the power is on or off (see Chapter 16). However, this data is provided in packed BCD. For this data to be displayed on a device such as an LCD, or to be printed by the printer, it must be in ASCII format. To convert packed BCD to ASCII, it must first be converted to unpacked BCD. Then the unpacked BCD is tagged with 0 II 0000 (30H). The following demonstrates converting from packed BCD to ASCII. See also Example 6-34. Packed BCD 29H 0010

1001

Unpacked

BCD

02H & 09H 0000 0010 & 0000 1001

ASCII 32H 0011 0011

39H 0010 & 1001 &

ASCII to packed BCD conversion To convert ASCII to packed BCD, it is first converted to unpacked BCD (to get rid of the 3), and then combined to make packed BCD. For example, for 4 ~nd 7 the k~,Yboardgives 34 and 37, respectively. The goal is to produce 47/-1 or 01000111 , which IS packed BCD. This process is illustrated next. J 68

= Key

ASCII

Unpacked

4

34 37

00000100 00000111

7

A, #'4' A, #OFH A B, A A, #'7' A, #OFH A, B

MOV ANL SWAP MOV MOV ANL ORL

BCD

Packed BCD 01000111 or 47H

;A=34H, hex for ASCII char 4 ;mask upper nibble (A=04) ;A=40H ;R1=37H, hex for ASCII char 7 ;mask upper nibble (R1=07) ;A=47H, packed BCD

After this conversion, the packed BCD numbers are processed and the result will be in packed BCD format. As we saw earlier in this chapter, a special instruction, "DA A", requires that data be in packed BCD format. Example 6-34

Assume that register A has packed BCD. Write a program to convert packed BCD to two ASCII numbers and place them in R2 and R6. Solution: MOV MOV ANL ORL MOV MOV ANL RR RR RR RR ORL MOV

A,#29H R2,A A,#OFH A,#30H R6,A A,R2 A,#OFOH A A

A A

A,#30H R2,A

;A=29H, packed BCD ;keep a copy of BCD data in R2 ;mask the upper nibble (A=09) ;make it an ASCII, A=39H ('9') ;save it (R6=39H ASCII char) ;A=29H, get the original data ;mask the lower nibble (A=20) ;rotate right ;rotate right ;rotate right ;rotate right, (A=02) ;A=32H, ASCII char '2' ;save ASCII char in R2

Of course, in the above code we can replace all the RR instructions with a single "SWAP A" instruction.

Using a look-up table for ASCII · ti ns it I·Smuch easier to use a look-up table to get the In some app IIca 10 .. . This is a widely used concept 111 interfacing a keyboard d ASCII character we nee . to tbe microcontroller. This is shown in Example 6-35.

169 CHAPTER

6: ARITHMETIC,

LOGJC INSTRUCTIONS,

AND PROGRAMS

Example 6-35

.

000 001 010 011

'0' 'I' '2' '3' .

100 101 110 III

'4' '5' '6' '7'

Solution: MOV MOV

DPTR,#MYTABLE A, PI ;get SW status ANL A,#07H ;mask all but lower 3 bits MOVe A,@A+DPTR ;get the data from look-up table MOV P2,A ;display value SJMP $ ; stay here ,"-------MYTABLE

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

ORG 400H DB '0' 'I' '2' '3' t4 I

,

,

1

t I

'5'

I

'6'

I

'7

1

END You can easily modify this program for the hex values of 0 - F, which are supplied by 4x4 keyboards. See Chapter 12 for a keyboard example.

Checksum byte in ROM To ensure the integrity of the ROM contents, every system must perform the checksum calculation. The process of checksum will detect any corruption of the contents of ROM. One of the causes of ROM corruption is current surge, either when the system is turned on or during operation. To ensure data integrity in ROM, the checksum process uses what is called a checksum byte. The checksum byte is an extra byte that is tagged to the end of a series of bytes of data. To calculate the checksum byte of a series of bytes of data, the following steps can be taken. I. Add the bytes together and drop the carries. 2. Take the 2's complement of the total sum; this is the checksum byte, which becomes the last byte of the series. To perform the checksum operation, add all the bytes, including the checksum byte. The result must be zero. If it is not zero, one or more bytes of data have been changed (corrupted). To clarify these important concepts, see Example 6-36. 170

Example 6-36

Assume that we have 4 byte f h . (a) Find the checksum b t sOb exadecimal data: 25H, 62H, 3FH, and 52H. integrity, and (c) ifthe s:C~~d the checksum operation to ensure data detects the error. y has been changed to 22H, show how checksum

~\:~~~rm

Solution:

(a)

Find the checksum byte. 25H +

62H

+

3FH

+

52H 118H

I .

(b)

(Dropping the carry of I, we have 18H. Its 2's complement is E8H. Therefore the checksum byte is E8H.)

Perform the checksum operation to ensure data integrity. 25H +

62H

+

3FH

+

52H

+

E8H 200H

(c)

(Dropping the carries, we see 00, indicating data is not corrupted.)

If the second byte 62H has been changed to 22H, show how checksum detects the error. . 25H

+

22H

+

3FH

+

52H

+

E8H

leOH

(Dropping the carry, we get COH, which is not 00, and that means data is corrupted.) .

Checksum program in modules Thc checksum generation and testing program is given in modular form. We have divided the program into several modules (subroutines or subprograms) Dividing a program into several modules (called functions in C programming) allows us to use its modules in other applications. It is common practice to divide a program into several modules, test each module, and put them into a library. The checksum program shown next has three modules: It (a) gets the data from code ROM, (b) calculates the checksum byte, and (c) tests the checksum byte for any data error. Each of these modules can be used in other applications.

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

171

Checksum Program ,·CALCULATING AND TESTING CHECKSUM BYTE DATA_ADDR COUNT RAM ADDR

EQU 400H EQU 4 EQU 30H

·------------main program , ORG 0 ACALL COPY DATA ACALL CAL CHKSUM ACALL TEST CHKSUM SJMP $ ;--------copying data from code ROM to data RAM COPY DATA: MOV DPTR,#DATA ADDR ;load data address MOV RO,#RAM ADDR ;load RAM data address MOV R2,#COuNT ;load counter HI: CLR A ;clear accumulator MOVC A,@A+DPTR ;bring in data from code ROM MOV @RO ,A ;save it in RAM INC DPTR ;increment DPTR INC RO ;increment RO DJNZ R2,Hl ;repeat for all RET ;-----calculating checksum CAL CHKSUM: MOV Rl,#RAM ADDR MOV R2,#COuNT CLR A H2: ADD A,@Rl INC Rl DJNZ R2,H2 CPL A INC A MOV @Rl,A RET

byte ;load data address ;load count ;clear accumulator ;add bytes and ignore carries i

increment

Rl

;repeat for all ;1's complement ;2's complement(checksum byte) ;save it in data RAM

;----------testing checksum byte TEST CHKSUM: MOV Rl,#RAM ADDR ;load data address MOV R2,#COuNT+l ;load counter CLR A ;clear accumulator H3: ADD A,@Rl ;~dd bytes and ignore carries INC Rl ;lncrement Rl DJNZ R2,H3 ;repeat for all JZ G 1 ;is result zero? then good MOV Pl,#'B ;if not, data is bad SJMP OVER G 1: MOV PI/#'G' ;data is not corrupted OVER: RET I

;----------my data in code ROM ORG 400H MYBYTE: DB 25H,62H,3FH 52H END '

-

Binary (hex) to ASCII conversion Many ADC (analog-to-digital converter) chips provide output data in binary (hex). To display the data on an LCD or PC screen, we need to convert it to ASCII. The following code shows the binary-to-ASCII conversion program. Notice that the subroutine gets a byte of 8-bit binary (hex) data from P I and converts it to decimal digits, and the second subroutine converts the decimal digits to ASCIl digits and saves them. We are saving the low digit in the lower address location and the high digit in the higher address location. This is referred to as the Little-Endian convention, that is, low-byte to low-location and high-byte to highlocation. All Intel products use the Little-Endian convention. Binary-to-ASCII Conversion Program ;CONVERTING BIN (HEX) TO ASCII RAM ADDR

EQU 40H ASCI RSULT EQU SOH COUNT EQU 3 ; main program ORG 0 ACALL BlliI DEC CONVRT ACALL DEC::)ScI _CONVRT SJMP $ ; Converting BIN (HEX) TO DEC (OO-FF TO 000-255) BIN DEC CONVRT: - MOV RO,#RAM ADDR ;save DEC digits in these RAMlocations MOVA,P1 ;read data from P1 MOVB, #10 ;B~OA hex (10 dec) DIV AB ;divide by 10 MOV@RO,B ;save lower digit INC RO MOV B,#10 'divide by 10 once more DIV AB :save the next digit , MOV@RO,B INC RO ,.save the last digit MOV@RO,A RET DEC digits to displayable ASCII digits . Converting , DEC ASCI CONVRT: - MOV RO,#RAM_ADDR ;addr of DEC data MOVR1,#ASCI_RSULT ;addr of ASCII data MOVR2,#3 BACK: MOVA,@RO ORL A,#30H MOV@R1,A INC RO INC R1 DJNZ R2,BACK RET

; count ;get DEC digit t an ASCII digit ;mak e 1 ;save lt . ;next dlglt ; next . ;repeat untll the last

-------

-------

one

----------

j-----

END

OGIC INSTRUCTIONS, AND PROGRAMS :HAPTER 6: ARITHME TIC , L

173

Review Questions I. For the following decimal numbers, give the packed BCD and unpacked BCD representations. (a) 15 (b) 99 .' 2. Show the binary and hex formats for "76" and ItS BCD isrructio is executed? 3. Does the register A have BCD data after the following mstruc Ion . MOV

A, #54

? 4. 67H in BCD when converted to ASCII is __ H and __ H 5. Does the following convert unpacked BCD in register A to ASCII. MOV

A,#09

ADD

A,#30H

6. The checksum byte method is used to test data integrity in __ (RAM R~~J' 7. Find the checksum byte for the following hex values: 88H, 99H, AA, , CCH,DDH 8. True or false. If we add all the bytes, including the checksum byte; and the result is FFH, there is no error in the data.

H

SUMMARY This chapter discussed arithmetic instructions for both signed and unsigned data in the 8051. Unsigned data uses all 8 bits of the byte for data, making a range of 0 to 255 decimal. Signed data uses 7 bits for data and I for the sign bit, making a range of -128 to +127 decimal. Binary coded decimal (BCD) data represents the digits 0 through 9. Both packed and unpacked BCD formats were discussed. The 8051 contains special instructions for arithmetic operations on BCD data. In coding arithmetic instructions for the 8051, special attention has to be given to the possibility of a carry or overflow condition. This chapter also defined the logic instructions AND, OR, XOR, and complement. In addition, 8051 Assembly language instructions for these functions were described. Compare and jump instructions were described as well. These functions are often used for bit manipulation purposes. The rotate and swap instructions of the 8051 are used in many applications such as serial devices. This chapter also described checksum byte data checking, BCD and ASCll formats, and conversions. .

PROBLEMS SECTION 6.1: ARITHMETIC INSTRUCTIONS I. Find the CY and AC flags for each of the following. (a)

MOV A, #3FH ADD A, #45H

174

(b)

MOV A #99H ADD A: #58H

--------

(c)

(e)

MOV A,#OFFH SETB C ADDC A, #00 MOV A,#OFEH SETB C ADDC A, #01

(d)

MOV A, #OFFH ADD A,#l

(I)

CLR C MOV A, #OFFH ADDC A, #01 ADDC A,#O

2. Write a program to add all the digits of your lD number and save the result in R3. The result must be in BCD 3. Write a program to add the following numbers, and save the result in R2, R3. Thc data IS stored In on-chip ROM. ' ORG MYDATA:

250H DB 53,94,56,92,74,65,43,23,83

4. Modify Problem 3 to make the result in BCD. 5. Write a program to (a) write the value 55H to RAM locations 40H - 4FH, and (b) add all these RAM locations' contents together, and save the result in RAM locations 60H and 61H. 6. State the steps that the SUBB instruction will go through and for each of the following. (a) 23H - 12H (b) 43H - S3H (c) 99 - 99 7. For Problem 6, write a program to perform each operation. 8. True or false. The "DA A" instruction works on register A and it must be used after the ADD and ADDC instructions. 9. Write a program to add 897F9AH to 34BC48H and save the result in RAM memory locations starting at 40H. 10. Write a program to subtract 197F9AH from 34BC48H and save the result in RAM memory locations starting at 40H. II. Write a program to add BCD 197795H to 344548H and save the BCD result in RAM memory locations starting at 40H. 12. Show how to perform 77 x 34 in the 805 I. 13. Show how to perform 77 -i- 3 in the 8051. 14. True or false. The MUL and DIY instructions work on any register of thc 805 j . 15. Write a program with three subroutines to (a) transfer the following data from on-chip ROM to RAM locations starting at 30H, (b) add them and save the result in 70H, and (c) find the average ofthc data and store it in R7. Notice that the data is stored in a code space of on-chip ROM. ORG MYDATA:

250H DB 3,9,6,9,7,6,4,2,8

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARlTHMETIC OPERATIONS 16. Show how the following are represented by the assembler. (a)-23 (b)+12 (c)-28 (d) +6FH (e) -128 (I) + 127 \ 7. The memory addresses in computers are (signed, unsigned) numbers. 175

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

. c. h of the following and indicate the status of the OV 18. Write a program lor eac flag for eaeh. (a)(+15) + (-12) (b)(-123) + (-127) (c) (+25H) + (+34H) (d) (-127) + (+127) . 19. Explain the difference between the CY and OV flags and where each one IS

used. 20. Explain when the OV flag is raised. 21. Which register holds the OV flag? 22. How do you detect the OV flag in the 8051? How do you detect the CY flag? SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS 23. Assume that these registers contain the following: A = FO, B = 56, and R 1 = 90. Perform the following operations. Indicate the result and the register where it is stored. Note: The operations are independent of eaeh other. (a) ANL A, #4SH (c) XRL A, #76H (e) XRL A,Rl

(b) ORL A, B (d) ANL A, Rl (I) ORL A,Rl

(g) ANL A, #OFFH (i) XRL A, #OEEH

(h) ORL A, #99H

0J

XRL A, #OAAH

24. Find the contents of register A after each of the following instructions (a) MOV A, #6SH (b) MOV A, #70H ANL A,#76H

(c) MOV A, #9SH

.

ORL A,#6BH

(d) MOV A, #SDH

XRL A,#OAAH

MOV R3,#78H ANL A,R3

(e) MOV A, #OCSH MOV R6,#12H ORL A,R6

(I) MOV A, #6AH MOV R4,#6EH XRL A,R4

(g) MOV A,#37H ORL A,#26H

25. True or false. In using the ClNE . . '. IIlstructlon ' we must use tIic accumulator t he destination 26. 27. 28 .

Is the following a valid instruction? "CJNE R Does the 8051 have a "ClE" (' . 4, #67, HERE" [ di compare and jump if . n icatc the status ofCY after ClN . P I equal) instruction? (a) MOV A, #2SH E IS executed in each of the following CJNE A, #44H OVER (b) MOV A, #OFFH (c) MOV A, #34 ' CJNE A, #6FH, NEXT CJNE A,#34,NEXT (d) MOV Rl,#O (e) MOV RS,#S4H CJNE Rl,#O,NEXT CJNE

(I) Mav A.."JL

RS,#OFFH,NEXT

29. In Problem 28, indicate Whether

0

h CJNE r not t e jurn

as

cases .

A,#OAAH A, #55H

°

A, # 0, NEXT

h

p appens for each case.

176

CHAP

SECTION

6.4: ROTATE INSTRUCTION

AND DATA SERIALIZATION

30. Find the contents of register A after each of the following is executed, (a) MOV A, #56H (b) MOV A, #39H ' SWAP

A

CLR

C

RR

A

RL

A

RR

A

RL

A

(c) CLR

(d)

C

SETB

C

MOV

A, #4DH

MOV

A, #7AH

SWAP

A

SWAP A

RRC

A

RLC

A

RRC

A

RLC

Ai'

RRC

A

!

31. Show the code to replace the SWAP code (a) using the rotate right instructions (b) using the rotate left instructions 32. Write a program that finds the number of zeros in an 8-bit data item. 33, Write a program that finds the position of the first high in an 8-bit data item. The data is scanned from DO to 07. Give the result for 68H, 34, Write a program that finds the position of the first high in an 8-bit data item, The data is scanned from 07 to DO. Give the result for 68H. 35, A stepper motor uses the following sequence of binary numbers to move the motor. How would you generate them? ' 1100,0110,0011,1001 SECTION

6.5: BCD, ASCII, AND OTHER APPLICATION

PROGRAMS

36. Write a program to convert a series of packed BCD numbers to ASCII. Assume that the packed BCD is located in ROM locations starting at 300H, Place the ASCII codes in RAM locations starting at 40H. ORG 300H MYDATA:

DB

76H,87H,98H,43H

37. Write a program to convert a series of ASCII numbers to packed BCD, Assume that the ASCII data is located in ROM locations starting at 300H, Place the BCD data in RAM locations starting at 60H. ORG 300H MYDATA:

DB

"87675649"

38. Write a program to get an 8-bit binary number from PI, convert it to ASCII, and save the result in RAM locations 40H, 41H, and 42H, What IS the result If P I has 1000 1\ 0 I binary as input? 39. Find the result at points (I), (2), and (3) in the following code, CJNE A,#50,NOT_EQU , ;point (1) NOT_EQU:

JC

NEXT

;point ;point

(2) (3)

NEXT: CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

177

40 Assume that the lower four bits of P I are connected to four switches. Write a . program to send the following ASCII characters to P2 based on the status of the switches. 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 Ij II

'0' 'I'

'2' '3' '4'

'5' '6' '7' '8' '9' 'A'

'B' 'C' '0' 'E'

'F'

41. Find the checksum byte for the following ASCII message: "Hello" 42. True or false. If we add all the bytes, including the checksum byte, and the result is DOH,then there is no error in the data. 43. Write a program: (a) To get the data "Hello, my fellow World citizens" from code ROM, (b) to calculate the check-sum byte, and (c) to test the checksum byte for any data error. 44. Give three reasons you should write your programs in modules. 45. To display data on LCD or PC monitors, it must be in (BIN, BCD, ASCII). 46. Assume that the lower four bits of P I arc connectcd to four switches. Write a program to send the following ASCII characters to P2 based on the status of the switches. Do not use the look-up table method, 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001

'0' 'I' '2' '3 ' '4' '5' '6' '7' '8' '9'

ANSWERS TO REVIEW QUESTIONS SECTION 6.1: ARITHMETIC iNSTRUCTIONS I. 2.

A, B A, B

3.

No. We must use registers A and B for this operation.

4.

A, B

5. 6. 7.

A, B No. We must use registers A and B for this operation. A, the accumulator No. We must usc registers A and B for this operation.

8.

9.

MOV A, R1 ADD

A,R2

10. A, the accumulator

II. (a) A

= 00 and CY

=

(b) A = FF and CY ~ 0

I

12. 43H

.:..Q.5.!:!

0100 0011 0000 0101 2' s complement

+

0100 0'011 1111 .1011

3EH 0011 1110 13. A

= 95H - 4FH'-

I

= 45H

SECTION 6.2: SIGNED NUMBER CONCEPTS AND ARITHMETiC OPERATIONS I.

07

2.

16H is 00010110 in binary and its 2's complement is 1110 1010 or

3.

-16H = EA in hex. -128 to +127 +9 = 00001001 and -9 = 11110111 or F7 in hex.

4. 5.

An overflow is a carry into the sign bit (07), but the carry is a carry out of register (07).

SECTION 6.3: LOGIC AND COMPARE INSTRUCTIONS I. 2. 3.

4. 5. 6.

7.

(a) 02 Zeros One All zeros False

(c) FDH

(b) FFH

#53 66H

SECTION 6.4: ROTATE iNSTRUCTION AND DATA SERIALIZATION I.

52H

2. 3.

2AH COH

5. 6.

SOH CY =0 CY= I CY= I

4.

7.

8. 9.

Because all the rotate instructions work with the accumulator only

MOV C, P2. 7 MOV 31,C

10. MOV C,9 MOV PI. 4, C

i

save status

jsave

carry

;save statuS jsave carry

of P2.7 on CY in RAM bit location of RAM bit in Pl. 4

09 in

06 CY

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS

179

SECTION 6.5: BCD. ASCIJ, AND OTHER APPLICATION PROGRAMS (a) 15H = 000 I 0101 packed BCD, 0000 000 I,00000 I0 I unpacked BCD (b) 99H = 1001 1001 packed BCD, 00001001,00001001 unpacked BCD 2. 3736H = 00110111 OOIIOIIOB. and in BCD we have 76H = 0111 OIIOB 3. No. We need to write it54H (with the H) or OIOIOIOOBto make it in BCD. The value 54 without the "H" is interpreted as 36H by the assembler. 4. 36H,37H 5. Yes, since A = 39H 6. ROM I.

7. 8.

88H + 99H + AAH + BBH + CCH + DOH its 2's complement is OIH. False

= 42FH.

Dropping the carries we have 2FH, and

-

CHAPTER 7

8051 PROGRAMMING INC

OBJECTIVES

Upon completion of this chapter, you will he able to:

» » » » » » » »

Examine the C data type for the 8051 Code 805] C programs for time delay and lIO operations Code 805] C programs for I/O bit manipulation Code 805] C programs for logic and arithmetic operations Code 8051 C programs for ASCII and BCD data conversion Code 8051 C programs for binary (hex) to decimal conversion Code 8051 C programs to use the 805] code space Code 805] C programs for data serialization

181

Why program the 8051 in C? Compilers produce hex files that we download into the ROM of the mierocontroller. The size of the hex file produced by the compiler IS one of the mam concerns of microcontroller programmers, for two reasons: l. Microcontrollers have limited on-chip ROM.

2. The code space for the 805J is limited to 64K bytes. How does the choice of programming language affect the compiled program size'? While Assembly language produces a hex file that is much smaller than C, programming in Assembly language is tedious and time consumrng, C programming, on the other hand, is less time consuming and much easier to write, but the hex file size produced is much larger than if we used Assembly language. The following arc some of the major reasons for writing programs in C instead of Assembly: I. 2. 3. 4.

It is easier and less time consuming to write in C than Assembly. C is easier to modify and update. You can usc code available in function libraries. C code is portable to other microcontrollcrs with little or no modification.

The study of C programming for the 8051 is the main topic of this chapter. In Section 7.1, we discuss data types and time delays. I/O programming is shown in Section 7.2. The logic operations AND, OR, XOR, inverter, and shift arc discussed in Section 7.3. Section 7.4 describes ASCII and BCD conversions and checksums. In Section 7.5 we show how 8051 C compilers usc the program (code) ROM space for data. Finally, in Section 7.6 data serialization for 8051 is shown.

SECTION 7.1: DATA TYPES AND TIME DELAY IN 8051 C In this section we first discuss C data types for the 8051 and then provide code for time delay functions.

C data types for the 8051 " Since one of the goals of 805 I C programmers is to create smaller hex files, It IS worthwhile to re-examine C data types for 8051 C. In other w d d d d' or s, a goo un erstan II1g of C data types for the 805 I can help programmcrs to create smaller hex files. In this section we focus on the specific C data types that are most useful and Widely used for the 8051 microcontroller. Unsigned char

Since the 805 I is an 8-b't' II . I mlcrocontro cr, the character data type is the most natural choice for many applications The unsi d har i . h k· . nsignc c ar IS an 8-blt data type t at ta es a value 111 the range of 0- 255 (00 _ FFH) It' . used data types for the 8051 I '. . ISone of the most Widely . n many Situations, such as setting a counter value 182

,

where there is no need for signed data we should use the unsigned char instead of the signed char. Remember that C compilers usc the signed char as the default if we do not put the keyword unsigned in front of the char (see Example 7-1). We can also use the unsigned char data type for a string of ASCII characters, including extended ASCII characters. Example 7-2 shows a string of ASCII characters. See Example 7-3 for toggling ports. In declaring variables, we must pay careful attention to the size of the data and try to use unsigned char instead of int if possible. Because the 8051 has a limited number of registers and data RAM locations, using the int in place of the char data type can lead to a larger size hex file. Such a misuse of the data types in compilers such as Microsoft Visual C++ for x86 IBM PCs is not a significant issue.

Example 7-1 Write an 8051 C program to send values 00 - FF to port PI. Solution: #include

void main(void) { unsigned char Z; for(z=O;z- 0

+

OB·9F

vee

10uF

2

~'"

RST

"

..

~

a

RxD

+5V

...,N

TxD

8.2k

5

4

,0

}

1k 1k

EA

10k 2N3904

P2.6

.5V

)

P2.7 :I:

DPENDR PULLED UP

l;UN

"'~ 1 >-0

PsEN

10k

~!=

(J)

I,

....

DS89C4xD

30pF

XTAL1

2N3904

PROGRAM

GND

XTAL2 11.0592 MHz

.~

Figure 8-6. DS89C4xO Trainer (for MAX232 connection, see Section 10.2)

Notice from Figure 8-6 that ihe reset circuitry and setial port connections are the same as in any 805 l-based system, However, the extra circuitry needed for programming are two transistors, a switch, and 10K and IK-ohm resistors, In fact, you ean add these components to your 8751/89C51 system and use it as a DS89C4xO system by simply plugging a DS89C4xO chip in the socket. The switch allows you to select between the program and run options, We can load our program into the DS89C4xO by setting the switch to V cc. and run the program by setting it to Gnd. Figure 8-6 shows the connection for the 8051 Trainer from www.MieroDigitaIEd.com. The Trainer provided by this web site has both of the serial ports connected and accessible via two DB-9 connectors. It also has 8 LEDs and 8 switches along with the PO- P3 ports, all of which are accessible via terminal blocks. It also comes with an on-board power regulator. See the following Web site for the DS89C4xO Trainer: www.MicroDigitaIEd.com

CHAPTER

8: 805] HARWARE CONNECTION AND INTEL HEX FILE

227

Communicating

with the D589C4xO trainer

After we build our DS89C4xO-based system, we can communicate with it using the HyperTerminal software. HypcrTerminal comes with Microsoft Windows 98, NT, 2000, and XP. Using HyperTerminal with the DS89C4xO

Assuming that your serial cable has a D8-9 connector on both ends, we take the following steps to establish communication between the DS89C4xO Trainer and HyperTerminaJ. I. With the trainer's power off, connect the COM I port on the back of your PC to one end of the serial cable. 2. The other end of the serial cable is connected to the D8-9 connection on the DS89C4xO Trainer designated as SERIAL#O. After you connect your DS89C420 Trainer to your PC, power up the trainer. Set the switch to the program position. 3. In Windows Accessories, click on HyperTerminaJ. (If you get a modem installation option, choose "No'") 4. Type a name, and click OK (or HyperTerminal will not let you go on). 5. For "Connect Using" select COM I and click OK. Choose COM2 if COM 1 IS used by the mouse. 6. Pick 9600 baud rate, 8-bit data, no parity bit, and I stop bit. 7. Change the "Flow Control" to NONE or Xon/Xoff, and elick OK, (Definitely do not choose the hardware option.) 8. Now you are in Windows HyperTerminal, and when you press the ENTER key a couple of times, the DS89C4xO will respond with the following message: DS89C420 LOADER VERSION 1.0 COPYRIGHT (C) 2000 DALLAS SEMICONDUCTOR>

---=r..-r~;;;,~"'-----_. DS89C420

>

FIgure 8-7.

228

LOADER

VERSION

1.0

COPYRIGHT

.

_101 xl

.__

(Ci 2000 DALLAS SEMICONDUCTOR

Screen Capture from HyperTerminal for DS89C4xO Trainer

"

If you do not see ">" after pressing the ENTER key several times, go through the above steps one more time. Then, if you do not get ">", you need to check your hardware connections, such as the MAX232/233. See the end of this section for some troubleshooting tips.

Loading and running a program with the DS89C4xO Trainer After we get the ">" from the DS89C4xO, we are ready to load the program into it and run. First, make sure that the file you are loading is in Intel hex format. The Intel hex format is provided by your 8051 assembler/compiler. More about Intel hex format is given in the next section.

Erase command for the DS89C4xO To reload the DS89C4xO chip with another program, we first need to erase its contents. The K (Klean) command will erase the entire contents of the flash ROM of the chip. Remember that you must use the ">K" command to erase the ROM before you can reload any program. You can verify the operation of the ">K" command by using the Dump command to display ROM contents on screen. You should see all FFs in all the locations of ROM after applying the ">K" command. Go to www.MicroDigitalEd.com to see the above steps presented with screen shots.

Loading the program After making sure that you have the switch on the program positionand you have the ">" prompt on your screen, go through the following steps to load a program: I. 2. 3. 4.

At the ">" prompt, enter L (L is for Load). Example: ">L" an~ pr~s~ En~ri In HyperTerminal, click on the Transfer m~,nu option. ,~IIck on en ext I e. Select your file from your disk. Example: C:test.hex h "GGGG " t Wait until the loading is complete. The appearance of t e > promp indicates that the loading is good and finished. 5. Now use D to dump the contents of the flash ROM of the DS89C4xO onto the screen Example: >D 00 4F . .. . '11' the opcodes and operands of all the mstrucnons m The dump WI gIve you . . . . id Y, mpare this information with the information provt your program' ou Icanthcoext section we will examine the Intel hex file and ed by the list lilI e. n en, compare it with the list file of the test program.

T

CHAPTER 8: 8051 HARWARE CONNEC

nON AND INTEL HEX FILE .

229

Running the program Change the switch to the run position, press the reset button on the DS89C4xO system, and the program will execute. Use a logic probe (or scope) to see the PO, Pl, and P2 bits toggle "on" and "off' continuously with some delay in between the "ON" and "OFF" states.

Test program for the DS89C4xO in Assembly and C To test your DS89C4xO hardware connection, we can run a simple test in which all the bits of PO, PI, and P2 toggle continuously with some delay inbetween the "on" and "off" states. The programs for testing the trainer in both Assembly and C are provided below. Notice that the time delay is for a DS89C4xO based on the 11.0592 MHz crystal frequency. This time delay must be modified for the AT89C5J152 chips since DS89C4xO uses a machine cycle of I clock period instead of the 12 clock periods used by the AT89C51/52 chip. Trainer Test Program in Assembly

ORG OH MOV PO, #55H .MOV PI, #55H MOV P2, #55H MOV R5, #250 ACALL MSDELAY MOV PO, #OAAH MOV PI, #OAAH MOV P2, #OAAH MOV R5, #250 ACALL MSDELAY SJMP MAIN ;--------- 250 MILLISECOND DELAY MSDELAY: HERE3: MOV R4, #35 HERE2: MOV R3, #79 HEREI: DJNZ R3, HERE I DJNZ R4, HERE2 DJNZ R5, HERE3 RET END MAIN MAIN:

_

Trainer Test Program in C

#include void MSDelay(unsigned int); void main (void) { while (I) !/repeat forever { PO:OX55; //send value to port PhOX55 r.

P2:0x55'r MSDelay(250) ; PO : OxAA', Pl : OxAA', P2 : OxAA', MSDelay(250) ;

Ilcall 250 ms function value to port

Iiset

Ilcall 250 ms function

} void MSDelay(unsigned

int itime)

(

unsigned int i , J'., for(i:O;i0-------, fIT!

----:,~.=---__ tI

Edge-triggered

lEI (lCONJ)

0013

Figure 11-4. Activation of INTO and INTI

External interrupts INTO and INT1 There are only two external hardware interrupts in the 805 I: INTO and INTI. They are located on pins P3.2 and P3.3 of port 3, respectively. The interrupt vector table locations 0003H and OOl3H arc set aside for INTO and INTI, respectively. As mentioned in Section II, I, they arc enabled and disabled using the IE register. How are they activated? There are two types of activation for the extemal hardware interrupts: (I) level triggered, and (2) edge triggered. Let's look at each one, First, we sec how the leVel-triggered interrupt works.

Level-triggered interrupt In the level-triggered mode, INTO and INT I pins arc normally high (just like alil/O port pins) and if a low-level signal is applied to them, it triggers the Interrupt Then the mierocontroller stops whatever it is doing and jumps to the mterrupt vector table to service that interrupt. This is called a level-triggered or level-actIvated mterrupt and is the default mode upon reset of the 8051. The lowlevel signal at the INT pin must be remOved before the execution of the last mstruetlOn of the interrupt service routine, RET!; otherwise another interrupt will be generated. In other wo d if hi' '. . before the ISR ' s fi ' h d i r. s,. I t e ow-levet Interrupt signal IS not removed I II11S e It IS mterpreted as another interrupt and the 8051 jumps to the vector table to execute the ISR agai L k E In. 00 at -xample 11-5,

326

--

-

-c

Example ll-S Assume that the INTI pin is co d . goes low, it should tum on an L~~ct;h t~ a switch that is normally high. Whenever it When it is turned on it should 'I . ~e ED IS connected to P 1.3 and is normally off . dIs ay on ror a fraction f d . IS presse ow, the LED should stay on. . a a secon . As long as the switch Solution: ORG

LJMP ;--ISR

OOOOH MAIN

for hardware ORG

SETB

;bypass interrupt vector table interrupt INTI to turn on the LED

OOUH PI.3 R3.#255 R3. BACK

;INTI ISR

;turn on LED ;load counter BACK: DJNZ ;keep LED on for a while CLR PI. 3 ;turn off the LED RETI . . . ;return from ISR ;--MAIN program for lnltlalization MOV

ORG

MAIN:

MOV

HERE:

SJMP END

30H IE.#IOOOOIOOB. HERE

;enable external INTI ;stay here until interrupted

Pressing the switch will tum the LED on. If' It is kept activated, the LED stays on.

"cc

f l-

8051 to

P1.3

LED

INTI

In this program, the microcontroller is looping continuously in the HERE loop. Whenever the switch on INTI (pin P3.3) is activated, the microcontroller gets out of the loop and jumps to vector location OOI3H. The ISR for INTI turns on the LED, keeps it on for a while, and turns it offbcforc it returns. Ifby the time it executes the RET! instruction, the INTI pin is still low, the microcontrollcr initiates the interrupt again. Therefore, to end this problem, the INT I pin must be brought ba~k to high by the time RET! is executed.

CHAPTER

11: JNTERRUPTS

PROGRAMMING IN ASSEMBLY AND C

327

. level-triggered interrupt Sampling the low 110 less the INTO and INTI bits

d f normal un . Pins P3.2 and P33 arc use or dw, interrupts in the IE register are dAfter the har ware I . I in the IE registers are enable . . the INTn pin for a low-level signa once enabled the controlJer keeps sampling c turer's data sheet "the pin must be ' d' to one manurac . b roug h t each machine cycle. Accor mg . f!SR If the INTn pin. IS . h rt f the execution o. . . held in a low state until testa 0 . flSR there will be no Inter.. h t rt of the execution 0 . back to a logic high before t e sa. t due to the low level, It must be tivation of the mterrup . rupt." However, upon ae . n of RET!. Again, according to one manbrought back to high before the executio I ft t logic low after the RETl instruc's d h t "If the INTn pm IS e a a . . ufacturer s ata s eet,h . t rrupt WI'11 be ae t'IVated after one instruction IS execut-. tion of the ISR, anot er me. . f the hardware interrupt at the INTn pin, cd." Therefore, to ensure the aetlva:~~~el signal is around 4 machine cycles, but make sure ~~~: t~se:~;at~O~~ff:~~ :~at the level-triggered

interrupt is not latched.

;~~~~~~. pin must be held in a low state until the start of the ISR execution. I MC

../

.. 085

1.

11s

4 machine cycles -----------4 x 1.085 us

Note.

to INTO or INTI pins

On RESET, ITO (TCON.O) and ITI (TCON.2) are both low, making external interrupts level-triggered.

Figure 11-5. Minimum Duration of the Low Level-Triggered (XTAL = 11.0592 MHz)

Edge-triggered

Interrupt

interrupts

As stated before, Upon reset the 8051 makes INTO and INT I low-level triggered interrupts. To make them edge-triggered interrupts, we must program the bits of the TCON register. The TCON register holds, among other bits, the ITO and IT I flag bits that determine level- or edge-triggcred mode of the hardware interrupts. ITO and IT] are bits DO and 02 of the TCON register, respectively. They are also referred to as TCON.O and TCON.2 since the TCON register is bitaddressable. Upon reset, TCON.O (ITO) and TCON.2 (lTI) are both Os, meaning that the external hardware interrupts of INTO and INT I pins are low-level triggercd. By making the TCON.O and TCON.2 bits high with instructions such as "SETB TCON. 0" and "SETB TCON. 2", the external hardware interrupts of INTO and INT] become edge-triggered. For example, the instruction "SETB CON. 2" makes INTI what is called an edge-triggered interrupt, in which, when a high-to-Iow signal is applied to pin P3.3, in this case, the controller will be interrupted and forced to jump to location 00 13H in the vector table to service the ISR (assuming that the interrupt bit is enabled in the IE register).

328

-

D7 l....-.TF_I_I

I

TRI

TFO

I

TRO

I

lEI

ITI

lEO

I

ITO

TFI

TCON.7

Timer I overflow flago Set b y hardware when timer/counter ' 1 overflows Cleared b h 'd . . .. . Y at ware as the processor vectors to the interrupt service routine.

TRI

TCON.6

Timer I run control bit. Set/cleared by software to turn timer/counter lon/off.

TFO·

TCON.S

Timer a overflow flag. Set by hardware when timer/counter overflows. Cleared by hardware as the processor vectors to the service routine.

TRO

TCONA

Timer 0 run control bit. Set/cleared by software to turn timer/counter a on/off.

IEl

TCON.3

External interrupt I edge flag. Set by CPU when the external interrupt edge (H-to-L transition) is detected. Cleared by CPU when the interrupt is processed. Note: This flag does not latch low-level triggered interrupts.

ITt

TCON.2

Interrupt I type control bit. Set/cleared by software to specify falling edge/low-level triggered external interrupt.

lEO

TCON.I

Externalinterrupt a edge flag. Set by CPU when external interrupt (H-to-L transition) edge is detected. Cleared by CPU when interrupt is processed. Note: This flag does not latch low-level triggered interrupts.

ITO

TCON.O

d

Interrupt a type control bit. Set/cleared by software to specify falling edge/low-level triggered external interrupt.

Figure 11-6. TCON (Timer/Counter)

Register (Bit-addressable)

Look at Example I J -6. Notice that the only difference between this program and the program in Example 11-5 is in the first line of MAIN where the instruction "SETB TCON. 2" makes INTI an edge-triggered interrupt. When the falling edge of the signal is applied to pin INT 1, the LED will be turned on momentarily. The LED's on-state duration depends 011 the time delay inside the ISR for INTI. To tum on the, LED again, another high-to-low pulse must be applied to pin 3.3. This is the opposite of Example 11-5. In Example 11-5, duc to the level-triggered nature of the interrupt, as long as INTI is kept at a low level, the LED is kept in the on state. But in this example, to tum 011 the LED again, the INTI pulse must be brought back high and then forced low to create a falling edge to activate the interrupt. CHAPTER

]1:

INTERRUPTS

PROGRAMMING IN ASSEMBLY AND C

329

Example 11-6 ulse generator, write a program in ing that pin 3.3 (INTI) is connected t~ :i Phto Pl.3, which is connected to an s: Iling edge of the pulse sendIS tumegd on and off at the same rate as the Assuhmh whic tne ra d hwillLED ED ( buzzer). In other war s, t e.. dge-triggered version of Example 11-5. L or pulses are applied to the IN T 1 p.in ThIS IS an e Solution: ORG OOOOH LJMP MAIN ,'--ISR for hardware ORG

interrupt

0013H

INTI to turn on the . INTI ISR ,:turn on the LED

SETB PI. 3 MOV R3,#255 BACK: DJNZ R3,BACK ,keep the LED on for CLR PI. 3 ·turn off the LED RETI ,:return from ISR ;--MAIN program for ini tialization ORG

LED

a while

30H

MAIN: SETB TCON.2 MOV IE,#IOOOOIOOB HERE: SJMP HERE END

'make INTI edge-trigger interrupt :enable External INTI ;stay here until interrupted

Sampling the edge-triggered interrupt Before ending this section, we need to answer the question of how often the cdge-triggered interrupt is sampled. In edge-tnggere . d interrup . ts, the external source must be held high for at least one mach inc cycle, and then held low for at least one machine cycle to ensure that thc transition is seen by the mieroeontroller. Minimumpulse duration to detect edge-triggeredinterrupts. XTAL ~ 11.0592 MHz

..

I

MC

1.085 IJS

...

1.085 IJS I

MC

The falling edge is latched by the 8051 and is held by the TCON register. The 1TCON.I and TCON.3 bits hold the latched falling edge of pins I TO and INT , respectively. TCON.I and TCON.3 arc also cal led IEOand IE I, re pectiveIy, as shown in Figurc 11-6. They function as interrupt-in-service flags. When an intenupt-in-service flag is raised, it indicates to the external world that the interrupt is bcing serviced and no new interrupt on this INTn pin will be responded to until this scrviee is finished. This is just like the busy signal you get if calling a telephone number that is in use. Regarding the ITOand ITI bits in the ICON register, the following two points must be emphasized. 330

-

1. The first point is that when the ISRs are finished (that is, upon execution of instruction RET!), these bits (TCON.l and TCONJ) are cleared, indicating that the mterrupt is finished and the 8051 is ready to respond to another interrupt on that pin. For another interrupt to be recognized, the pin must go back to a lOgIC high state and be brought back low to be considered an edge-triggered interrupt. 2. The second point is that while the interrupt service routine is being executed, the TNTn pin is ignored, no matter how many times it makes a high-to-low transition. In reality one of the functions of the RET! instruction is to clear the corresponding bit in the TCON register (TCON.I or TCON.3). This informs us that the service routine is no longer in progress and has finished being serviced. For this reason, TCON.I and TCONJ in the TCON register are called interrupt-in-service flags. The interrupt-in-service flag goes high whenever a falling edge is detected at the !NT pin, and stays high during the entire execution of the [SR. It is only cleared by RETI, the last instruction of the ISR. Because of this, there is no need for an instruction such as "CLR TCON. 1" (or "CLR TCON. 3" for INT I) before the RET! in the ISR associated with the hardware interrupt INTO. As we will see in the next section, this is not the case for the serial interrupt.

Example 11-7 What is the difference between the RET and RET! instructions? not use RET instead of RET! as the last instruction of an ISR.

Explain why we can-

Solution: Both perform the same actions of popping off the top two bytes of the stack into the program counter, and making the 8051 return to where it left off. However, RETI also performs an additional task of clearing the interrupt-in-service flag, indicating that the servicing of the interrupt is over and the 8051 now can accept a new interrupt on that pin. If you use RET instead of RET! as the last instruction of the interrupt service rounne, you simply block any new interrupt on that pin after the first interrupt, smce the pm status would indicate that the interrupt is still being serviced. In the cases of TFO, TF I, TCON.I, and TCONJ, they are cleared by the execution of RET!.

More about tile TeON register Next we look at the TCON register more closely to understand its role in handling interrupts. Figure 11-6 shows the bits of the TCON register. ITO and IT1

TCON.O and TCON.2 are referred to as ITO and IT I, respectively. These . I I I edge-triggered modes of the external hardware intertwo bits set the ow- eve or . I ins They are both 0 upon reset, which makes them TNT rupts of the INTO an d pl. . hi h k h . d The ro ammer can make either of them tg to rna etc low-level tnggere .. Pt ~ e triggered In a given system based on the 8051, external hardware mterru Ph e g '~Inot be aitercd again since the designer has fixed once they are set to 0 or l t ey WI . d the interrupt as either edge- or level-tnggere .

CHAPTER

11: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C

331

lEO and IE1

TCON.I and TCON.3 are referred to as lEO and lEI, respectively. These bits are used by the 8051 to keep track of the edge-trIggercd. Interrupt only. In other words, if the ITOand ITI are 0, meaning that the hardware interrupts are low-level triggered, lEO and lEI are not used at all. The lEO and IE I bits are used by the 8051 only to latch the high-to-low edge transition on the INTO and INT I Pins. Upon the edge transition pulse on the INTO (or INT I) pin, the 805 I marks (sets high) the lEx bit in the TCON register, jumps to the vector in the interrupt vector table, and starts to execute the ISR. While it is executing the ISR, no H-to-L pulse transition on the fNTO (or INTI) is recognized, thereby preventing any interrupt inside the interrupt. Only the exeeution of the RET! instruction at the end of the ISR will clear the lEx bit, indicating that a new H-to-L pulse will activate the interrupt again. From this discussion we can see that the lEO and IE I bits are used internally by the 805 I to indieate whether or not an interrupt is in use. In other words, the programmer is not concerned with these bits since they are solely for internal use. TROand TR1

These are the D4 (TCON.4) and 06 (TCON.6) bits of the TCON register. We were Introduced to these bits in Chapter 9. They are used to start or stop timers o and I, respectively. Although we have used syntax such as "SETB TRx" and "CLR Trx", we could have used instructions such as "SETB TeON. 4" and "CLR TCON. 4" since TCON is a bit-addressable register. TFO and TF1

These are the 05 (TCON.5) and 07 (TeON.7) bits of the TCON register. We were Introduced to these bits m Chapter 9. They are used by timers 0 and I, respect~~ely, to mdicate If the urner has rolled over. Although we have used the syntax ~NB TFx, target" and "CLR Trx", we could have used instructions such as JNB TCON. 5, target" and "CLR TCON 5'" TCON' bi addressablc. . SInce IS It-

Review Questions I. True or false There is as'

2. 3.

4. 5. 6. 7.

I . . . to both exte~al hardwar mgte mterruITPtIn the Interrupt vector table assigned . e m errupts 0 and IT I Wh at address In the interru t t ble i .' about thee ni p vee Pin num bers on port 3? or ta e ISassigned to INTO and INTI? . How Which bit of IE belongs to th' Ih are enabled. e extema ardware interrupts? Show how both Assume that the IE bit for the exrerna] h d . is active low. Explain how this' t ar ware Interrupt EX I is enabled and True or false. Upon reset the ~:~erruPt works When it is activated. gered. 'mal hardware mterrupt is low-level trigIn Question 5, how do we make sure that a'. . as multIple mterrupts? single Interrupt IS not recognized True or false. The last two instructions of the ISR for INTO CLR TCON.1 are: RETI

8. Explain the role that each of the t bi cution of external interrupt O. wo Its TCON.O and TCON.2 play in the exe332

SECTION 11.4: PROGRAMMING THE SERIAL COMMUNICATION INTERRUPT In Chapter LOwe studied the serial communication of the 8051. All examples in that chapter used the polling method. In this section we explore interruptbased serial communication, whieh allows the 8051 to do. many things, in addition to sending and receiving data from the serial communication port.

RI and TI flags and interrupts As you may recall from Chapter 10, TI (transfer interrupt) is raised when the Lastbit of the framed data, the stop bit, is transferred, indicating that the SBUF register is ready to transfer the next byte. RI (received interrupt), is raised when the entire frame of data, including the stop bit, is received. In other words, when the SBUF register has a byte, RI is raised to indicate that the received byte needs to be picked up before it is lost (overrun) by new incoming serial data. As far as serial communication is concerned, all the above concepts apply equally when using either polling or an interrupt. The only difference is in how the serial communication 'needs are served. In the polling method, we wait for the flag (TI or RJ) to be raised; while we wait we cannot do anything else. In the interrupt method, we are notified when the 8051 has reeeived a byte, or is ready to send the next byte; we can do other things while the serial communication needs are served. In the 805L only one interrupt is set aside for serial communication. This interrupt is used to both send and receive data. If the interrupt bit in the IE register ([E.4) is enabled, when RI or TI is raised the 8051 gets interrupted and jumps to memory address location 0023H to execute the ISR. In that ISR we must examine the TI and RI flags to see which one caused the interrupt and respond accordingly. See Example 11-8.

~: Dl------

0023H

Serial interrupt is invokedby Tl or RI flags

Figure 11-7. Single Interrupt for Both TI and RI

Use of serial COM in the 8051 .' f plications, the serial interrupt is used mainly for In the vast majority 0 .d s: sending data serially. This is like receiving a .. d ta d IS never lise lor recervmg a an d' to be notified. If we need to make a phone II here we nee a nng . . . I h te ep one ca , w emind ourselves and so no need for nnging. In rcceivcall there are other ways to r ond immediately no matter what we are . II h ver we must resp . . mg the phone ca , owe,S' ilarly we lISC the serial interrupt to recervc doing or we will miss th.e c~I;~s/~~Ok ;t Example 11-9. incoming data so that It IS no . CHAPTER

11: INTERRUPTS

PROGRA

MMING IN ASSEMBLY AND C

333

Example Jl-8 fr m PI and writes it to P2 continuously . h h 8051 reads data 0 . II A h W n.te a ..program in whic e senal . CO M po rt to be transferred sena y. ssume t at f it t t the while grving a copy 0 IS 0 h baud rate at 9600. XTAL ~ 11.0592 MHz. et t e Solution:

MAIN:

BACK:

ORG o LJMP MAIN ORG 23H LJMP SERIAL ORG 30H MOV Pl,#OFFH MOV TMOD,#20H MOV THl,#OFDH MOV SCON,#50H MOV IE,#lOOlOOOOB SETB TRI MOV A, Pl MOV SBUF,A MOV P2,A SJMP BACK

;jump to serial

interrupt

ISR

'make PI an input port

,:timer 1, mode 2 (auto-reload) .9600 baud rate ;a-bit, 1 stop, REN enabled ,'enable serial interrupt ;start timer 1 ,'read data from port 1 ;give a copy to SBUF ;send it to P2 ;stay in loop indefinitely

, ,·------------------Serial Port ISR ORG lOOH SERIAT,: JB TI,TRANS ;jump if TI is high MOV A,SBUF r'otherwise due to receive CLR RI ;clear RI since CPU does not RETI ;return from ISR TRANS: CLR TI ;clear TI since CPU does not RETI ;return from ISR END

In the above program notice the role of TI and RJ. The moment a byte is written into SBUF it is framed and transferred serially. As a result, when the last bit (stop bit) is transferred the TI is raised, which causes the serial interrupt to be invoked since the corresponding bit in the IE register is high. In the serial ISR, we check for both TJ and RJ since both could have invoked the interrupt. In other words, there is only one interrupt for both transmit and receive.

Clearing RI and TI before the RETI instruction . Notice in Example 11-9 that the last instruction before the RET] is the cleating afthe Rl or TI flag Thi . . . . fi . S. IS ISnecessary Smce there ISonly one mterrupt or both receive and transmit a d th 8051 d . It'. ISthe Job ., of the ISR t nI eI fl oes not know. Who generated It.'. therefore, . mterrupts Where It'. ISthe'0 c bearf t ie h 80ago Contrast this with the external and timer . JO 0 t e 51 to clear the interrupt flags. By contrast,

334

-

Example 11-9 Write a program in which th 8051 hile J e gets data from PI and sends it to P2 continuously w 1 e incoming data from th . I . e senai port IS sent to PO. Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600. Solution:

i

ORG 0 LJMP MAIN ORG 23H LJMP SERIAL ;jump to serial ISR ORG 30H MAIN: MOV PI, #OFFH ;make PI an input port MOV TMOD,#20H ;timer 1, mode 2 (auto-reload) MOV THl,#OFDH ; 9600 baud rate MOV SCON,#50H ;8-bit,1 stop, REN enabled MOV IE, #10010000B ;enable serial interrupt SETB TRI ;start Timer 1 BACK: MOV A,PI ;read data from port 1 MOV P2,A ;send it to P2 SJMP BACK ;stay in loop indefinitely ;------------------SERIAL PORT ISR ORG 100H SERIAL: JB TI r TRANS ;jump if TI is high MOV A,SBUF ;otherwise due to receive MOV PO,A ;send incoming data to PO .CLR RI ;clear RI since CPU doesn't RETI ;return from ISR TRANS: CLR' TI ;clear TI since CPU doesn't ;return from ISR RETI END

,

in serial communication the RI (or TI) must be cleared by the programmer using software instructions such as "CLR TI" and "CLR RI" in the ISR. See Example 11-10. Notice that the last two instructions of the ISR are clearing the flag, followed by RET!. Before finishing this section notice the list of all interrupt flags given in Table 11-2. While the Table 11-2: Interrupt Flag Bits for the 8051152 TCON register holds four of the Interrupt flags, in the 8051 the SCON register has the RI and TI flags.

Interrupt External 0 External I Timer 0 Timer I

Flag lEO lEI TFO TFI

SFR Register Bit TCON.I TCONJ TCON.5 TCON.7

Serial port Timer 2 Timer 2

Tl TF2 EXF2

SCON.I T2CON.7 (AT89C52) T2CON.6 (AT89C52)

CHAPTER 11: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C

335

Example II-tO

.

.. mterrup tsdtoit do the following: Write a program usmg t PO ( a) Receive data serially and sen. I 0 : lly and a copy given to P2, ( d b) Have port P I rea and transmitted sena f 5, kHz frequency on PO...I t a square wave 0 (c) Make Timer 0 g~era e 2 MHz. Set the baud rate at 4800. Assume that XTAL - 11.059 Solution:

MAIN:

BACK:

ORG o LJMP MAIN ORG OOOBH CPL PO.1 RETI ORG 2JH LJMP SERIAL ORG JOH MOV P1,#OFFH MOV TMOD,#22H MOV TH1,#OF6H MOV SCON,#50H MOV THO,#-92 MOV IE,#10010010B SETB TR1 SETB TRO MOV A,P1 MOV SBUF,A MOV P2,A SJMP BACK

,·------------------SERIAL ORG 100H SERIAL: JB TI,TRANS MOV A,SBUF MOV PO,A CLR RI RETI TRANS: CLR TI RET I END

,.ISR for Timer 0 ;toggle PO. 1 ,'return from ISR ;jump to serial into ISR 'make PI an input port ;timer O&l,mode 2, auto-reload '4800 baud rate ;8-bit, 1 stop, REN enabled ;for 5 KHz wave ,'enable serial, timer 0 into ;start timer 1 ;start timer 0 ,'read data from port 1 ;give a copy to SBUF ;write it to P2 ;stay in loop indefinitely I

PORT ISR ;jump if TI is high ;otherwise due to received .send serial data to PO ;clear RI since CPU does not ;return from ISR ;clear TI since CPU does ;return from ISR

Review Questions I. True or false. There is a single interrupt in the interrupt vector table assigned to both the TI and RI interrupts. 2. What address in the interrupt Vector table is assigned to the serial interrupt? 3. enabled. Which bit of the IE register belongs to the serial interrupt? Show how it is 4. Assume that the IE bit for the serial interrupt is enabled. Explain how this interrupt gets activated and also explain its actions upon activation. 336

not

5. True or false. Upon reset the seri I . . 6. True or false The 1 ' . a Interrupt IS active and ready to go . ast two Instructions . 0 f th e ISR i:tor the receive ..' CLR RI Interrupt are: RETI

7. Answer Question 6 for the send interrupt.

SECTION 11.5: INTERRUPT PRIORITY IN THE 8051/52 The next topic that we must de I WIt.h . activated at the same time? Who h t~h IS what happens if two interrupts arc t Interrupt priority is the main to IC fOd ese two Interrupts is responded to first? pic 0 ISCUSSlOnIn this section.

Interrupt priority upon reset WhenF the T8051 .. . are assigned . Table 11-3 bl is powered up, th . e priorities according to ru ts 0 and' 1 rom a e 11-3 we see, for example, that if external hardware interp are activated at the same time, external interrupt 0 (INTO) . . d ed to first. Only after INTO IS respon has been serviced is INTI Table 1]-3: 8051152 Interrupt Priority Upon Reset' serviced, since INT I has the lower priority. In reality, the priority scheme in the table is nothing but an internal polling sequence

Highest to Lowest Priority ~Etxt:ern:7.al:;I::n=te=rru7P~t~0~ __ ...:(~IN~T!!.0)L ~T:7im;:e::r:;:[n'f:t;:erru2P::t=0:7 ~(T~F~0~) ,..External Interrupt I (INTI) ~T~im:e=r~I=nt=erru=p~t~I~---"':(~T~F~I!..) L

in which the 8051 polls the ~S:i:er=ia::I::.:C~o;;;mm~~u~n::ic::;atsio::.n~ __ ~(R~I~+:""T~I~) __ --interrupts in the sequence .;;.T,;;;;im;;;.e;;,;r..;2;.;(o;;8.;;;05;.;2:..0;;.:n:.:.IYrl.i.):..... __ T.:.F~2=-

_ _

_ _

listed in Table 11-3, and responds accordingly.

Example

11-11

Discuss what happens if interrupts INTO, TFO, and INTI are activated at the same time. Assume priority levels were set by the power-up reset and that the external hardware interrupts

are edge-triggered.

Solution: If these three interrupts are activated at the same time, they are latched and kept internally. Then the 8051 checks all five interrupts according to the sequence listed in Table 11-3. If any is activated, it services it in sequence. Therefore, when the above three interrupts are activated, lEO (external interrupt 0) is serviced first, then Timer 0 (TFO), and finally IEI (external interrupt I).

CHAPTER

J I: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C

337

DO

D7

,--_I

I PT2 1 PS

I

PTI

I

PXI

I

PTO

IL-_PX_O_

. pnonty. .. .. bit = 0 assigns low priority. Priority bit = I assigns high Priority fP.7 1P.6 PT2

IP.5

PS

IPA

PTI

fP.3 IP.2 fP.1 /P.O

PXI PTO PXO

Reserved Reserved Timer 2 interruptpriority bit (8052 only) Serial port interruptpriority bit Timer I interrupt priority bit External interrupt f priority bit Timer 0 interruptpriority bit External interrupt 0 priority bit

User software should never write fs to unimplemented bits, since they may be used in future products. Figure /1-8. Interrupt Priority Register (Bit-addressable)

Setting interrupt priority with the IP register We can alter the sequence of Table 11-3 by assigning a higher priority to anyone of the interrupts. This is done by programming a register called IP (interrupt priority). Figure 11-8 shows the bits of the IP register. Upon power-up reset, the IP register contains aliOs, making the priority sequence based on Table 11-3. To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high. Look at Example 11-12. Example 1I-12 (a) Program the IP register to assign the highest priority to INTI (external interrupt I), then (b) discuss what happens if INTO, INTI, and TFO are activated at the same time. Assume that the interrupts are both edge-triggered. Solution: (a) MOVIP,#OOOOOIOOB

Theis instruction "SETB IP bit-addressable.

;IP.2=1 IP.

to assign

INTI

higher

priority

2" also will do the same thing as the above line since

(b) The instruction in Step (a) assigned a higher priority to INTI than the others; therefore,. when INTO, INTI, and TFO interrupts are activated at the same time , the 8051 servtces INT I first, then it services INTO, then TFO. This is due to the fact that INTI has a higher priority than the other two because of the instruction in Step (a). The instructIOn In Step (a) makes both the INTO and TFO bits in the IP register 0. As a result, the sequence In Table 11-3 is followed, which gives a higher priority to INTO overTFO. .

338

CI

Example 11-13

Assume

"MOV IP

that

after reset

#00001100~"

. d" Ice.

th

. '" e. Interrupt .pnonty IS set by the instruction . DISCUSSthe sequence in which the interrupts are serv.

Solution:

The instruction . "MOV IP ',OB #0000110 "(B' ISfor binary) . sets the external interrupt 1 (TNT I) and Timer 1 (TF I) to a higher priority level compared with the rest of the interrupts, However, smce they are polled according to Table 11-3 ' th ey WI'11 h ave teo h fi I. .. Iowing pnonty. Highest Priority

Lowest Priority

External Interrupt 1 Timer Interrupt 1 External Interrupt 0 Timer Ioterrupt 0 Serial Communication

(INTI) (TFI) (INTO)

(TFO) (RI

+ II)

Another point that needs to be clarified is the interrupt priority when two or more interrupt bits in the IP register are set to high. In this case, while these interrupts have a higher priority than others, they are serviced according to the sequence of Table 11-3. See Example 11-13.

Interrupt inside an interrupt What happens if the 8051 is executing anlSR belonging to an interrupt and another interrupt is activated? In such cases, a high-priority interrupt can interrupt a low-priority interrupt. This is an interrupt inside an interrupt. In the 8051 a lowpriority interrupt can be interrupted by a higher-priority interrupt, but not by another low-priority interrupt. Although all the interrupts are latched and kept internally, no low-priority interrupt can get the immediate attention of the CPU unti I the 8051 has finished servicing the high-priority interrupts,

Triggering the interrupt by software There are times when we need to test an ISR by way of simulation. This can be done with simple instructions to set the interrupts high and thereby cause the 8051 to jump to the interrupt vector table. For example, if the IE bit for Timer 1 is set, an instruction such as "SETB TF1" will interrupt the 8051 III whatever it is doing and force it to jump to the interrupt vector table. In other words, ~e do not need to wait for Timer 1 to roll over to have an interrupt. We can cause an interrupt with an instruction that raises the interrupt flag.

CHAPTER

11: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C

339

Review Questions 2.I. 3.

4. 5.

True or false. Upon reset, all interrupts have the same priority . . keeps tra ck of interrupt priority in the 805 I? Is It a bit-address. What register able register? . . . . Which bit of IP belongs to the serial interrupt priority? Show how to assign It the highest priority. '. Assume that the IP register contains all Os. Explain what happens If both INTO and INTI are activated at the same time. Explain what happens if a higber-priority interrupt is activated while the 8051 is serving a lower-priority interrupt (that is, cxecunng a lower-pnonty ISR).

SECTION 11.6: INTERRUPT PROGRAMMING

IN C

So far all the programs in this chapter have been written in Assembly. In this section we show how to program the 8051/52's interrupts in 805 J C language. In reading this section, it is assumed that you already know the material in the first two sections of this chapter.

8051 C interrupt numbers The 8051 C compilers have extensive support for the 805 J interrupts with two major features as follows: I. They assign a unique number to each of the 8051 interrupts as shown in Table

11-4.

,

2. It can also assign a register bank to an ISR. This avoids code overhead due to the pushes and pops of the RO - R7 registers.

Table 11-4: 8051152 Interrupt Numbers in C Interru t Externallntemlpt 0 Timer Interrupt 0 External Interrupt I TImer Interrupt I Senal Communication Timer 2 (8052 only)

Name (INTO) (TFO) (INTI) (TF 1) (Rl + TI) (TF2) I

Example 11-14 shows how

340

Numbers used b 805] C 0 I

2 3 4 5

. I' . a Simp e Interrupt IS written in 8051 C.

Example 11-14 Write a C program that continuously gets a single bit of data from Pl.? and sends it to PI.O, while simultaneously creating a square wave of 200 us period on pin P2.5. Use timer 0 to create the square wave. Assume that XTAL = 11.0592 MHz.

Solution: We will use timer 0 in mode 2 (auto-reload). One half of the period is 100 us. 100 II. 085 us = 92, and THO = 256 - 92 = 164 or A4H #include

sbit SW sbit IND sbit WAVE

= PI ?; ::;: Pl Oi ::;: P2 Si

void timerO(void) {

interrupt 1

= -WAVE;

WAVE

Iitoggle pin

} void main () { SW = 1; = Ox02;

TMOD

THO

Ilmake switch input

=

liTHO = -92 lienable interrupts for timer 0

OxA4;

= OX82;

IE

while (1) { IND = SW;

Iisend switch to LED

}

200 us I 2

=

100 us

100 us I 1.085 us

= 92

8051 Pl.0

SWITCH

---1

LED

5000 Hz

Pl.7 P2.5

CHAPTERll:fNTERRUPTSPROGRAM

MING IN ASSEMBLY AND C

341

Example ll-IS Write a C program that continuously gets a single bit of data from PI. 7 and sends it t-;; PI ,0 in the main, while simultaneously (a) creating a square wave of 200 IlS period on pin P2.5, and (b) sending letter 'A' to the serial port. Usc Timer 0 to create the square wave, Assume that XTAL = 11.0592 MHz. Usc the 9600 baud rate. Solution: We will use Timer 0 in mode 2 (auto-reload), THO = 100/1.085 IlS = -92, which is A4H #include sbit SW sbit IND sbit WAVE

PI

=

Ai;

PIAOi A

= P2 S i

void timerO(void) interrupt 1 { WAVE

=

-WAVE;

}

Iitoggle pin

void serialO() interrupt 4

==

H(TI

1)

{ SBUF = 'A'; TI = 0;

Iisend A to serial port Ilclear interrupt

RIO;

Ilclear interrupt

} else { )

void main () { SW = 1; = -3.

THI

,

TMOD = Ox22. THO = OxA4" SCON = OXS~' TRO = 1. , '

Ilmake switch input 119600 baud Ilmode 2 for both t'lmers II -92=A4H for t i lmer 0

TRI = 1.,

IE

=

Ox92.

while(l) , { INn = SW; )

Iistart timer IIIenable interrUPt for

1 stay here

I I send swi t ch ta

TO LED

-

342

-

-

Cl

Example 11-16

Write a C program using interrupts to do the following: (a) Receive data serially and send it to PO, (b) Read port PI, transmit data serially, and give a copy to P2, (c) Make timer 0 generate a square wave of 5 kHz frequency on PO.J • Assume that XTAL = 11.0592 MHz. Set the baud rate at 4800. Solution: #include sbit WAVE = PO 1; A

void timerO() interrupt 1 { WAVE = -WAVE; } void serialO() if (TI

Iitoggle pin

interrupt 4

== 1)

{ = 0;

TI

Ilclear interrupt

} else { PO = SBUF;

RIO;

Ilput value on pins Ilclear interrupt

void main ()

{ unsigned

char x;

= OXFF; TMOD = Ox22; TH1 =' OXF6; PI

THO

OxSO;

=

SCON

= OxA4;

IE = OX92; TR1 = 1; TRO

1;

=

while {

Ilmake PI an input ~

114800 115

baud rate

kHz has T

= 200 uS

lienable interrupts

I I start timer 1 I I start timer 0

(1)

x

=

P'l : SliUF = x;

P2

=

x;

Ilread value from pins Ilput value in bUf~er Ilwrite value to pIns

CHAPTER 11: INTERRUPTS PROGRA

MMING IN ASSEMBLY AND C

343

r Example 11-17 Write a C program using interrupts to do the following: (a) Generate a 10000 Hz frequency on P2.] using TO 8-bit auto-reload, (b) Use timer I as an event counter to count up a l-Hz pulse and display it on PO. The pulse is connected to EX I, Assume tbat XTAL = 11,0592 MHz. Set the baud rate at 9600. Solution: #include sbit WAVE; P2Al; unsigned char cnt; void timerO () interrupt 1 { WAVE;

Iitoggle pin

-WAVE;

} void timerl () interrupt 3 ( cnt++i

PO ~ cnt;

II increment counter Iidisplay value on pins

void main () cnt ; 0; TMOD ; OX42·, THO; OX-46', IE ; Ox86", TRO ~ 1; TRI ~ 1;

while(l);

I / 10000 Hz

=

Iiset counter to zero 1110000

Hz

lienable interrupts /Istart timer 0 I I start timer 1 Ilwait until interrupted

100 us

100 us / 2 = 50 IlS 50 IlS / 1.085 IlS = 46

8051

PO§

LEO.

P2.1 10000 Hz

-

-

CI

SUMMARY An interrupt is an external or internal event that interrupts the microcontroller to ' needss Its i service. Every ,interrupt has a program ... , inform " it that a de vice associated with It called the ISR, or interrupt service routine, The 8051 has 6 interrupts, 5 of which are user-accessible, The interrupts arc for reset: two for the timers, two for external hardware interrupts, and a serial communication interrupt. The 8052 has an additional interrupt for Timer 2, ,. The 8051 can be programmed to enable or disable an interrupt, and the mterrupt pnonty can be altered. This chapter showed how to program 8051/52 mterrupts 111 both Assembly and C languages,

PROBLEMS SECTION II, I: 8051 INTERRUPTS I. 2. 3. 4.

Which technique, interrupt or polling, avoids tying down the microcontroller? Including reset, how many interrupts does the 8051 have? In the 8051 what memory area is assigned to the interrupt vector table? True or false, The 8051 programmer cannot change the memory space assigned to the interrupt vector table. 5. What memory address in the interrupt vector table is assigned to INTO? 6. What memory address in the interrupt vector table is assigned to lNT I? 7. What memory address in the interrupt vector table is assigned to Timer O? 8. What memory address in the interrupt vector table is assigned to Timer I? 9. What memory address in the interrupt vector table is assigned to the serial COM interrupt? 10. Why do we put an LJMP instruction at address O? 11. What are the contents of the IE register upon reset, and what do these value mean? 12. Show the instruction to enable the EX I and Timer 1 interrupts. 13. Show the instruction to enable every interrupt of the 8051. 14. Which pin of the 8051 is assigned to the external hardware interrupts INTOand INTI? 15. How many bytes of address space in the interrupt vector table are assigned to the INTO and INT 1 interrupts? 16. How many bytes of address space in the interrupt vector table are assigned to the Timer 0 and Timer I interrupts? 17, To put the entire interrupt service routine in the interrupt vector table, it must be no more than bytes in size. 18. True or false. The IE register is not a bit-addressable register. 19. With a single instruction, show how to disable all the interrupts. 20. With a single instruction, show how to disable the EX I mterrupt. 21. True or false. Upon reset, all interrupts are enabled by the 8051. . 22. In the 8051, how many bytes of ROM space arc assigned to the reset Interrupt, and why?

CHAPTER 11: INTERRUPTS PROGRAMMJNG IN ASSEMBLY A DC

345

SECTION

11.2: PROGRAMMING

TIMER INTERRUPTS

23. True or false. For bot h T·imer 0 and Timer I , there is an interrupt assigned to it in the interrupt vector table. .. .? 24. What address in the interrupt vector table IS assigned to TUller I . . bit. 0 fIE bite ongs o. the Timer 0 Interrupt? Show how It 25. Which . .IS enabled. 26. Whic. h biIt 0fIE b e Iong s to the Timer I Interrupt? Show how It IS enabled. . 27. Assume that Timer 0 is programmed in mode 2, TH I FOH, and the IE bit for Timer 0 is enabled. Explain how the interrupt for the nrncr work . 28. True or false. The last two instructions of the ISR for Timer I arc:

='

CLR TFI RETI 29. Assume that Timer I is programmed for mode I, THO = FFH, TL I = F8H, and the IE bit for Timer I is enabled. Explain how the interrupt is activated. 30. If Timer I is programmed for interrupts in mode 2, explain when the interrupt is activated. 3 J. Write a program to create a square wave of T = 160 ms on pin P2.2 while at the same time the 8051 is sending out 55H and AAH to P I continuously. 32. Write a program in which every 2 seconds, the LED connected to P2.7 is turned on and off four times, while at the same time the 8051 is getting data from PI and sending it to PO continuously. Make sure the on and off states arc 50 ms in duration. SECTION 11.3: PROGRAMMING

EXTERNAL

HARDWARE

INTERRUPTS

33. True or false. A single interrupt is assigned to each of the external interrupts EXO and EX I.

hardware

34. What address in the interrupt vector table is assigned to INTO and INT I? How about the pin numbers on port 3'1 35. Which bit of IE belongs to the EXO interrupt? Show how it is enabled. 36. Which bit of IE belongs to the EX I interrupt? Show how it is enabled. 37. Show how to enable both external hardware interrupts. 38. Assume that the IE bit for external hardware interrupt EXO is enabled and is low-level tnggered, Explain how this interrupt works when it i activated. How can we make sure that a singl . t .. . . e 111 errupt IS not mterpretcd as multiple interrupts? 39. True or false Upon reset th t Ih d . .. , e ex erna ar ware Interrupt is edge-triggered. 40. In Question 39 how do we ak I . . . .Interrupts? ' m e sure t iat a SIngle mtcrrupt is not recognized as multIple 41. Which bits ofTCON belong to EXO? 42. Which bits ofTCON belong to EX

I?

43. True or false. The last two instructions of the ISR for /NT I

CLR TCON. 3 RETI

arc.

.

44. Explain the role ofTCON.O and TCON 2 . . 45. Explain the role ofTCON.l and TCON·3 In the execution of external interrupt O. 46. Assume that the IE bit for t . 111 the execution of external interrupt 1. . ex crnat hardware· t . . d e ge-tnggered. Explain how thi . 111 errupr EX I IS enabled and IS IS lI1terrupt wo k h .. r s w en it is activated. How can 346

-

-c

47. 48. 49. 50. 51. 52.

we make sure that a single interrupt is not interpreted as multiple interrupts? Write a program using interrupts to get data from P I and send it to P2 while TImer 0 IS generating a square wave of 3 kHz. Write a program using interrupts to get data from PI and send it to P2 while Timer I is turning on and off the LED connected to POA every second. Explain the difference between the low-level and edge-triggered interrupts. How do we make the hardware interrupt edge-triggered? Which interrupts are latched, low-level or edge-triggered? Which register keeps the latched interrupt for INTO and INT I?

SECTION 11.4: PROGRAMMING THE SERIAL COMMUNlCATION iNTERRUPT 53. True or false. There are two interrupts assigned to interrupts TI and RI. 54. What address in the interrupt vector table is assigned to the serial interrupt? How many bytes are assigned to it? 55. Which bit of the IE register belongs to the serial interrupt? Show how it is enabled. 56. Assume that the IE bit for the serial interrupt is enabled. Explain how this interrupt gets activated and also explain its working upon activation. 57. True or false. Upon reset, the serial interrupt is blocked. 58. True or false. The last two instructions of the ISR for the receive interrupt arc:

CLR TI RET I 59. Answer Question 58 for the receive interrupt. . 60. Assuming that the interrupt bit in the IE register is enabled, when Tl is raised, what happens subsequently? 61. Assuming that the interrupt bit in the IE register is enabled, when RI is raised, what happens subsequently? 62. Write a program using interrupts to get data serially and send it to P2 whi Ie at the same time Timer 0 is generating a square wave of 5 kHz. 63. Write a program using interrupts to get data serially and send it to P2 while Timer 0 is turning the LED connected to PI.6 on and off every second. SECTION

11.5: INTERRUPT PRIORITY IN THE 8051152

64. True or false. Upon reset, EX I has the highest priority. . . 65. What register keeps track of interrupt priority in the 8051? Explain Its role ". 66. Which bit of IP belongs to the EX2 interrupt priority? Show how to assign It the highest priori tv. . . 67. Which bit of IP belongs to the Timer I interrupt pnonty.

?

.

Show how to assign

it the highest priority. . . . . f IP b I s to the EX I interrupt priority? Show 68. Which bit 0 e ong the highest priority. . . . t r has all Os. Explain what happens IP 69. Assume that t h e regis e . TNTl activated at the same lime. . are IP' t has all Os. Explain what happens 70. Assume that the regis er . TF 1 are activated at the same lime.

CHAPTER

. . how to assign It if h I bot INTO and . If both TFO and

11: INTERRUPTS PROGRAMMING IN ASSEMBLY AND C

347

h' h what happens if both arc acti71. If both TFO and TF I in the IP are set to ign. at the same time? t high what happens n. vated If both INTO and INT I in the IP are set 0 , vated at the same time?

. .

73. Explain what happens if a low-pnonty

if both are acti-

. terrupt is activated while the 8051 is In

serving a higher-pnonty Interrupt.

ANSWERS TO REVIEW QUESTIONS SECTION 11.1:8051 INTERRUPTS I.

Interrupts

2

5 Address locations 0000 to 25H. No. They are set when tIic processor .rs dcsi csrgnc d . ~: All Osmeans that all interrupts arc masked. and as a result no Interrupts will be responded to by the 8051. 5. MOV IE, #10000011B 6. P3.3. which is pin 13 on the 40-pin DIP package 7. 0013H for INTI and OOIBH for Timer I SECTION 11.2: PROGRAMMING TIMER INTERRUPTS I. False. There is an interrupt for each of the timers. Timer 0 and Timer I. 2. OOOBH 3. Bits 01 and 03 and "MOV IE, #10001010B" will enable both of the timer interrupts. 4. Aller Timer I is started with instruction "SETB TR1". the timer will count up from F5H to FFH on its own while the 8051 is executing other tasks. Upon rolling over from FFH to 00. the TFI nag is raised, which will interrupt the 8051 in whatever it is doing and force it to jump to memory location 001 BH to execute the ISR belonging to this interrupt. 5. False. There is no need for "CLR TFO" since the RETI instructior, docs that for us. SECTION 11.3: PROGRAMMING EXTERNAL HARDWARE INTERRUPTS I. False. There is an interrupt for each of the external hardware interrupls of INTO and tNTI. 2. 0003H and 0013H. The pins numbered 12 (P3.2) and 13 (P3J) on the DIP package. 3. Bits DO and D2 and "MOV IE, #10000101B" will enable both of the external hardware interruplS.

4. Upon application of a low pulse (4 machine cycles wide) to pin PJ.J. the 8051 is interrupted in whatever it is doing and jumps 10 ROM location OOIJH to execute the ISR. 5. Tme 6. Make sure that the lowpulse applied 10 pin INTI is no wider than 4 machine cycles. Or. make sure thatthetheISR. INTl prn tSbrought back to high by the time the 8051 executes the RETI instrucuon III 7. False. There is no need 1'0 11 "CLR C ". . TCON 0 . . r ic T ON. 0 SInce the RETI instruction '.does that for us.d 8. . IS set to high to make INTO dee-m (th t i TCON 0 . an e gc-tnggered ttlterrupt. II' INTO rs cdge-triggerc a IS, . ISSeI) whenever a h'gl t I I" . . d (latched) d k b '. I 1- 0- Ow pu se ISapplied to the INTO pin 'I 's capture being se:i~ed +~d'Nt~e TCON.2 bit by making TCON.2 high. While the ISR for I TO is pin INTO.Upon the cxe st~ys htgh no mauc- how many times an H-to-L pulse is applied to bit is cleared, indicatin c~~~~~~f ~,e last IOstruet;on of the [SR. which is RETI, the TCON.2 g I TOpIOcan respond to another interrupt.

348

-

-

C.I1

SEc:;TlON 1104:PROGRAMMING THE SERIAL COMMUNICATION INTERRUPT I.

True. There is only one interrupt for both the transfer and receive.

2.

23H

3. 4.

Bit 04 (lEA) and ';MOV IE, #10010000B" will enable the serial interrupt. The RI (received inlemlpt) nag is raised when the entire frame of data, including the stop bit, is received. As a result the received byte is delivered to the SBUF register and the 8051 jumps to memory location 0023H to execute the ISR belonging to this interrupt. In the serial C:;OM interrupt service routine, we must save the SBUF contents before it is lost by the incoming data. False

5. 6. 7.

True. We must do it since the RETI instruction will not do it for the serial interrupt. CLR TI RETI

SECTlON 11.5: INTERRUPT PRlORJTY IN THE 8051/52 I. False. They are assigned priority according to Table 11-3. 2. IP (interrupt priority) register. Yes, it is bit-addressable. 3.. Bit 04 (IPA) and the instruction "MOV IP, #000 10000B" will do it. 4. Ifboth are activated at the same time, INTOis serviced first since it has a higher priority. Aller INTO is serviced, INTI is serviced, assuming that the external interrupts are edge-triggercd and H-to-L transitions are latched. In the case oflow-Ievel triggered interrupts, ifboth are activated at the same time, the INTO is serviced first; then after the 8051 has finished servicing the INTO, it scans the INTO and INTI pins again, and if the INTI pin is still high, it will be serviced. 5. We have an interrupt inside an interrupt, meaning tha: the lower-priority interrupt is put on hold and the higher one is serviced. After servicing this higher-priority interrupt, the 8051 resumes servicing the lower-priority ISR.

. MMING IN ASSEMBLY AND C CHAPTER 11: INTERRUPTS PROGRA

349

\

CHAPTER 12

L·CD AND KEYBOARD INTERFACING

OBJECTIVES

Upon completion of this chapter, you will be able to:

» >>

» » »

» » »

List reasons that LCDs are gaining widespread use, replacing LEOs Describe the functions of the pins of a typical LCD List instruction command codes for programming an LCD Interface an LCD to the 8051 Program an LCD in Assembly and C Explain the basic operation of a keyboard Describe the key press and detection mechanisms Interface a 4x4 keypad to the 8051 using C and Assembly

This. chapter exp Iores so me real-world applications of the 8051. We . c: explam. how to interrace the 8051 to devices such as an LCD and . a keyboard. 2 k b In . 12.1, we show LCD' m terfaeing with the 8051. In Section 12. Section h , ey . oard .interfacing . Wit . h t he 8051 IS. shown . We usc C and Assembly for bot sections.

SECTION 12.1: LCD INTERFACING This section describes the operation modes ofLCDs, then describes how to program and interface an LCD to an 8051 using Assembly and C.

LCD operation In recent years the LCD is finding widespread usc replacing LEOs (sevensegment LEOs or other multisegment LEOs). This is due to the following reasons: I. Thc declining prices of LCOs. 2. The ability to display numbers, characters, and graphics. This is in contrast to LEOs, which are limited to numbers and a few characters. 3. Incorporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of refreshing the LCD. In contrast, the LED must be refreshed by the CPU (or in some other way) to keep displaying the data. 4. Ease of programming for characters and graphics.

LCD pin descriptions The LCD discussed in this section has 14 pins. The function of each pin is given in Table 12-l. Figure 12-J shows the pin positions for various LeOs. ss Vee, V , and VEE

Table 12-1: Pin Descriptions

for LCD

While Vee and Vss provide +5V and PI'n Symbol I/O _ Description ground, respectively, VEE is used for control- 71~"""""":'Y';-s-s"'-~"""-';G~ro;';u;';;'n"di-'-;';"-~~ ling LCD contrast. RS, register select

;:2--:-:y::- =-c----+""SY:-:-"p-o-w-e-r-s-up-p'7 ly c 3 y EE Power supply

'. There are two very important registers to control contrast Inside the LCD. The RS pin is used for their 4 RS RS = 0 to select selection as follows. If RS = 0, the instruction command register, command code register is selected, allowing the RS = I to select user to send a command such as clear display, data register cursor at home, etc. If RS = I the data register S RlW RIW _ 0 for write, ISselected, allowIng the user to send data to be RIW = I for read displayed on the LCD. c6--;E~--:1/';';:0:---::E~n.:.:ab....,l-e~::::....:==-RIW, read/write RlW .

7 OBO I/O The 8-bit data bus 7,'8--;0:;':B:':"-1 -,::,1/~0--T~h.:..:e:.-.:8::-..-b::..:i"-t d::':a:':'ta::"'b:-u-s. input allows the user to write in COr_ ;;-9---;:0:';B:::2:--::::;~-~~~~=~-:mat Ion tateh L CD or read infonnation fromII it ~I I/O The 8-bit data bus O;;--~~-:-~--=~::--;::-:-:;:=~=RlW = I when reading' RlW = 0 wh ..' DB3 I/O The 8-bit data bus , en Wntmg. II OB4 I/O The 8-bit data bus E, enable 7'::;-2 ----;:~-~~~~~::.:.:..:;:=~~ OBS I/O The 8-bit data bus OB6 I/O The 8-bit data bus latch . The enable pin is used by the LCD to 13 mfonnatlon preSented t it d . OB7 I/O The 8-bit data bus a 1 s ata PIns. 14

352

When data is supplied to data pins, a high-to-Iow pulse must be applied to this pin in order for the LCD to latch in the data present at the data pins. This pulse must be a minimum of 450 ns wide. DO-D7 The 8-bit data pins, DO- 07, are used to send information to the LCD or read the contents of the LCD's internal registers. To display letters and numbers, we send ASCII codes for the letters A - Z, a - z, and numbers 0 - 9 to these pins while making RS = I. There are also instruction command codes that can Table 12-2: LCD Command Codes be sent to the LCD to clear the Code Command to tcb Instruction display or force the cursor to Register the home position or blink the cursor. Table 12-2 lists the 2 Return home instruction command codes. 4 Decrement cursor (shift cursor to left) We also use RS = 0 to 6 Increment cursor (shift cursor to right) check the busy flag bit to see if 5 Shift display right the LCD is ready to receive 7 Shift display left information. The busy flag is 8 Display off, cursor off D7 and can be read when RJW A Display off, cursor on = I and RS = 0, as follows: if c Display on, cursor off RJW = I, RS = O. When D7 = E Display on, cursor blinking I (busy flag = I), the LCD is F Display on, cursor blinking busy taking care of internal 10 Shift cursor position to left operations and will not accept 14 Shift cursor position to right any new information. When 18 Shift the entire display to the left D7 = 0, the LCD is ready to IC Shift the entire display to the right receive new information. Note: 80 Force cursor to beginning of 1st line Force cursor to beginning of 2nd linc It is recommended to check the co busy flag before writing any 38 2 lines and 5x7 matrix Note: This table is extracted trom Table 12-4. data to the LCD. 12

14

o DDDDDDDDDDDDDD

0

-:====== II

II 0

0 DMCl610A DMC1606C DMC16117 DMC16128 DMCl6129 DMCI616433 DMC20434

14

DMCI6106B DMCI6207 DMCI6230 DMC20215 DMC32216

o

gry=== 2::l1~

14

00

13

o

DMC2026I DMC24227 DMC2413R DMC32132 DMC32239 DMC40131 DMC40218

. LeDs from Optrex Figu re 12-1. Pin Positions for various CHAPTER 12: LCD AND KEY BOA

RD INTERFACING

353

. com man ds an d data to LeOs with a time delay Sending pin RS To send any of the cornman ds from Table 12-2 to the LCD, make . . S I Th send a high-to-Iow pulse to the E pill to enable = O. For data, make R -. en. F' . the internal late h 0 f th e LCD . This is shown 111 Program 12-1. Sec igurc 12-2 for LCD connections.

;cal s a time delay before sending next.data command ; P1.0-P1.7 are connected to LCD data plns 00-07 P2.0 is connected to RS pln of LCD P2.1 is connected to R/W pin of LCD P2 .2 is connected to E pin of LCD ORG OH MOV A,#38H ;init. LCD 2 lines,5x7 matrix ACALL COMNWRT ;call command subroutine ACALL DELAY ;give LCD some time MOV A,#OEH ;display on, cursor on ACALL COMNWRT ;call command subroutine .ACALL DELAY ;give LCD some time MOV A, #01 ;clear LCD ACALL COMNWRT ;call command subroutine ACALL DELAY ;give LCD some time MOV A,#06H ;shift cursor right ACALL COMNWRT ;call command subroutine ACALL DELAY ;give LCD some time MOV A,#84H ;cursor at line l,pos. 4 ACALL COMNWRT ;call command subroutine ACALL DELAY ;give LCD some time MOV A,#'N' ;display letter N ACALL DATAWRT ;call display subroutine ACALL DELAY ;give LCD some time MOV A,#'O' ;display letter 0 ACALL DATAWRT ;call display subroutine AGAIN: SJMP AGAIN ;stay here COMNWRT: ;send command to LCD MOV P1,A ;copy reg A to portl CLR P2.0 ;RS=O for command CLR P2.1 ;R/W=O for write SETB P2.2 ;E=l for high pulse ACALL DELAY ;give LCD some time CLR P2.2 ;E=O for H-to-L pulse RET DATAWRT: MOV SETB CLR SETB ACALL CLR . ommUOIcating with LCD

354

.

uSll1g a delay (conlil1uedon next page)

-

CI

DELAY: HERE2: HERE:

MOV MOV DJNZ DJNZ RET END

R3,#50 R4,#255 R4,HERE R3,HERE2

;50 or hlgher for fast CPUs ;R4=255 ;stay until R4 becomes 0

Program 12-1. (continI/ed/rom previous page)

Sending code or data to the LCD with checking busy flag The above code showed how to send commands to the LCD without checking the busy flag, Notice that we must put a long delay between issuing data or commands to the LCD, However, a much better way is to monitor the busy flag before issuing a command or data to the LCD, This is shown in Program 12-2,

8051

P!.O

LCD Y y.,..cc.., o::-:o:------"7+5

r:

10K PI.7

07

POT

P2,Of---..J P2,1f---..J P2,2 f------'

Figure 12-2. LCD Connections

;Check busy flag before sending data, command to LCD ;P1=data pin,P2.0=RS,P2.1=R/W,P2.2=E pins MOV A,#38H ;init. LCD 2 lines,5x7 matrix ACALL COMMAND ;issue command MOV A,#OEH ;LCD on, cursor on ACALL COMMAND ;issue command MOV A,#OlH ;clear LCD command ACALL COMMAND ;issue command MOV A,#06H ;shift cursor right ACALL COMMAND ;issue command MOV A, #86H ;cursor: line ;t, pos. 6 ACALL COMMAND ;command subroutine MOV A,#'N' ;display letter N ACALL DATA_DISPLAY ;display letter 0 MOV A,#'O' ACALL DATA_DISPLAY ;STAY HERE HERE: SJMP HERE lis LCD ready? COMMAND: ACALL READY ·issue command code MOV P1,A ;RS=O for command CLR P2.0 ;R/W=O to write to LCD CLR P2.1 ·E=l for H-to-L pulse SETB P2.2 ;E=O ,latch in CLR P2.2 RET . . . h LCD using the busy nag {continued on next page) Program 12-2: CommumcatlOg WIt

CHAPTER 12: LCD AND KEYBOARD INTERFACING

355

DATA DISPLAY: r.is LCD ready? ACALL READY ·issue data PI,A MOV :RS=1 for data SETB P2.0 ;R/W=O to write to LCD P2.1 CLR ·E=l for H-to-L pulse SETB P2.2 ;give LCD some time ACALL DELAY ;E=O, latch in P2.2 CLR RET ,make PI.7 input port READY: SETB PI. 7 ,RS=O access command reg P2.0 CLR ,R/W=l read command reg SETB P2.1 ;read command reg and check busy flag BACK: CLR P2.2 ;E=O for L-to-H pulse ACALL DELAY ;give LCD some time SETB P2.2 ;E=l L-to-H pulse JB PI.7,BACK ;stay until busy flag=o RET END Program 12-2. (continued from previous page)

Notice in the above program that the busy flag is 07 of the command register. To read the command register we make RJW = I and RS = 0, and a Lto-H pulse for the E pin will provide us the command register. After reading the command register, if bit 07 (the busy flag) is high, the LCD is busy and no inforrnation (command or data) should be issued to it. Only when 07 = 0 ean we send data or commands to the LCD. Notice in this method that no time delays arc used sinee we arc checking the busy flag before issuing commands or data to the LCD. Contrast the Read and Write timing for the LCO in Figures 12-3 and 12-4. Note that the E line is negative-edge triggered for the write while it is positive-edge triggered for the read.

DO - D7

-----.---.~K'-__D_a_ta__

__')r------

'0

E R/W

'

-1r... ·,A=s·..:-T·-------bi~=1I

RS,

_

'--t---_-itD.:=

'AS

Data output delay tim~ 0

'o,---L..---.l_l...-_



"Off'

"On"

.. IOL

=I

VOL

= RaN

"Off'

IlL

(transistor)x

IOL

Figure C-7. Current Sinking and Sourcing in TTL Notice that in Figure C-7 as the b . . gle output increases I rises h'· h num cr of mpur pins connected to a sin'Ol , w ic causes V t . If" . of VOL makes the noise' Ol 0 nse, this continues, the nse margin smaller and th i . I . logic due to the slightest noise's resu ts m the OCcurrence of false

574

E

Example C-l Find how many unit loads (UL) can b e driven . by the output of the L5 logic family. Solution: The unit load is defined as I IL --. I 6 rnA an d IIH = 40 ~A. Table C-I shows I . = 400 OH I1A and IOL = 8 rnA for the L5 family. Therefore, we have

8 rnA

IOL

fan-out (low)

=

IlL

=

1.6 rnA 400 ~A

IOH

fan-out (high) =

'=

=5

= 10

1IH 40 ~ This means that the fan-out is 5. In other words, the L5 output must not be connected to more than 5 inputs with unit load characteristics.

74L5244 and 74L5245 buffers/drivers In cases where the receiver current requirements exceed the driver's capability, we must use buffers/drivers such as the 74L5245 and 74L5244. Figurc ·8 shows the internal gates for the 74L5244 and 74L5245. The 74L5245 is used f r bidirectional data buses, and the 74L5244 is used for unidirectional address buses, o Vee

I

0

B2

1G

Vcc

B3 1Y-1

1A-1

B4

-A4

1A-2

r-,

11 1A-3 r-,

2A-1

r-, ~2Y-2

2A-2

1Y-2

-A5

1Y-3

-A6

GND

I

18

B6 DIR Enable

control

Function DirectiOO00ntr0I

2Y-4

1C-

B7

Direction

2Y-3

2A-4

B6

-A6

2Y-1

:-c.-

2A-3

BS

-A7

1Y-4

1A-4

GND B1

Enable L L

G

DIR L

H

H X

Table DnArst"'" B Data to A Bus A Dat8 10B Bus lsotation

. re C-8 (b). 74LS245 Bidirecli nal BulTer

. GY AND SYSTEM DESIGN I APPENDIX C: IC TECHNOLO

Tri-state buffer Notice that the 74LS244 is simply 8 tristate buffers in a single (a) In~ut chip. As shown in Figure C-9 a tri-state buffer has a single input, a single output, and the enable control input. By activating the enable, data at the input is H~ ~, transferred to the output. (e) The enable can be an active-low or an activehigh. Notice that the enable input for the 74LS244 is an active low whereas the Figure C-9. enable input pin for Figure C-9 is active high.

L~

Tri-state control (active high)

(b)

l

H

(d)

H

High-impedence (open-circuit) Tri-State Buffer

74LS245 and 74LS244 fan-out It must be noted that the output of the 74LS245 and 74LS244 can sink and

source a much larger amount of current than that of other LS gates. Sec Table C4. That is the reason we use these buffers for driver when a signal is travelling a long distance through a cable or it has to drive many inputs. Table C-4: Electrical Specifications for Buffers/Drivers

74LS244 74LS245

IOH (rnA)

IOL (rnA)

3 3

12 12

After this background on the fan-out, next we discuss the structure of 8051 ports. We first discuss the structure of PI - P3 since their structure is slightly different from the structure of PO.

P1 - P3 structure and operation Since all the ports of 8051 are bidirectional they all have the following three components in their Structure: I. D latch 2. Output driver 3. Input buffer Figure Col 0 shows the structure of P I and its three components. The other ports, P2 and P3, are basically the same except with extra circuitry to allow their dual functions (see Chapter 14). Notice in Figure C-I 0 that the L I load is an internalload for PI, P2, and P3. As we will see at the end of this section that is not the

=~~. 576

,

Vcc

Read latch TB2

Internal CPU bus

0

PH pin

Q

PH Clk Q

Write to latch

Read pin __

Load (L1)

M1

TB1

---I

Figure C-IO. 8051 Port I Structure rc: Also notice that in Figure ColO, the 8051 ports have both the latch and IOn IS, is.j 111 reading . the port, arc we reading the status of the b. utrer . . Now th e ques tion input pm or arc we reading the status of the latch? That is an extremely important question and ItS answer depends on which instruction we arc using. Therefore. when reading the ports there are two possibilities: (I) reading the input pin, or (2) reading the latch. The above distinction is very important and must be understood lest you damage the 8051 port. Each is described next.

Reading the input pin As we stated in Chapter 4, to make any bits of any port of 8051 an input port, we first must write a I (logic high) to that bit. Look at the following sequence of events to see why. I.. As can be seen from Figure C-11, a I written to the port bit is written to the latch and the D latch has "high" on its Q. Therefore, Q = I and Q = O. 2. Since Q = 0 and is connected to the transistor M I gate, the M I tran i 'tor is 01T. 3. When the M I transistor is off, it blocks any path to the ground for any signal connected to the input pin and the input signal is directed to the tri-srarc TB I, 4. When reading the input port in instructions such as "MOV A, Pl" we arc realIy reading the data present at the pin. In other words, it is bringing into the CPU the status of the external pin. This instruction activates the read pin of T8 I (tristate buffer 1) and lets data at the pins flow into the CPU's internal bus. Figures C.I I and C-12 show high and low signals at the input, respectIvely.

Vce Read latch

Load (L 1)

TB2

High

Internal CPU bus

0 elk

P1'X

pin

'1' '0'

PH

Write to latch

Read pin __

Q Q

Off

TB1 ...--J

Figure C.11. R~ading "High" at Input Pin

APPENDIX C: IC TECHNOLOGY AND SYSTEM DESIG ' IS

Read latch

Vcc

-, TB2

Internal CPU bus

Load (L1) Low

-+--j

D

Q

P1·X

Write to latch ..-.-.,f----i

Clk

P1X

'1'

pin

'0' Q

1-------1 Off

TB1

Read pin -_--'

~

Figure C-12. Reading "Low" at the Input Pin

Writing "0" to the port The above discussion showed why we must write a "high" to a port's bits in order to make it an input port. What happens if we write a "0" to a port that was configured as an input port? From Figure C-13 we see that if we write a 0 (low) to port bits, then Q = 0 and 0 = I. As a result of 0 = I, the M I transistor is "on". If M I is "on," it provides the path to ground for both LI and the input pin. Therefore, any attempt to read the input pin will always get the "low" ground signal regardless of the status of the input pin. This can also damage the port, as explained next.

Vcc

Read iatch T82

Internal CPU bus

Write to latch

0

Q

PH Clk

'0' PH

'1' Q

~M1

On Read pin

i

Load (L1) -/ pin

Vcc

-&

willdamage

M1

TB1

Figure C-13. Never Connect Direct Vee to the 8051 Port Pin

Avoid damaging the port We must be very careful when connecting a switch to an input port of the 8051. This IS due to the fact that the wrong kind of connection can damage the port. Look at Figure C-13. If a switch with Vee and ground is connected directly to the pm and the M I transistor is "on" it will sink current from both internal load LI and external Vee- This can be too much Current for MI, which will blow the transistor and, as a result damage the port bit Th . . . bl '. . . ere are several ways to avoid this pro em. They are shown m Figures C-14, C-15, and C-16.

578 j

Read latch

Vcc

---

TB2

Vee

Load (L1)

10K

Internal

CPU bus

Write 10latch

_.....--Jr,:;----:-t o Q ----1~~J

PH pin

ClkPH Qr----I

=jt-TiTBa:11-----...s~J

Read pin

. Figure C-14 . I nput Switch with Pull-U p R esistor Read latch

Internal

CPU bus

---

TB2

_-4_Jn--;:l 0

Q

Write to latch ---4'----1 ClkPH Q

Read pin

Load (L1)

P1X

pin

r----......J

'--~r-;T;B:;-1-----::...~

Figure C-15. Input Switch with No V ee Vee Read latch

_

TB2

Load (L1)

Vee 74LS244

Internal _~_-fn-nl

CPU bus

Write to latch -if----IClk

Read pin ---'

0

P1'X

Q

M1

PH pin

Q t-----....j

TB1

Figure C-16. Buffering Input Switch with Direct Vee I. One way is to have a J OK-ohm resistor on the Vee path to limit current flow through the Ml transistor. See Figure C-14. 2. The second method is to usc a switch with a ground only, and no Vee· shown in Figure C-15. In this method, we read a low when the switch

3S I'

pressed and we read a high when it is released. 3. Another way is to connect any input switch to a 74LS244 tri-state butTer before it is fed to the 8051 pin. This is shown in Figure C-16.

E

APPENDIX

C: IC TECHNOLOGY AND SYSTEM DESIGN I

5 9

· are exterme Iy importan . t an d must be emphasized since The above pomts many people damage their ports and wonder how it happened. We must also use the right instruction when we want to read the status of an mput pm. Table C-5 shows the list of instructions in which reading the port reads the status of the mput pm. Table C-5: Instructions Reading the Status of Input Port Mnemonics

Examples

MOV A,PX JNB PX. Y, . . . JB PX.Y,...

MOV A,PI JNB Pl. 2 , TARGET JB P1.3,TARGET

MOV C,PX.Y CJNE A, PX, . . .

MOV C,PI.4 CJNE A, PI, TARGET

Reading latch Since, in reading the port, some instructions read the port and others read the latch, we next consider the case of reading the port where it reads the internal port latch. "ANL PI, A" is an example of an instruction that reads the latch instead of the input pin. Look at the sequence of actions taking place when an instruction such as "ANL PI, A" is executed. I. The read latch activates the tri-state buffer ofTB2 (Figure C-17) and brings the data from the Q latch into the CPU. 2. This data is ANDed with the contents of register A. 3. The result is rewritten to the latch. After r:...writingthe result to the latch, there are two possibilities: (I) If Q = 0, then Q = I and M I is "on," and the output pin has "0," the same as the status of the Q latch. (2) If Q = I, then Q = 0 and the M I is "off," and the output pin has" I," the same as the status of the Q latch.

Read pin

Figure C-17. Reading the Latch 580

T81 (off)

-

From the above discusthat the instruction that reads the latch normally reads a value, performs an operation (possibly changing the value), and rewrites the value to the latch. This is often called "read-modify-write." Table C-6 provides a list of read-modify-write instructions. Notice from Table C-6 that all the read-modifywrite instructions .use the port as the destination operand.

sion, we conclude

Table C-6: Read-Modify-Write

Instructions

Mnemonics

Example

ANL ORL XRL JBC CPL INC DEC

ANL ORL XRL JBC CPL INC DEC

Pl,A Pl,A Pl,A Pl.l,TARGET Pl.2 PI PI DJNZ Pl,TARGET MOV Pl.2,C CLR PI. 3 SETB Pl.4

DJNZ

MOV PX.Y,C CLR PX.Y SETB PX. Y

PO structure A major difference between PO and other pons is that PO has no internal pull-up resistors. (The reason is to allow it to multiplex address and data. Sec Chapter 14 for a detailed discussion of address/data multiplexing.) Since PO has no internal pull-up resistors, it is simply an open-drain as shown in Figure C-18. (Open-drain in MOS is the same as open-collector in TTL). Now by writing a "I" to the bit latch, the M I transistor is "off' and that causes the pin to float. That i the reason why when PO is used for simple data I/O wc must connect it to cxicrnal pull-up resistors. As can be seen from Figures C-18 and C-19, for a PO bit to drive an input, there must be a pull-up resistor to source current.

Read latch

Internal CPU bus Write to latch

T82 PO·X pin

Q

0

PO·X Q Clk

M1

T81 Read pin ----'

Figure C-18. PO Structure

(notice ope II-drain)

. th h PO is used for address/data multiplexing and it i e nNotice at w en h ddr there is no need for e tcmal pull-up nectcd to the 74LS373 to latch t c a ess, resistors, as shown in detail in Chaptcr 14.

E

APPENDIX

C: ]C TECHNOLOGY AND SYSTEM DESIGN I

Vcc Read latch

TB2

10K

'J

Internal bus

0

CPU

pull-up resistor PO'X pin

Q f--

PO·X Q Clk

Write to latch

- External

:~

M1

t' TB1

Read pin

Figure C-19. POWith External Pull-Up Resistor

8051 fan-out Now that we are familiar with the port structure of thc 8051, we need to examine the fan-out for the 8051 microconctroller. While the early 8051 microcontrollers were based on NMOS IC technology, today's 8051 microcontrollcrs are all based on CMOS technology. However, notc that while the core of the 8051 microcontrollcr is CMOS, the circuitry driving its pins is all TTL compatible. That is, the 8051 is a CMOS-based product with TTL-compatible pins.

P1, P2, and P3 fan-out

Table CO?: 805] Fan-out for P], P2, P3

The three ports of PI, P2, and P3 have the same VO structure, and therefore the same fan-out. Table C-7 provides the I/O characteristics of PI, P2, and P3.

Pin 10L

Port 0 fan-out

I1H

PO requires external pull-up resistors in order to drive an input since it is an open drain I/O. The value of this resistor decides the fan-out. However, since IOL = 3.2 mA for

VOL =

Fan-out 1.6 rnA 10H 60 pA :-:"7'Lc.:.......---:5::..:0~p::;.A.:---------

0.45

V,

we must make

sure that the pull-up resistor connected to each pin of the PO is no less than 1422 ohms, since (5 V - 0.45 V) / 3.2 rnA = 1422 ohms. In applications in which PO is not connected to an external pull-up resistor, or is used in bus mode connected to a 74LS373 or other chip, it can drive up to 8 LS TTL inputs.

74L5244 driving an output pin

650 pA

Note: PI, P2, and P3 can drive up to 4 LS TIL inputs when connected to other lC chips.

8051

74LS244

DO Printer P1

data r--+~>-+-07

port

STROBE

P2.0r----l P2.1 r----