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

8051 (Volume-1)

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

8051 (Volume-1)

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

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 g and C / Muhammad
~lJ.t~h.Muh.1mmad All. d bedded systems: using Assembly,
I luoconlrolltr an em . 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
"""rved. 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,
Pcmllssiol\s Department. photocopying, recording, or likewise. For information regarding pennission(s), write to: Rights and

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 Australia PTY, Lintited
Pearson Education Canada, Ltd.
Petlt!On Education-Japan Pearson Education North Asia Ltd.
Pearson Educacion de Mexico, SA de C. V.
Pearsoll Education MalaYSia, Pte. LId.
Pearson Education 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: Introduction to Computing 23
I: The 8051 Microcontrollers 37
2:
8051 Assembly Language Programming
69
3: Jump, Loop, and Call Instructions
9
4: I/O Port programming
109
s: 80SI Addressing Modes
1'9
6: Arithmetic & Logic Instructions and Programs
I I
7: 80SI Programming in C
80SI Hardware Connection and Intel Hex File 217
8:
8051 Timer Programming in Assembly and C 2 9
9:
Ed 10: 80SI Serial Port Programming in Assembly and C 277
Ed II: Interrupts Programming in Assembly and C 317
PI 51
De 12: LCD and Keyboard Interfacing
Co 13: ADC. DAC. and Sensor Interfacing 37
Co 14: 8051 Interfacing to External Memory 411
PI
So IS: 8051 Interfacing with the 8255 449
So 16: DS12887 RTC Interfacing and Programming 467
17: Motor Control: Relay, PWM. DC. and Stepper Motors 491

APPENDICES
A: 8051
B. Instructions
. I
Timing and Registers
,
.
52
B: asrcs of WIre Wrapping
C: Ie Technology adS . Issues 56
0:
FI h n ystem DeSIgn 567
Owe arts and Pseudocode
E: 8051 Primer for X86 P 7
F: ASCII Codes rogrammers 592
G: Assemblers. Development R 593
H: Data Sheets eSOurces. and Suppliers 594
596
CONTENTS

CHAPTER 0: INTRODUCTION TO COMPUTING 1


Section 0.1: Numbering and coding systems 2
Section 0.2: Digital primer 9
Section 0.3: Inside the computer 13

CHAPTER 1: THE 8051 MICROCONTROLLERS 23


Section 1.1: Microcontrollers and embedded processors 24
Section 1.2: Overview of the 8051 family 28

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 37


Section 2.1: Inside the 8051 38
Section 2.2: Introduction to 8051 Assembly programming 41
Section 2.3: Assembling and running an 8051 program 44
Section 2.4: The program counter and ROM space in the 8051 46
Section 2.5: 8051 data types and directives 49
Section 2.6: 8051 flag bits and the PSW register 52
Section 2.7: 8051 register banks and stack 55

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 69


Section 3.1: Loop and jump instructions 70
Section 3.2: Call instructions 75
Section 3.3: Time delay for various 8051 chips 80

CHAPTER 4: I/O PORT PROGRAMMING 93


Section 4.1: 8051 I/O programming 94
Section 4.2: I/O bit manipulation programming 100

CHAPTER 5: 8051 ADDRESSING MODES 109


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

CHAPTER 6: ARITHMETIC & LOGIC INSTRUCTIONS


AND PROGRAMS 139
Section 6.1: Arithmetic instructions 140
Section 6.2: Signed number concepts and arithmetic operations 150
Section 6.3: Logic and compare instructions 155
Section 6.4: Rotate instruction and data serialization 161
Section 6.5: BCD, ASCII, and other application programs :167

v
-
CHAPTER 7: 8051 PROGRAMMING IN C
181
Section 7.1: Data types and time delay in 805 I C
182
Section 7.2: I/O programming in 8051 C
188
Section 7.3: Logic operations in 8051 C
194
Section 7.4: Data conversion programs in 8051 C
199
Section 7.5: Accessing code ROM space in 8051 C
204
Section 7.6: Data serialization using 8051 C
209

CHAPTER 8: 8051 HARDWARE CONNECTION AND


INTEL HEX FILE
217
Section 8.1: Pin description of the 805 I
218
Section 8.2: Design and test of DS89C4xO trainer
224
Section 8.3: Explaining the Intel hex file
232

CHAPTER 9: 8051 TIMER PROGRAMMING


IN ASSEMBLY AND C
239
Section 9.1: Programming 8051 timers
240
Section 9.2: Counter programming
255
Section 9.3: Programming timers 0 and I in 8051 C 260

CHAPTER 10: 8051 SERIAL PORT PROGRAMMING


IN ASSEMBLY AND C
277
Section 10.1: Basics of serial communication 278
Section 10.2: 8051 connection to RS232 285
Section 10.3: 8051 serial port programming in Assembly 287
Section 10.4: Programming the second serial port 300
Section 10.5: Serial port programming in C 306

CHAPTER II: INTERRUPTS PROGRAMMING


IN ASSEMBLY AND C 317
Section I 1.1: 8051 interrupts 318
Section 11.2: Programming timer interrupts 322
Section I 1.3: Programming external hardware interrupts 326
Section 11.4: Programming the serial communication interrupt 333
Section I1.5: Interrupt priority in the 8051/52 337
Section 11.6: Interrupt programming in C 340

CHAPTER 12: LCD AND KEYBOARD INTERFACING 351


Section 12.1: LCD interfacing 352
Section 12.2: Keyboard interfacing 363

CHAPTER 13: ADC, DAC, AND SENSOR INTERFACING 373


Section 13. I: Parallel and serial ADC 374
Section 13.2: DAC interfacing 398
Section 13.3: Sensor interfacing and signal conditioning 403

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

CHAPTER 15: 8051INTERFACING WITH THE 8255 449


Section 15.1: Programming the 8255 450
Section 15.2: 8255 interfacing 458
Section J 5.3: 8051 C programming for the 8255 462

CHAPTER 16: DS12887 RTC INTERFACING


AND PROGRAMMING 467
Section 16.1: DS 12887 RTC interfacing 468
Section 16.2: OSI2887 RTC programming in C 476
Section 16.3: Alarm, SQW, and IRQ features of the
DS 12887 chip 479

CHAPTER 17: MOTOR CONTROL: RELAY, PWM, DC,


AND STEPPER MOTORS 491
Section 17.1: Relays and optoisolators 492
Section 17.2: Stepper motor interfacing 498
Section 17.3: DC motor interfacing and PWM 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

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, stu-
pcncnce 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

..",.n,·. ICp ppr .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

the 0 I and feature of other 8051 fam-


I. n ~OOO.and D 9C4xO. It also pro-
hIp •
r hue lure 0/ the 0 I and explains the
-to-run program. 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 flow-
charts 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-
What is new in the sec . edition is the addition A sembI languag
The biggest change inWhile
this new
Chapters I t hough
r 6 blyand
use language pr _
ming throughou t ,the book.
ith ChapterI 7, we haddition
ve both Assem
includes t h e following new
. Iy, starting .ws discussed. The secon e
exclusive
grams for all the topic

features: . (Chapter 7)
8051 C programming . ers ( ection 9.3)
Anew chapter 00 he 80" C programm ing of ";89<:4'0 ch ip ( ecti n 10:')
A new secuon on 1 d serial port of the D d erial pan ( e lion
A new section on the ~~;~ C programming of the econ
A new secnon on the . I I 6)

10.5) . . of interrupts
th 8051 C programming ( c lion 14.4)
0 h' (Section .
A new secuon on e KB SRAM of the DS89C4x C Ip ( ecti n 14. )
Programming of", , ro ramming of ~I"",, memory 16)
A new section on the 8051 ~:7 :TC (real-time clock) chip ( hapter
A new chapter
A new chapter on
on motors,
the DSI2relays, and optoisolators (Chapter 17)
E
E
P
lab manual h b k b the
The lab manual and suppo~ rnat~.rialslEd' and otite.er
for this Web
authors can be found at the www.MlcroDlglla.eom

S","",," ""00."'_""",, ,"'" . f


The solutions manual was produced wu. h tee h h Ipo. f Ardeshirfor theI rm
dr (0
\ _
harif University). The solutions manual and PowerPotnt@ slide ir Pr mi e
ings are available online for instructors only. Instructors Can Contact the
Ila/l representative or visit wWw.prenhall.eom.
Acknowledgments

This book is the result of the dedication and encouragement of many indi-
viduals. Our sincere and heartfelt appreciation goes to all of them.
First, we Would like 10 thank PrOfessor Danny Morse, the rno t knowl-
edgeable and experienced person on the 8051 that we know. He felt a trong need
for a book such as this, and due to his lack of time he encOuraged 1I 10 write it. He
i the one who introduced us to this microcontroller and was always there, ready
10 discuss issues related to 8051 architecture.

0 Also we Would like to express our sincere thanks to Profe SOr Iyde
book.
K ,hI o f De Vry Univers. 0/ for hi, h"p'o' ""'''''"' 00 the ,~'" ,f the '''''00
in .dll'"" the""ow'"8 pmf,",," ,"d _"" 'Oo"' '"'" whII," ing
the""" in '" "P"""",oo
'h'm """"y, ,,"r.~,
f,""
in "'" m
PhilG"Id~"diobo B,"Y"
"",,'01" II" '"""' ,,' we mM'
Do V~ UoI;",~, R,bon
lV'gh"",,, p,,,,,,,, "'",""
U"'i,m '" "m boo, D"" B'.m", J'Im H'.. ''''
~ Rob."", y'''Y Ch""" N"
J,m" Doo'" Ro,," MI,,,,, I B,,,, ''''00
"0
Hoang, and Trevor Isra.
II,J"" ~ ""Y H'", """
J"h"~",J"" K,,,,:M""" I M'"h;", M,"
Acknowledgments for the second edition
Thanks to the reviewers of this edition: Jack Adams, Merrimack College;
Hector Gutierrez, Florida Institute of Technology; Martin Hebel, Southern Illinois
University; Gary Hill, California State University - Long Beach; Juan Vargas,
University of Central Florida; Richard W. Wall, University of Idaho; and Rainer
Weschke, SUNY - Suffolk.
Numerous professors, students, and individuals sent us comments and
errors found in the first edition. Many others made suggestions for the second
edition. We would like to thank all of them sincerely for their enthusiam and support.
We hope to create a list of their names on our Web site at
www.MicroDigitaIEd.com. They are Danny Morse, Clyde Knight, Shah ram
Rohani (all from DeVry University), Javad Rasti (Esfahan University), Nassir
Abedi (KN. Toosi University), Hooman Shayani (BIHE), Jaco Vosloo
(Stellenbosh University), Mohammad Khalid Kerani, Hassan Mohammadi Abdar
(Azad University), Jeff Solinsky, Alijah Ballard, Jacob Stauffer, Vaibhav Joshi,
Michael Kelley, and Dan Masterson.
Finally, we would like to thank the people at Prentice Hall, in particular
our editor Kate Linsner, who continues to support and encourage our writing, and
our production editor Kevin Happell, who made the book a reality.
We enjoyed writing this book, and hope you enjoy reading it and using it
for your courses and projects. Please let us know if you have any suggestions or
find any errors .

. Assemblers
The following gives sites where you can download assemblers:

www.MicroDigitalEd.com
www.keil.com for Keil Corporation
www.fsinc.com for Franklin Software, Inc.

Another interesting Web site is www.8052.com. which contains more


discussion on the microcontroller. Finally, the following site provides useful Intel
manuals:

http://developer.intel.com/design/mcs51/docs_mcs51.htm

SafariX: Where the Web Meets Textbooks for Student Savings!


SafariX Textbooks Online" is an exciting n'ew choice for students looking
to save money. As an alternative to purchasing the print textbook, students can
subscribe to the same content online and save up to 50% off the suggested list
price of the prim text. With a SafariX WebBook, students can search the text,
make notes online, print out reading assignments that incorporate lecture notes,
and bookmark important passages for later review. For more information, or to
subscribe to the SafariX WebBook, visit http://www.safarix.com.

- xi
AtlUU I 1m: I\U II """ ..
Whati
Ali Mazidi went to Tabrll
Muhamma d U . ahe
fi both Southern Methodi l 0I1e1'l11)
degrees rom d hi Ph D In a
Dallas. He is currenlly a.b. : on. . .
Department of Southern Methodist VOile II) lie I
textbook, The 80x86 IBM PC and CIlI/lf'</IIh1l'
Prentice Hall. He leaches microproce t-
A University in Dallas, Texas. .
• A Janice Gillispie Mazidi has a M rer 01
A Science from the University of orth Texas. h h " c
A as a software engineer in Dallas. he h been hid 'ChilI I \ III r
10. lionmanager, and was responsible for solhl re ckl I pm III a
• A Iy used textbook, The 8Ox86 IBM PC anti 1I1IIp</lr"l tN I/' 1/
P from Prentice Hall.
• A
A
Rolin McKinlay has a BSEET fr m De\/) llll\1;
working on his Masler's degree and PE licen . In Ih' ,.
I'I I
, A
rently self-employed as a programmer and ir UII rd d I '/I r, r
in MicroDigitaIEd.com.

The authors can be Contacled aI/he fol/oll In -m "


any comments or suggestions, or if you find II) cit I •
Sol [email protected]
mmazidi@microdigi,aJed.com
hari rmckinJaY@microdigi,aled.com
rngs
Iiall
Ack
This volume is dedicated to the memory of Dr. A. Davoodi,
Professor of Tehran University, who in the tumultuous years a/my youth
taught me the importance of an independent search for truth.
- Muhammad Ali Mazidi

To Betsy.for all the love, encouragement, and sacrifice she has made/or me.
- Rolin D. Mckinlay

xiii
r
r

"
f>
I'
CHAPTER 0

INTRODUCTION TO
COMPUTING

OBJECTIVES

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

» Convert any number from base 2, base 10, or base 16 to either of the
other two bases
» Add and subtract hex numbers
» Add binary numbers
» Represent any binary number in 2's complement
» Represent an alphanumeric string in ASCII code
» Describe logical operations AND, OR, NOT, XOR, NAND, NOR
» Use logic gates to diagram simple circuits
» Explain the difference between a bit, a nibble, a byte, and a word
» Give precise mathematical defmitions of the terms kilobyte, megabyte,
gigabyte, and terabyte
» Explain the difference between RAM and ROM and describe their use
» Describe the purpose of the major components of a computer system
» List the three types of buses found in computers and describe the
purpose of each type of bus
» Describe the role of the CPU in computer systems
» List the major components of the CPU and describe the purpose of each

1
ana 1I'1lu·.....·- ...... - . _. )' ~
To understand the software basic concep!. underlymg mput r d ign
ter some very , be II d .
one must first mas d'tl'on of digital comput rs n h pIer
iem, hi h 10 the tra I d
I this chapter (w ic 'and coding 'yslems rc pre enre Iter an
On)the fundamentals of numbenng llew of the work 109 In rd the c mpul r is
, , I' gates, an overv " f' P
'ntroduetIon to ogle . we give a brief hi I ry o r hlle lure
I 'I' the last sectIOn , d f .
given, Fmal y, 10 have an adequale ba kgrourt 10 10'10) rh I pic
Although some,readers maYendcdthat the matcrial be 00 d. h wever bneny.
of Ihis chapter, It IS rccomIO

SECTION0.1: NUMBERING AND CODING SYSrE S


'ngs usc base 10 (de 1fI1I,{) ruhm II .. mpurc u
Whereas h uman bel .
rbebase 2 (binary) system. In this section we expl In h \\ 10 nv 'n fr Ih d _
imaI systemto the binary system, and VICCversa, Th nvem 01 rep :tll:tllon of
binarynumbers in base 16,called hexadecimal, I 0 I c v red 10.. 11, Ih bma-
ry formatof the alphanumeric code, called ASCII. IS pi n:d

Decimal and binary number systems


Although there has been speculation rh t Ih ' on '10 of th rem
is the fact that human beings have 10 fingers. th re I s IUlel
aboulthe reason behind the usc of the binarysystem In om pule Th
em is used in computers because I and 0 represent the I'" \ III
and off. Whcreas in base 10 therc arc 10 di lin I ym Is. O. I .••
therearc only two, 0 and J, with which to generate num r a
I
its 0 through 9; binary contains digits 0 and I only. Th 1\\ In
I, arc commonly referred to as bits.

Convertingfrom decimal to binary


be ~ne method of converting from de imollo blndry I I dlVI Ih
r 2 'elm I
D~ th y repeatedly, keeping track of the re/lUlllld'''' Thi pr
UDh e quohcnl becomcs zero Th . nllnu
10obtain Ihc binary number Th" , ~ remalndcn. re lh n \\ nil n In r \ rd r
Eumple 8-1 ' IS IS emonstraled In Empie 0-1

Convert 2510 to binary,

SoluMa:
Quot:ient
25/2 = 12 Rema:inder
12/2 = 6 1 LSB (leas
6/2 =
3
o 81 01 c n b1 )
3/2 =
1
o
1/2 = 1
o
1
MSB (moSt signi
Therefore,2510" Jl001 c 0 1t)

- --::------
2

-
Converting from binary to decimal 74068310
To convert from binary to decimal, it is
important to understand the concept of weight ~ 10°
~ 3
101 = 80
associated with each digit position. First, as an 6 x
102 = 600
analogy, recall the weight of numbers in the base 0 x
103 = 0000
10 system, as shown in the diagram. By the same 4 104
x = 40000
token, each digit position in a number in base 2 7 X 105 = 700000
has a weight associated with it: 740683

1101012 = Decimal Binary


1X20 = 1x1 = 1 1
OX21 = Ox2 = 0 00
2
1X2 = 1X4 4 100
3
OX2 = Ox8 = 0 0000
1x24 1X16 16 10000
1X25 = 1x32 = J2 100000
53 110101

Knowing the weight of each bit in a binary number makes it simple to add
them together to get its decimal equivalent, as shown in Example 0-2.

Example 0-2
Convert 110012 to decimal.

SOlution:
Weight: 16 8 4 2 1
Digits: 1 I 0 0 1
Sum: 16 + 8+ 0+ 0+ 1=2510

Knowing the weight associated with each binary bit position allows one to
convert a decimal number to binary directly instead of going through the process
of repeated division. This is shown in Example 0-3.

Example 0-3
Use the concept of weight to convert 39, 0 to binary.

Solution:
Weight: 32 16 8 4 2 1
1 0 0 I 1 1
32 + 0+ 0+ 4+ 2+ 1=39
Therefore, 3910 = 1001112,

CHAPTER 0: INTRODUCTION TO COMPUTING 3


Table 0-1: Base 16
Hexadecimal system Number Systems
Base 16, or the hexadecimal system as it is called in
computer literature, is used as a convenient representation Decimal Binary Hex
of binary numbers. For example, it is much easier for a o 0000 o
human being 10 represent a string of Os and I s such as 0001
100010010110 a its hexadecimal equivalent of896H. The 2 0010 2
binary ystem has 2 digits, 0 and I. The base 10 system has J 0011 J
10 digits, 0 through 9. The hexadecimal (base 16) system 4 0100 4
ha 16 digits. In base 16, the first 10 digits, 0 to 9, arc the 5 0101 5
same as in decimal, and for the remaining six digits, the let- 6 0110 6
ters A, B, C, D, E, and F are used. Table 0-1 shows the 7 0111 7
equivalent binary, decimal, and hexadecimal representa- 8 1000 8
tions for 0 10 15. 9 1001 9
10 1010 A
Converting between binary and hex 11 1011 B
. To represent a binary number as its equivalent hexa- 12 1100 c
decimal number, start from the right and group 4 bi ts at a 13 1101 o
lime, replacing cach 4-bit binary number with its hex equiv- 14 1110 E
alent shown III Table 0-1. To convert from hex to bi 15 1111 F
each h ex die:
Iglt IS rep Iaced with its 4-bit binary e uivalmary,
ee Examples 0-4 and 0-5. q cnt,

Example 0-4

Represent binary 100111110 I 0 I in hex.

Solution:
First the number is d .
Then each groupe. mto sets of 4 bits: 100 I I11I 0101
group of 4 bits IS replaced with its hex e . I .
1001 1111 0101 quiva ent:
9 F 5
Therefore, 100111110 I0 12 = 9F5 hexadecimal.

Example 0-5
Convert hex 29B to binary.
I Solulion:
2 9 B
Dropping the I~ding ~e~~~ gi 100 II0 II 0 II
ves 0011011
Converting from decimal to hex .
onvertmg from deCimal t h
I. Convert to bimary first and0 ex could be a
th pproaehed in two
method of conven: . en Convert to h ways:
2. C nvcn direetlye~lng ddeclmal to hex. ex. Example 0-6 shows this
. om eelmal to I b
remamders. Experimentin . lex y repeated divisio .
g With this method is left n, keepmg track of the
to the reader.
4
Example 0-6
(a) Convert 4510 to hex.

32 16 .8. 1 2 1 First, convert to binary.


I o 1 1 o I 32 + 8 + 4 + I ~ 45

(b) Convert 62910 to hex.

512 256 128 64 32 16 .8. 1 2 1


I 0 0 1 I I o I o I

62910,;, (512 + 64 + 32 + 16 + 4 + I) ~ 0010 01 J I 01012 = 275 hex

(c) Convert 171410 to hex.

1024 512 256 128 64 32' 16 .8. 1 2 1


1 101 0 I 1 o o 1 o

17141O~ (1024+512+ 128+32+ 16+2)=0110 ion 00102~682hex

Converting from hex to decimal


Conversion from hex to decimal can also be approached in two ways:
l. Convert from hex to binary and then to decimal. Example 0-7 demonstrates
this method of converting from hex to decimal.
2. Convert directly from hex to decimal by summing the weight of all digits.

Example 0-7

Convert the following hexadecimal numbers to decimal.

(a) 68216 ~ OlIO lOll 00102


1024 512 256' 128 64 32 16 .8. 1 2 1
I 1 o I o I I o o I o
1024 + 512 + 128 + 32 + 16 + 2 ~ 171410

(b) 9F2DJ6 = 1001 1111 0010 11012


32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 .8. 1 2 1
1 0 0 I I I I I 00 I 0 110 I

32768 + 4096 + 2048 + 1024 + 512 + 256 + 32 + 8 + 4 + 1= 40,749


10

CHAPTER 0: INTRODUCTION TO COMPUTING 5

7
Table 0-2: Counting in Bases . bases 10, 2 , and 16
Counting In
Decimal Binary Hex To show the relationship between all
o 00000 o . bl 0 2 we show the sequence
three bases, In Ta e - . d . I along with
00001 of numbers from 0 to 31 In ecimar,
2 00010 2 the equiva- Table 0-3: Binary Addition
3 00011 3 lent binary Sum
4 00100 4 A+ B Carry
5 00101 5 numbers. 0 I
6 00110 6 . 0+ I
Notice 111 0 I
7 00111 7 1+0
each base I 0
8 01000 8 that when 1.~+...!I
1 __ L;__ ..::....
__
9 01001 9 one more IS
10 01010 A added to
II 01011 B
the highest digit, that digit becomes zero and a
12 01100 C
I is carried to the next-highest digit position.
13 01101 o For example, in decimal, 9 + I = 0 with a carry
14 01110 E
15
to the next-highest position. In binary, I + I =
01111 F
16 10000
o with a carry; similarly, in hex, F + I = 0 with
10 a carry.
17 10001 II
18 10010 12 Addition of binary and hex numbers
19 10011 13
20 10100 14 The addition of binary numbers is a
21 10101 15 very straightforward process. Table 0-3 shows
22 10110 16 the addition of two bits. The discussion of sub-
23 10111 17 traction of binary numbers is bypassed since all
24 11000 18 computers usc the addition process to imple-
25 11001 19 ment SUbtraction. Although computers have
26 11010 IA adder circuitry, there is no separate circuitry for
27 11011 IB sUbtractors. Instead, adders arc used in con-
28 11100 IC junction with 2 s complement circuitry to per-
29 11101 ID form SUbtraction. In other words, to implement
30 11110 IE "x - y", the computer takes the 2's complement
31 11111 IF ofy and adds it to x. The concept of2's com-
plement is reviewed next. Example 0-8 shows
the addition of binary numbers.
Example 0-8

Add the following binary numbers. Cheek against their decimal equivalents.
Solution:

Binary
Decimal
1101
13
+ lllill
10110
-.2
22

6
·2's complement
To get the 2's complement of a binary number, invert all the bits and then
add I to the result. Inverting the bits is simply a matter of changing all Os to ls
and J s to Os. This is called the I :\'complement, See Example 0'-9,
Example 0-9
Take the 2's complement of JOOIIIOl.

Solution:
10011101 binary number
01100010 I's complement
+ 1
01100011 2's complement

Addition and subtraction of hex numbers


In studying issues related to software and hardware of computers, it is
often necessary to add or subtract hex numbers. Mastery of these techniques is
essential. Hex addition and subtraction are discussed separately below.
Addition of hex numbers
This section describes the process of adding hex numbers, Starting with the
least significant digits, the digits are added together. If the result is less than 16,
write that digit as the sum for that position, If it is greater than 16, subtract 16 from
it to get the digit and carry 1 to the next digit. The best way to explain this is by
example, as shown in Example O-JO,

Example 0-10
Perform hex addition: 2309 + 94BE,

Solution:
2309 LSD: 9 + 14 = 23 23 - 16 = 7 with a carry
+ 94BE I + 13 + II = 25 25 -16 = 9 with a carry
B897 1+3+4=8
MSD: 2+ 9=B

Subtraction of hex numbers


In subtracting two hex numbers, if the second digit is greater than the first,
borrow 16 from the preceding digit. See Example 0-11.
ASCII code
The discussion so far has revolved around the representation of number
systems, Since all information in the computer must be represented by Os and Is,
binary patterns must be assigned to letters and other characters, In the 1960s a
standard representation called ASCII (American Standard Code for Information
Interchange) was established, The ASCII (pronounced "ask-E") code assigns

CHAPTER 0: INTRODUCTION TO COMPUTING 7

7
bimary P attcrns
, for numbers 0 to 9, all the Hex Symbol Hex Symbol
letters of the English alphabet, both 41 A 61 a
uppercase (capital) and lowercase, and 42 B 62 b
many control codes and punctuation :~ C 63 c
marks, The great advantage of this sys- D 64 d
tem is that it is used by most computers, 59
y 79 y
so that information can be shared among 5A
computers, The ASCII system uses a Z 7A z
total of? bits to represent each code, For LF-igu-r-e
":'"0--1-, S=-e":'"le-e':-te"":d"":A-::S:::C::-n:-C;:-:-od;e:::s--
example, 100 0001 is assigned to the
uppercase letter "A" and 110 000 I is for "" ,
the lowercase "a", Often, a zero is placed in the most significant bit position to
make it an 8-bit code, Figure 0-1 shows selected ASCII codes, A complete list of
ASCII codes is given in Appendix F. The usc of ASCII is not only standard for
keyboards used in the United States and many other countries but also provides a
standard for printing and displaying characters by output devices such as printers
and monitors,
Notice that the pattern of ASCII eodcs was designed to allow for easy
manipulation of ASCII data, For example, digits 0 through 9 are represented by
ASCII eodcs 30 through 39, This enables a program to easily convert ASCII to
decimal by masking off the "3" in the upper nibble, Also notice that there is a rela-
tionship between the uppercase and lowercase letters, The uppercase letters arc
represcnted by ASCII codes 41 through 5A while lowercase letters arc represent-
ed by codes 61 through 7A, Looking at the binary code, the only bit that is differ-
ent between the uppercase "A" and lowercase "a" is bit 5, Therefore, conversion
between uppercase and lowercase is as simple as changing bit 5 of the ASCII code,
Example 0-11
Perform hex Subtraction: 59F 2B8,

olution:

59F
LSD: 8 from 15 ~ 7
- 2B8
2E7 J 1 1T0m 25 (9 + 16) = 14 (E)
21T0m4(5-1)=2
ReView Questions
I.
Why do computcrs use thc binary number system instead of the dcei nal
tern? I sys-
2, Convert 3410 to binary and hex,
3. Convert /10 I012 to hex and dccimal.
4, Pcrfonll binary addition: 101100 + 101.
5, Convert 101/002 to its 2 's complemcnt representation
6, Add 36BH + F6H, '
7, SUbtract 36BH _ F6H,
8, Write "80x86 CPUs" in its ASC/J code (in hex 1'0 )
rm).
8
4

SECTION 0.2: DIGITAL PRIMER

This section gives an overview of digital logic and design. First, we cover
binary logic operations, then we show gates that perform these functions. Next,
logic gates are put together to form simple digital circuits. Finally, we cover some
logic devices commonly found in microcontroller interfacing.
~--------,
Binary logic
Sf-
As mentioned earlier, computers use the
binary number system because the two voltage lev- 4 Logic I
els can be represented as the two digits 0 and l. 3f-
Signals in digital electronics have two distinct volt-
age levels. For example, a system may define 0 Vas 2f-
logic 0 and +5 V as logic I. Figure 0-2 shows this
system with the built-in tolerances for variations in· If-
the voltage. A valid digital signal in this example Logic 0
Of-
should be within either of the two shaded areas.

Figure 0-2. Binary Signals


Logic gates
Logical AND Function
Binary logic gates are simple circuits that
take one or more input signals and send out one out- Inputs Output
put signal. Several of these gates are defined below.
XY XANDY
00 0
AND gate oI 0
The AND gate takes two or more inputs and I0 0
performs a logic AND on them. See the truth table I 1 1
and diagram of the AND gate. Notice that if both
inputs to the AND gate are 1, the output will be I.
~:=:[)- X AND V
Any other combination of inputs will give a 0 output.
The example shows two inputs, x and y. Multiple Logical OR Function
outputs are also possible for logic gates. In the case Inputs Output
of AND, if all inputs are I, the output is I. If any
input is 0, the output is zero.: XY XORY
00 0
OR gate
011
The OR logic function will output a I if one 101
or more inputs is I. If all inputs are 0, then and only I 1 1
then will the output be O.
~=D-XORV
Tri-state buffer
Buffer
A buffer gate does not change the logic level
of the input. It is used to isolate or amplify the sig- X--j)-V
nal.
Control -J

CHAPTER 0: INTRODUCTION TO COMPUTING 9

___ c _
Inverter

The inverter, also called NOT, outputs the


value opposite to that input to the gate. That IS: a I Logical Inverter
input will give a 0 output, while a 0 input will give a
I output. Input Output
x NOT X
XORgate o
The XOR gate performs an exclusive-OR
o
operation on the inputs. Exclusive-OR produces a I x -{>o-- NOT X
output if one (but only one) input IS I. II both
operand arc 0, the output is zero. Likewise, if both
operands arc I, the output is also zero. Notice from Logical XOR Function
the XOR truth table, that whenever the two mpurs Inputs Output
arc the same, the output is zero. This function can be
used to compare two bits to sec if they arc the same. Xy X XOR Y
00 0
NAND and NOR gates o1 I
10 I
The NAND gate functions like an AND gate I I 0
with an inverter on the output. It produces a zero out-
put when all inputs are I; otherwise, it produces a I ~=D-XXORY
output. The NOR gate functions like an OR gate with
an inverter on the output. It produces a I if all inputs
arc 0; otherwise, it produces a O. NAND and NOR
gates arc used extensively in digital design because Logical NAND Function
they are easy and inexpensive to fabricate. Any cir- Inputs Output
cuit that can be designed with AND, OR, XOR, and
INVERTER gates can be implemented using only XY X NANDY
00 I
AND and NOR gates. A simple example of this is
given below. Notice in NAND, that if any input is oI I
zero, the output is one. Notice in NOR, that if any J 0 1
Input lone, the output is zero. I I 0

~=D-XNANDY
Logic design using gates

Next we will show a simple logic design to


add two binary digits. If we add two binary digits Logical NOR Function
there are four Possible Outcomes:
Inputs Output
X y X NOR Y
Carry Sum 00 1
0+0= 01
0+/=
o 0 0
1+0=
o 1 10 0

1+/=
o I I J 0
I 0
;=D-XNORY

10

-
2

Notice that when we add I + I we get 0 with a carry to the next higher
place. We will need to determine the sum and the carry for this design. Notice that
the sum column above matches the output for the XOR function, and that the carry
column matches the output for the AND function. Figure 0-3 (a) shows a simple
adder implemented with XOR and AND gates. Figure 0-3 (b) shows the same
logic circuit implemented with AND and OR gates. . .

X
x l--- Sum
Y ---'---I
Y -.--1-1-/
}---Sum
X---I
Y
'-_~----,)--- Carry
X-----.,
y-- }------- Carry

(a) Half-Adder Using XOR and AND (a) Half-Adder Using AND, OR, Inverters

Figure 0-3, Two Implementations of a Half-Adder

Figure 0-4 shows a block dia-


gram of a half-adder. Two half-adders X Sum
can be combined to form an adder that Half-
can add three input digits. This is called Adder
a full-adder. Figure 0-5 shows the logic y
Carry
diagram of a full-adder, along with a . out
block diagram that masks the details of
the circuit. Figure 0-6 shows a 3-bit F' 0-4 81 k 0' f H If d
. 3 full -a dd ers.
a dd er usmg igure . oc iagram 0 a a -Ad er

x X Half- Carry
y Sum y Adder

Sum

Half-
- C out
Adder Carry
C in
C in
Final Sum

Figure 0-5. Full-Adder Built from a Half-Adder

CHAPTER 0: INTRODUCTION TO COMPUTING 11


uecoaers
Another example of the application
of logl gates is the decoder. Decoders arc xo
widely u ed for address decoding In corn-
Full- r-----so
pUlcr. d ign Figure 0-7 shows decoders
. . for rt YO
Adder
9(1001 binary) and 5 (0101) usmg mvc _
Carry
rs nd A D gate .

Flip-flops
X1
A widely u cd component in digital Y1
Full· r-.-----S1
) ,Icm I the nip-nop. Frequently, nip- Adder
IIIlfl' Me u. cd to tore data. Figure 0-8 Carry
ho"" the logic diagram, block dIagram,
nd lrulh wble f r a nip-nop.
Thc 0 nip.nop (D-FF) is widely X2
u\(d to latch data. oucc from the truth Y2 Full- r-----_S2
I ble th(ll 0·1'1' grab the data at the input Adder Carry
Ihe clock is tivated. A D·FF holds the r-----_S3
d.1l long s the POwer is n. ';F;::j'::'gu:-r:-c';>O_-;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

() ddre, deCOder for 9 (binary 100 I) -{)o-


I he output of Ihe AND gate will be , (b) Address decoder for 5 (binary 0101)
II und only If Ihe Inpur i~ binary 100 I.
The output of the AND gate will be I
ifand only iflhe input is binary 0101.
OecOders

D
elk D
Q No
II. x
Ik 1- 0
1- I
Q
(~)
'rcull draglllm
Q - x .:::::
don', care

(b) BlOck diagram


(c) Truth table

-
/2

-
Review Questions
1. The logical operation gives a I output when all inputs are I.
2. The logical operation __ gives a 1 output when I or more of its inputs is I.
3. The logical operation __ is often used to compare if two inputs have the
same value .
. 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
word is two bytes, or 16 bits. The display is Nibble 0000
intended to show the relative size of these Byte 0000 0000
units. Of course, they could all be com- Word 0000 0000 0000 0000
posed 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 mem-
ory. 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 COIll-
puter 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
CPU
(monitor,
(RAM, ROM) printer, etc.)

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 supercom-
PU 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 connect-
ed 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
I
determines the number of locations with which it can communicate. The number
of locations is always equal to 2x, where x is the number of address lines, regard-
less of the size of the data bus. For example, a CPU with 16 address lines can pro-
vide 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-pur-
pose microprocessor CPUs are what is called byte addressable. As another exam-
ple, 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
example there would be 224
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 dis-
played 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 pack-
ages 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 trans-
h 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 control-
ling a machine such as a robot. It is the function of the CPU to fetch these instruc-
tions 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 reg-
isters. The CPU uses registers to store information temporari Iy. The informa-
tion 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 big-
ger the registers, the better the CPU. The disadvantage of more and bigger reg-
isters is the increased cost of such a CPU.
2. The CPU also has what is called theALU (arithmetic/logic unit). The ALU sec-
tion 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 fol-
lows.

Action Code Data


Move value 21H into register A BOH 21H
Add value 42H to register A 04H 42H
Add value 12H to register A 04H 12H

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 (BO)code for moving a value to register A
1401 (21)value to be moved
1402 (04)code for adding a value to regist'er A
1403 (42)value to be added
1404 (04)code for adding a value to register A
1405 (12)value to be added
1406 (F4)code for halt

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 CIr-
cuitry 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 instruc-
tion, the program counter points to the address of the next instruction to be exe-
cuted, 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 pro-
vidcs 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
fmstrucuon
th tells
' the CPU
, to stop incrementing the program counter and asking'
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, How many bytes is 24 kilobytes?
2. What docs "RAM" stand Cor? Ho ' ,
3. " , r W IS It u"ed '
W hat docs "ROM" stand f< ? H " s 111 computer systems?
4 Wh ' RA or, ow IS It used i '
. . Y IS M called volatile mcmor ') n computer systems?
5. List the three major com y,
6. What docs "CPU" t d ~onents of a computcr system
' san for? Explain it f' '
7, 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 num-
ber can be coded directly into its hexadecimal equivalent for the convenience of
humans. Converting from binary/hex to decimal, and vice versa, is a straightfor-
ward 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 com-
puter 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 com-
puter 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 19

7
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-I-
4DD991-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 ? .
(c) If ItS.
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) How many K is 1 meg?
(t) What is the exact value (in decimal) of I giga?
(g) How many K is I giga?
(h) How many meg is I giga?
(i) 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 infor-
mation. 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 loca-
tion 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 com-
puter, 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 fol-
lowing 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
off.
2. 3410 = 1000102 = 2216
3. 1101012=3516=5310
4. 1110001
5. 010100
6. 461
7. 275

CHAPTER 0: INTRODUCTION TO COMPUTING 21

7
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 run-
ning, such as the operating system, word processing programs, etc.
3. 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
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 infor-
mation in and out ofthe CPU; the control bus is used by the CPU 10 send signals controlling
I/O devices,
R. (aJ bidirectional (b) unidirectional
9. 64K. or 65,536 byres
10. Arithmetic/logic unit; it performs all arithmetic and logic operations
1I. It IS for temporary storage of information
12. It holds the address of the next instruclion to be executed,
13. It tells the CPU what steps to perform for each instruction,
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 micro-
controllers 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 AND EMBEDDED


PROCESSORS

In this section we discuss the need for microcontrollers and contrast them
with general-purpose microprocessors such as the Pentium and other x86 micro-
processors. 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 fami-
ly (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 com-
monly referred to as general-purpose microprocessors.

D ata b us
CPU
r I .i. I I
CPU RAM ROM
General-
Purpose RAM Serial
ROM VO Timer
Miero- COM
Port
processor Port I/O Timer Serial
T I I I I COM
Addresss bus Port

, 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 n-
ports needed to fit the t k h
trollers. A microcontroller has :scpa~
amOunt of RAM ROM I/O
td
. on e arnounr of RAM ROM
. This IS not the ease with mi~rocon~
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-' .
Home cal. In many applications, for example a TV remote control, there
Appliances is no need for the computing power of a 486 or even an 8086
Intercom microprocessor. In many applications, the space it takes, the
Telephones power it consumes, and the price per unit are much more critical
Security systems considerations than the computing power. These applications
Garage door openers most often require some I/O operations to read signals and tum on
Answering machines .'and off certain bits. For this reason some call these processors
Fax machines
lBP, "itty-bitty processors" (see "Good Things in Small Packages
Home computers
TVs Are Generating Big Product Opportunities" by Rick Grehan,
Cable TV tuner BYTE magazine, September 1994; www.byte.com, for an excel-
VCR lent discussion of microcontrollers).
Camcorder It is interesting to note that some microcontroller manu-
Remote controls facturers have gone as far as integrating an ADC (analog-to-digi-
Video games tal converter) and other peripherals into the microcontrolJer.
Cellular phones
Musical instruments Microcontrollers for embedded systems
Sewing machines
In the literature discussing microprocessors, we often see
Lighting control
Paging the term embedded system. Microprocessors and microcontrollers
Camera are widely used in embedded system products. An embedded
Pinball machines product uses a microprocessor (or microcontroller) to do one task
Toys and one task only. A printer is an example of embedded system
Exercise equipment since the processor inside it performs only one task; namely, get-
Office ting the data and printing it. Contrast this with a Pentium-based
Telephones PC (or any x86 IBM-compatible PC). A PC can be used for any
Computers number of applications such as word processor, print server, bank
Security systems teller terminal, video game player, network server, or internet ter-
Fax machine minal. Software for a variety of applications can be loaded and
Microwave run. Of course the reason a PC can perform myriad tasks is that it
Copier
has RAM memory and an operating system that loads the appli-
Laser printer
Color printer cation software into RAM and lets the CPU run it. In an embed-
Paging ded system, there is only one application software that. is typical-
Auto ly burned into ROM. An x86 PC contains or is connected to var-
Trip computer IOUS embedded products such as the keyboard, printer, modem,

Engine control disk controller, sound card, CD-ROM driver, mouse, and so on.
Air bag Each one of these peripherals has a microcontroller inside it that
ABS performs only one task. For example, inside every mouse there is
Instrumentation a microcontroller that performs the task of finding the mouse
Security system position and sending it to the Pc. Table I-I lists some embedded
Transmission control products.
Entertainment
Climate control X86 PC embedded applications
Cellular phone
Keyless entry Although microcontrollers are the preferred choice for
many embedded systems, there are times that a microcontroller is .
Table I-I: Some inadequate for the task. For this reason, in recent years many
Embedded Products manufacturers of general-purpose microprocessors such as Intel,
Using
Freescale Semiconductor Inc. (formerly Motorola), AMD
Microcontrollers
(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 com-
puter 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 general-
purpose 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 fea-
Norn 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
ondary cache memory. New designs are erne . . . '
I~;
et eon-
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 high-
t' . 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.

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
not compatible w'th nlque instruction set and reoi
T~~tei Freeseale's 6811,
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 mak-
meeling 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.
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 prod-
ucts.
(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-con-
sumption 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 devel-


op products around it. Key considerations include the availability of an assem-
bler, debugger, a code-efficient C language compiler, emulator, technical sup-
port, and both in-house and outside expertise. In many cases, third-party ven-
dor (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 (multi-
ple 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 It should be noted that
Member of the 8051 Family . Freescale, Zilog, and Microchip
Technology have all dedicated
Company Web Site massive resources to ensure wide
Intel www.intel.com/design/mcs5l and timely availability of their
Atmcl www.atmel.com product since their product is sta-
Philips/Signetics www.semiconductors.philips.com ble, mature, and single sourced.
Infineon www.infineon.com In recent years they also have
Dallas SemilMaxim www.maxim-ic.com begun to sell the ASIC library
cell of the microcontroller.

CHAPTER 1: THE 8051 MICROCONTROLLERS 27


Review Questions . than microproees-
True or false. Mieroeontrollers are normally less expensive
I.
sors. . .
b d based on a microcontru IIer an d a general-pur-
2 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
4. A general-purpose mlerop;oeessor norma y
II

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 man-
ufacturers 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 proecs-
or, 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
the manufacturer. g ss of RAM 128 byte
Timer 2
8051 microcontroller I/O pins 32
Serial port I
The 8051 i the original memb f
ily. Intel refers to it as MCS-51 T bl ~r 0 the 8051 fam. Interrupt sources 6
features of the 8051. . a e -3 shows the main Note' . ROM amounlmdlcates
'. on-chip
pl"Ogram space.
28
EXTERNAL
INTERRUPTS

ON-CHIP o
Y 't ROM o
c
INTERRUPT 1--._. . for ETC ~
__ .. program
CONTROL
'-----,-----'-
~.
.-- code
ON-CHIP
RAM
TIMER 0 f-oc--} - g]
TIMER 1 _- Z
I • '?-
1J
c
Y oJ
~
IA I
CPU
\
A A .lJ
BUS
~
4 I/O
~7
SERIAL
CONTROL PORTS PORT

I
A
t .~
f t f
PO P2 P1 P3
I
Y
TXD RXD
I
...... .
-
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 stan-
dard 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 8052 8031
ROM (on-chip program space in bytes) 4K 8K OK
RAM (bytes) 128 256 128
Timers 2 3 2
I/O pins 32 32 32
Serial port 1
Interrupt sources 6 8 6

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 pro-
I. 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 differ-
ent 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 ver-
sion 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 ver-
sion 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
where Nextarcweused.
discuss briefly each of the above chips and describe applications

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 eras-
er to crase the COntentsof UV-EPROM inside the 8751 chi b C
gram It. agarn.
. Beeausc the on-Chip . ROM for the 875/ is tpUV-EPROM
e,ore you can pro-
it takes
around
Id 20 mmutes to erase the 8751 before it can be d' ' .
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 memo-
This 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
hem eve °pment time. Using the AT89C5 I to devel_
reqUires a ROM b
mcmory; owevcr, a ROM crase'" umcr that sUpports flash
30 r IS not ncedcd. Notice that in flash mCm
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 devel-
opment system. Dallas Semiconductor also has an NV-RAM version of the S051
called DS5000.I
The advantage ofNV-RAM is. the ability to change the ROM con-
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 RAM I/O pins Timers Interrupts Vee
DSS9C420/30 16K (Flash) 256 32 3 6 5V
DSS9C440 32K (Flash) 256 32 3 6 5V
DSS9C450 64K (Flash) 256 32 3 6 5V
DS5000 SK (NVRAM) . 12S 32 2 6 5V
DSSOC320 0 K 256 32 3 6 5V
DSS7520 16K (UVROM) 256 32 3 6 5V
Source: www.maxim-ic.comlproducts/microcontrollers/S051_ 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 -
Vce Packaging
- ROM RAM I/O pins Timer Interrupt
Part Number 5V 40
'A'T89C51 4K 128 32 2 6 40
3V
AT89LV51 4K 128 32 2 6 20
3V
AT89CIOSI IK 64 15 I 3 20
3V
AT89C20S1 2K 128 IS 2 6 40
5V
AT89C52 8K 128 32 3 8 40
3V
AT89LV52 8K 128 32 3 8
Note: "C" in thc part number indicates CMOS.

Table 1-7: Various Speeds of 8051 From Atmel

Part Number Speed Pins Packaging Use


AT89C51-12PC 12 MHz 40 DIP plastic commercial
AT89CSI-16PC 16 MHz 40 DIP plastic commercial
AT89C51-20PC 20 MHz 40 DIP plastic commercial

OTP version of the 8051


There are also OTP (one-time-programmable) versions of the 805 t avail-
able 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. .,
Iy see thc We b sues
si . h
m t c box below. rarrn

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
, ,,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 com-
pared. We discussed the use of microcontrolJers in the embedded market. We also
discussed criteria to consider in choosing a microcontroller such as speed, memo-
ry, 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 AND EMBEDDED PROCESSORS

I. True or False, A general-purpose microprocessor has on-chip ROM.


2. True or False. A microcontroller has on-chip ROM.
3. True or False. A microcontrotler has on-chip I/O ports.
4. True or False. A microcontroller has a fixed amount of RAM on the chip.
5. What components are normally put together with the microcontroller into a
single chip?
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 ,

13. matter? . ortant is it to have multiple ouree


In choosing a microcontroller, how Imp for
I· ')
that Clip. " ?

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. A l1licrocontrollcr.bascdsystem
J. (d)
4. (d)
5. II is dediealed since it is dediealed I d .
6.
7
Embedded syslem mcam that th °1lcallon
, omg one Iype of job.
'I' I. e app 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. 128 bytes of RAM, 4K bytes of on-ehip ROM, [our 8-bit JlO pons.
2. 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.
3. Both the 8051 and the 8031 have 128 bytes of RAM and the 8052 has 256 bytes.
4. (a) 4K bytes (b) 8K bytes (c) OK bytes
5. 8
6. The main difference is the type of on-chip ROM. III the 8751 it is UV-EPROM; in the
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

- CHAPTER 1: THE 8051 MICROCONTROLLERS 35

___ ...-z _
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 pro-
gramming 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 pro-
gram 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 arith-
metic 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, reg-
isters 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
r------=--~ A endi specia registers 111 future chapters, See
pp x A.2 for a complete list of 8051 .
I A .
I registers,

I B I DPTR
I RO I [_D_PH_I DPL

I RI I -----
PC
\ R2 I [ PC (program counter)

I R3 ] F'
Igure 2-1 (b). Some 8051 16-b't R .
I R4 ]

I Rsl
J
The most widel .
a\<cUm"I"fiO' D bOY used registers of the 8051
l
[
R6~''D

R7
]
l 1IJ l'lt
J
iIt._ ..", • RI R2 R
pointer), and Pc ' 3, R4, R,
0fhe above registers arc 8 ,{p gram COUn er . All
arc
6, R7,

'";1:::~-:-:-:----
1
program COUnter Iieaccuml-OilS, exce(lt DPTR a n d tne
fo' h
Figure 2-1 (a), Some 8-bit rail arithmetie and 10 ' , u ator, reglste A is used
Registers or the 8051 the use of th esc registersglc Instructions
. '
,0 understand
Context oftw' .' we will show th .
o Simple Instructions Mo em In the
38 , Vand ADD.
MOV instruction

Simply stated, the MOV instruction copies data from one location to anoth-
er, It has the following format:

MOV destinatlon,source ;copy source to dest.

This instruction tells the CPU to move (in reality, copy) the source operand
to the destination operand, For example, the instruction "MOV A, RO" copies the
contents of register RO to register A, After this instruction is executed, register A
will have the same value as register RO, The MOV instruction does not affect the
source operand, The following program first loads register A with value 55H (that
is 55 in hex), then moves this value around to various registers inside the CPU,
Notice the "#" in the instruction, This signifies that it is a value, The importance
of this will be discussed soon,

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


MOV RO,A ;copy contents of A into RO
; (now A=RO=55H)
MOV Rl,A ;copy contents of A into Rl
; (now A=RO=Rl=55H)
MOV R2,A ;copy contents of A into R2
;now A=RO=Rl=R2=5SH)
MOV R3,#95H ;load value 95H into R3
; (now R3=95H)
MOV A,R3 ;copy contents of R3 into A
;now A=R3=95H)

When programming the 8051 rnicrocontroller, the following points should


be noted:
I, Values can be loaded directly into any of registers A, B, or RO - R7, However,
to indicate that it is an immediate value it must be preceded with a pound sign
(#). This is shown next.

MOV A,#23H ;load 23H into A (A=23H)


MOV RO,#12H ;load 12H into RO (RO=12H)
MOV Rl,#lFH ;load IFH into Rl (Rl=lFH)
MOV R2,#2BH ;load 2BH into R2 (R2=2BH)
MOV B,#3CH ;load 3CH into B (B=3CH)
MOV R7,#9DH ;load 9DH into R7 (R7=9DH)
MOV R5, #OF9H ;load F9H into R5 (R5=F9H)
MOV R6,#12 ;load 12 decimal (OCH)
;into reg. R6 (R6=OCH)

otice in instruction "MOV R5, #0 F9H" that a 0 is used between the # and
F to indicate tbat F is a hex number and not a Ie er. In other words "MOV
R5, #F9H" will cause an error,

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 39


2. If values 0 to F are moved into an 8-bit register, the rest of the bits are assumhed
to be all zeros. For example, in "MOV A, #5" the result will be A = 05; t at
is, A = 00000 I0 I in binary.

3. Moving a value that is too large into a register will cause an error.
MOV A,#7F2H ;ILLEGAL: 7F2H > 8 bits (FFH)
MOV R2,#456 ;ILLEGAL: 456 > 255 decimal (FFH)

4. A value to be loaded into a register must be preceded with a pound sign (#).
Otherwise it means to load from a memory location. For example "MOV
A, 17H"means to move into A the value held in memory location 17H, which
could have any value. In order to load the value 17H into the accumulator we
must write "MOV A, # 1 7H"with the # preceding the number. Notice that the
absence of the pound sign will not cause an error by the assembler since it is a
valid instruction. However, the result would not be what the programmer
intended. This is a common error for beginning programmers in the 8051.
ADD instruction
The ADD instruction has the following format:

ADD A,source
;ADD the Source operand
;to the accumulator

The ADD instnletion tells the CPU to add the Source byte to register A and
put
b the result In register A. To add two numbers such as 25H and 34H h
e move d to a register
. and then added together: ,cae can

MOV A,#25H
;load 25H into A
MOV R2,#34H
ADD A,R2 ;load 34H into R2
;add R2 to accumulator
; (A = A + R2)

- Executing the program above results in A = 59H (25H + 34 =


R2 - 34H. Notice that the Content of R2 d h H 59H) and
be wntrcn
. .111 many ways depending 0 Ih'oes not c ange .' The p rogram a b ove can
' n e registers used. Another way might be:
MOV RS,#25H 'load 2SH .
MOV R7 #34H
, . oad 34H Into
'1
. R5 (R5=25H)
MOV A #0
ADD A,R5
,
'
'load
: dd
°. Into R7 (R7=34H)
Into A (A=O,clear A)
,a to A Content of R5
ADD A,R7 ;where A = A + R5
;add to A Content of R7
;where A = A + R7
. The program above reSUlts in A _
wruc the same program One . - 591-1.There are always many w
pro b . question that might ays to
gram a ovc, is Whether it is neeess COmeto mind after looking at the
40 ary to move both data items into registers
before adding them together. The answer is no, it is not necessary. Look at the fol-
lowing variation of the same program:

MOV A,#25H ;load one operand into A (A~25H)


ADD A,#34H ;add the .second operand 34H to A

In the above case, while one register contained one value, the second value
followed the instruction as an OReland. This is calle an immediate 0 erand. The
examples shown so far for the 00' nstructi n indicate that the source 0 erand
can be either a register or immediate data, but the destination must w ys be rcg
list r , he accumulator. n other words, an instruction such as "ADD R2, #12H"
is invalid since register A (accumulator) must be involved in any arithmetic oper-
ation. Notice that "ADD R4,A" is also invalid for the reason that A must be the
destination of any arithmetic operation. To put it simply: In the 8051, register A
must be involved and be the destination for all arithmetic operations. The forego-
ing discussion explains why register A is referred to as the accumulator. The for-
mat for Assembly language instructions, descriptions of their use, and a listing of
legal operand types are provided in Appendix A.I.
There are two 16-bit registers in the 8051: PC (program counter) and
OPTR (data pointer). The importance and use of the program counter are covered
in Section 2.3. The OPTR register is used in accessing data and is discussed in
Chapter 5 where addressing modes are covered.

Review Questions
I. Write the instructions to move value 34H into register A and value 3FH into
register B, then add them together.
2. Write the instructions to add the values 16H and COHo Place the result in reg-
ister R2.
3. True or false. No value can be moved directly into registers RO - I3-7.
4. What is the largest hex value that can be moved into an 8-bit register? What is
the decimal equivalent of the hex value?
5. The vast majority of registers in 8051 are __ bits.

SECllON 2.2: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING

In this section we discuss Assembly language format and define some.


widely used terminology associated with Assembly language programming.
While the CPU can work only in binary, it can do so at a very high speed.
For humans, however, it is quite tedious and slow to deal with Os and Is in order
to program the computer. A progJ.:amthat consists of Os and Is is called machine
/anguag In the early days of the computer, programmers coded programs in
machine language. Although the hexadecimal system was used as a more efficient
way to represent binary numbers, the process of working in machine code was still
cumbersome for humans. Eventually, Assembly languages were developed that
provided mnemonics for the machine code instructions, Ius other features that
made programming faster and less rone to error. [Ihe term mnemonic is frcque t-
IXused in comguter science and engineering literature to refer to codes and abbr -

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 41

__ .dtn-.__
viations that arc relatively easy to--lG!!!£.mber.ssembly language rograms must
be translated into machine code by a program called an assemoler Assembl J -
uage is referred 10as a 10 Ilanlmage because it deals directly with the inter-
nal tructure of the CPU. To program in Assembly language, the programmer must
know all the registers of the CPU and the size of each, as well as other dctai Is.
Today, one can use many different programming languages, such as
SA IC. Pascal. C, CH. Java>rnd numerous others. These languages are called
high-level languages cause t rogJ!mmer ooes not ha e toJ>~ cgneemed with
the internal details of the CPU. hereas an assembler is used to translate an
Assembly language program into machiPc code (somcti also called object
code or opcode for operation c~e), high- evel anguages are translated int
rftiIehinecode by a program called a compil . For instance, to write a program in
, one must usc a C compiler to trans ate t e program into machine language. Now
we look at 805I Assembly language format and use an 8051 assembler to create a
ready-to-run program.

Structure of Assembly language


, An Assembly language program consists of, among other things, a series
of lines of Assembly language instructions. An Assembly language instruction
consists of a mnemonic, optionally followed by one or two operands. The
operands arc the data Items being manipulated, and the mnemonics arc the com-
mands to the CPU, tellIng it what to do with those items.

ORG OH ;start (origin) at location


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

Program 2-1: Sample of an Assembly L


anguagc Program
A given Assembly language pro
rnents, or lines, which are either Assem~ra~~see Program 2-1) is a series of state-
MOV,. or statements called directives W~. guage Instructions such as ADD and
directives (al 0 called ps do-:
::I:~PI~~ .
"
SJ~v~
lie InstructIOns tell the CPU h
eu O-Instructlon)'
:~et~p~o~e program while the
,
~;;~~i~~
w at to do
to the assembler. Fo;
, RG and END arc direct'. . II1struCtionsare com-
42 rves to the assembler. ORG tells the
assembler to place the opeode at memory location 0 while END indicates to the
assembler the end of the source code. In other words, one is for the start of the pro-
gram and the other one for the end of the program.

An Assembly language instruction consists of four fields:

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

Brackets indicate that a field is optional, and not all lines have them.
Brackets should not be typed in. Regarding the above format, the following points
should be noted.

I. The label field allows the program to refer to a line of code by name. Thc label
field cannot exceed a certain number of characters. Check your assembler for
the rule.

2. The Assembly ianguage mnemonic (instruction) and operand/s) fields togeth-


er perform the real work of the program and accomplish the tasks for which
the program was written. In Assembly language statements such as

ADD A, B
MOV A, #67

ADD and MOY are the mnemonics, which produce opcodes; and "A, B" and
"A, #67" are the operands. Instead of a mnemonic and an operand, these two
fields could contain assembler pseudo-instructions, or directives. Remember
that directives do not generate any machine code (opeode) and are used only
by the assembler, as opposed to instructions that are translated into machine
code (opcode) for the CPU to execute. In Program 2-1 the commands ORG
(origin) and END are examples of directives (some 8051 assemblers usc .ORG
and .END). Check your assembler for the rules. More of these pseudo-instruc-
tions are discussed in detail in Section 2,5.

3. The comment field begins with a semicolon comment indicator ";".


Comments may be at the end of a line or on a line by themselves, The assem-
bler ignores comments, but they are indispensable to programmers, Although
comments are optional, it is recommended that they be used to describe the
program and make it easier for someone else to read and understand, or for the
programmer to remember what they wrote.

4. Notice the label "HERE" in the label field in Program 2-1. Any label referring
to an instruction must be followed by a colon symbol, ":". In the SJMP (short
jump instruction), the 8051 is told to stay in this loop indefinitely, If your sys-
tem has a monitor program you do not need this line and it should be deleted
from your program, In the next section we will see how to create a ready-to-
run program.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 43


Review Questions
. ?
I What is the purpose of pseudo-instructions. .
2.. are translated by the assembler into mach me code, whereas
are not.
J. -T-ru-e-o-rccfa-cls-e-.
A-:-s-s-em~blylanguage is a high-Ievcllanguage.
4. Which of the following produces opcode? OH (d) SJMP HERE
(a) ADD A,R2 (b) MOV A,#12 (c) ORG 200
5. Pseudo-instructions arc also called CU. If Th
6. True or false. Assembler directives are not used by the P itsclt. ey are
simply a guide to the assembler.
7. In question 4, which one is an assembler directive?

SECTION 2.3: ASSEMBLING AND RUNNING AN 8051


PROGRAM

Now that the basic form of an Assembly language program has been given,
the next question is: How it is created, assembled, and made ready to run? The
steps 10 create an executable Assembly language program are outlined as follows.

I. First we use an editor to type in a ED1TOR


program similar to Program 2-1. PROGRAM
Many excellent editors or word myfilc .asm
processors are available that can be
used to create and/or edit the pro-
ASSEMBLER
gram. A widely used editor is the
PROGRAM
MS-DOS EDIT program (or
Notepad in Windows), which comes my/ile. ISI.J
with all Microsoft operating systems.
Notice that the editor must be able to
my lile.obj
produce an ASCII file. For many
assemblers, the file names follow the
r
LINKER
OI her obj f les

usual DOS conventions, but the PROGRAM


source file has the extension 'as"!"
r "src", depending on which assco-
bier you are using. Check YOur
+
mynle.abs
a sembler for the convention. The
"asm" extension for the SOurce file is ~
used by an assembler in the next OH
step.
PROGRAM

2. The "asm'' so fil


urce 1 e Containing the +
my/ile.hex
program code created in step I is fed
to an 8051 assembler. The assembler
conVerts Ihe instructions into Figure 2-2. Steps to Create a Program

44
machine code. The assembler will produce an object file and a list file. The
extension for the object file is "obj' while the extension for the list file is "lst".

3. Assemblers require a third step called linliing. The liii:Kprogram taRes one or
more object files ana produces an a5soluteobject file with the extension "abs".
This ab de is used by 8051 trainers t at have a monitor program.

4. Next, the "abs" file is fed into a program called "OH" (object to hex convert-
er), which creates a file with extension "hex" that is ready to burn into ROM.
This program comes with all 8051 assemblers. Recent Windows-based assem-
blers combine steps 2 through 4 into one step.

More about "asm" and "obj" files


The "asm" file is also called the source file and for this reason some asscm-
biers require that this file have the "src" extension. Check your 8051 assembler to
see which extension it requires. As mentioned earlier, this file is created with an
editor such as DOS EDIT or Windows Notepad. The 8051 assembler converts the
asm file's Assembly language instructions into machine language and provides the
obj (object) file. In addition to creating the object file, the assembler also produces
the lst file (list file).

1stfile
The 1st (list) file, which is optional, is very useful to the programmer
because it lists all the ope odes and addresses as well as errors that the assembler
detected. Many assemblers assume that the list file is not wanted unless you indi-
cate that you want to produce it. This file can be accessed by an editor such as
DOS EDIT and displayed on the monitor or sent to the printer to produce a hard
copy. The programmer uses the list file to find syntax errors. It is only after fixing
all the errors indicated in the lst file that the obj file is ready to be input to the link-
er program.

1 0000 ORG OH ;start (origin) at 0


2 0000 7D25 MOV R5,#25H ;load 25H into R5
3 0002 7F34 MOV R7,#34H ;load 34H into R7
4 0004 7400 MOV A,#O ;load 0 into A
5 0006 2D ADD A,R5 ;add contents of R5 to A
;now A = A + R5
6 0007 2F ADD A,R7 ;add contents of R7 to A
;now A = A + R7
7 0008 2412 ADD A, #12H ;add to A value 12H
;now A = A + 12H
8 OOOA 80FE HERE: SJMP HERE ;stay in this loop
9 oooe END ;end of asm source file

Program 2-1: List File

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 45


Review Questions
True or false. The DOS program EDIT produces an ASCII ,~Ie." "src"
~: True or false. Generally, the extension °df thedsbourtehefi 11eE~~
l s p~~gram~
Which of the following files can be pro uce y e o O S .
3. (a) myprog.asrn (b) myprog.obj (c) myprog.exe (d) myprog.lst ry
Which of the following files IS produced hy an.8.051 assemblIT.
4. (a) myprog.asm (b).!!1yprog.obj (c) myprog.hex (d) myprog.lst
5. Which of the following files lists syntax errors? (d) It
(a) myprog.asm (b) myprog.obj (c) myprog.hex myprog. s

SECTION 2.4: THE PROGRAM COUNTER AND ROM


SPACE IN THE 8051

In this section we examine the role of the program counter (PC) register in
executing an 8051 program. We also discuss ROM memory space for various 8051
family members.

Program counter in the 8051


Another important register in the 8051 is the PC (program counter). The
program counter points to the address of the next instruction to be executed. As the
CPU fetches the opcodc from the program ROM, the program counter is incre-
mcnted to point to the next instruction. The program counter in thc 8051 is 16 bits
wide. This means that the 8051 can access program addresses 0000 to FFFFH, a
total of 64K bytes of code. However, not all members of the 8051 have the entire
64K bytes of on-chip ROM installed, as we will see soon. Where does the 8051
wake up when it is powered? We will discuss this important topic next.

Where the 8051 wakes up when it is powered up


One question that we must ask about any microcontroller (or microproces-
sor) is: At what address does the CPU wake up upon applying power to it? Each
microprocessor is different. In the case of the 8051 family (that is, all members
regardless of the maker and variation), the microcontroller wakes up at memory
address 0000 when it is powered up. By powering up we mean applying Vee to
the RESET pin as discussed in Chapter 4. In other words, when the 8051 is pow-
ered up, the PC (program counter) has the value of 0000 in it. This means that it
expects the first ope ode to be stored at ROM address OOOOH. For this reason in the
8051 system, the first opcode must be burned into memory location OOOOH of pro-
gram ROM smce this IS where it looks for the first instruction when it is booted.
We achieve. this by the ORG statement in the source program as shown earlier.
Next, we diSCUSSthe step-by-step action of the program counter in fctchin and
executll1g a sample program. g

Placing code in program ROM

To get a better understanding or the role of the progra n tcr i C


.111g an d executIng
. a program we examine the act' f h I coun cr 111 retch,
each instruction is fetched and executed Fi st Ion 0 t e program counter as
. rsr, we examine once more the list file
of the sample program and how the code is placed in the ROM of an 80S I chip.
As we can see, the opcode and operand for each instruction are listed on the left
side of the list file.

1 0000 ORG OH ;start at location a


2 0000 7025 MOV R5,#25H ;load 25H into R5
3 0002 7F34 MOV R7,#34H ;load 34H into R7
4 0004 7400 MOV A,#O ;load a into A
5 0006 20 ADD A,R5 ;add contents of R5 to A
inow A = A + R5
6 0007 2F ADD A,R7 ;add contents of R7 to A
inow A = A + R7
7 0008 2412 ADD A,#12H ;add to A value 12H
;now A = A + 12H
8 DaDA 80FE HERE: SJMP HERE ;stay 1n this loop
9 DaDe END ;end of asm source file

Program 2-1: List File


ROM Address Machine Language Assembly Language
0000 7025 MOV R5, #25H
0002 7F34 MOV R7,#34H
0004 7400 MOV A,#O
0006 20 ADD A, R5
0007 2F ADD A,R7·
0008 2412 ADD A, #12H
OOOA 80FE HERE: SJMP HERE

After the program is burned into ROM of an 80S 1 family member such as
875 I or AT89S 1 or DSSOOO, the opcode and operand are placed in ROM memory
locations starting at '0000 as shown in the list below.
The list shows that address 0000 con-
tains 7D, which is the opcode for moving a Program 2-1: ROM Contents
value into register RS, and address 000 J con- Address Code
tains the operand (in this case 2SH) to be 0000 7D
moved to RS. Therefore, the instruction "MOV 0001 25
R5, #25H" has a machine code of "7D2S", 0002 7F
where 7D is the opcode and 25 is the operand. 0003 34
Similarly, the machine code "7F34" is located 0004 74
in memory locations 0002 and 0003 and rep- 0005 00
resents the opcodc and the operand for the 0006 2D
instruction "MOV R7, #34H". In the same 0007 2F
way, machine code "7400" is located in mem- 0008 24
ory locations 0004 and 0005 and represents 0009 12
the opcode and the operand for the instruction OOOA 80
"MOV A, #0".The memory location 0006 has 0008 FE
the opcode of 2D, which is the opcode for the

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 47


instruction "ADD A, RS" and memory location 0007 has the content 2F,. wh,i,ch is
the opcode for the "ADD A, R7" instruction. The opcode for the mstrucnon ADD
A #12H" is located at address 0008 and the operand 12H at address 0009. The
memory location OOOAhas the ope ode for the SJMP instruction and its target
address is located in location OOOB. The reason the target address IS FE IS
explained in the next chapter.

Executing a program byte by byte


Assuming that the above program is burned into the ROM of an 8051 chip
(or 8751, AT895I, or DS5000), the following is a step-by-step description of the
action of the 8051 upon applying power to it.

I. When the 8051 is powered up, the PC (program counter) has 0000 and starts
to fetch the first opcodc from location 0000 of the program ROM. In the case
of the above program the first opeode is 70, which is the code for moving an
operand to R5. Upon executing the opcode, the CPU fetches thc value 25 and
places it in R5. Now onc instruction is finished. Then the program counter is
incremented to point to 0002 (PC = 0002), which contains opcode 7F, the
opcode for the instruction "MOV R7, .. ".
2. Upon cxeeuting the ope ode 7F, the value 34H is moved into R7. Then the pro-
gram counter is incremented to 0004.
3. ROM location 0004 has the opeodc for thc instruction "MOV A, #0". This
instruction is executed and now PC = 0006. Notice that all the above instruc-
tions arc 2-byte instructions; that is, each one takes two memory locations.
4. Now PC = 0006 points to the next instruction, which is "ADD A, RS". This is
a l-byte instruction. After the execution of this instruction, PC = 0007.
5. The location 0007 has the opeode 2F, which belongs to the instruction "ADD
A, R7". This also is a l-bytc instruClion. Upon execution of this instruction
PC is incremented to 0008. This process goes on until all the instructions are
fetched. and executed. The fact that the program counter points at the next
msrrucnon to be executed explains why some microprocessors (notably the
x86) call the program counter the ins/ruction pointer.

ROM memory map in the 8051 family

. As we saw in the last chapter, some family members have only 4K bytes
of on-chip ROM (e.g., 8751, AT895 J) and some, such as the AT89C52 have 8K
bytes of ROM. Dallas Semiconductor's DSSOOO-32 h 32K b ' .
ROM . 0 a llas Semi -
as emlconduetor also has an 8051 with 6'4K bas ytcs of . on-chIp
Th·· I f '1 ytes of on-chip ROM .
e pomt to remember IS that no member of the 8051
64K bytes of opcode since the program counter' ami y can access more than
(0000 to FFFF address range). It must be noted th~tn:he 8051 IS a 16-~lt register
gram ROM inside the 8051 has the address of 0000 hile the first location of pro-
ferent depending on the size of the ROM h ' the last locatior, can be dif-
members, the 875 J and AT895 J have 4K b on t fe chiP: Among the 8051 family
0
ROM memory has memory addresses of06~~St O~~ChIP ROM. This 4K bytes of
lion of on-chip ROM of this 8051 h 0 FH. Thereforc, the first loca-
the address ofOFFFH. Look at E as tc ;ddress 01'0000 and the last location has
xarnp e -I to see how this is computed.
48
Example 2-1

Find the ROM memory address of each of the following 8051 chips.
(a) AT89C51 with 4KB (b) DS89C420 with 16KB (c) DS5000-32 with 32KB

Solution:

(a) With 4K bytes of on-chip ROM memory space, we have 4096 bytes' (4 x 1024 =
4096). This maps to address locations of 0000 to OFFFH. Notice that 0 is always
the first location. (b) With 16K bytes of on-chip ROM memory space, we have
16,384 bytes (16 x 1024 = 16,384), which gives 0000 - 3FFFH. (c) With 32K bytes
we have 32,768 bytes (32 x 1024 = 32,768). Converting 32,768 to hex, we get
8000H; therefore, the memory space is 0000 to 7FFFH.

0000
.. byte
..
0000
.. byte
. ,.
byte
..
0000

OFFF '--- __ ---J

8051
AT89C51 3FFF

DS89C420/30

7FFF
'------'
DS5000-32

Figure 2-3. 8051 On-Chip ROM Address Range


Review Questions
I. In the 8051, the program counter is bits wide.
2. True or false. Every member of the 8051 family, regardless of the maker,
wakes up at memory OOOOHwhen it is powered up.
3. At what ROM location do we store the first opcode of an 8051 program?
4. The instruction "MOV A, #44H" is a -byte instruction.
5. What is the ROM address space for the 8052 chip?g ~13

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES

In this section we look at some widely used data types and directives sup-
ported by the 8051 assembler.

8051 data type and directives


The 8051 microcontroller has only one data type. It is 8 bits, and the size
of each register is also 8 bits. It is the job of the programmer to break down data

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 49


larger than 8 bits (00 to FFH, or 0 to 255 in decimal) to be processed by the CPU.
For examples of how to process data larger than 8 bits,. see Chapter 6. The data
types used by the 8051 can be positive or neganvc. A discussion of SIgned num-
bers is given in Chapter 6.

DB (define byte)
The DB directive is the most widely used data directive in the assembler.
It is used to define the 8-bit data. When DB is used to define data, the numbers can
be in decimal, binary, hex, or ASCII formats. For decimal, the "D" after the deci-
mal number is optional, but using "B" (binary) and "H" (hexadecimal) for the oth-
ers is required. Regardless of which is used, the assembler will convert the num-
bers into hex. To indicate ASCII, simply place the characters in quotation marks
('like this'). The assembler will assign the ASCII code for the numbers or charac-
ters automatically. The DB directive is the only directive that can be used to define
ASCII strings larger than two characters; therefore, it should be used for all ASCII
data definitions. Following are some DB examples:

ORG 500H
DATAl: DB 28 ;DECIMAL(lC in hex)
DATA2: DB 00110101B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 510H
DATA4: DB 11259111 ;ASCII NUMBERS
ORG 518H
DATA6: DB "My name is Joel! ;ASCII CHARACTERS

Either
C'
single or double
.
quotes can be used around ASCII strings . Thi1 scan
b e use ful tor stnngs, which contain a single quote such as "O'Leary". DB is also
used to allocate memory in byte-sized chunks.

Assembler directives

The following arc some more widely used directives of the 8051.

ORG (origin)

The ORG directive is used to indicate the be' .


number that comes after ORG can be cith . h ginning of the address. The
er 111 ex or In dee' I If h
not followed by H, it is decimal and the assernbl . una .. t e number is
assemblers usc" . ORG" (notice the dot) instead ofe,~wllI"convert tl to hex. Some
heck your assembler. ORG for the ongin dIrective.
EQU (equate)

This . is used
. to define a constant WIithout oec .
TI ic EQ U directive does not set aside stora e uPY1l1ga memory location.
stant value with a data label so that h g for a data item but associates a con-
. W cn the label a .
I
Slant va ue will be substituted for the label ' ppears In the program, its can-
er constant and then the consta t" . The follOWing uses EQU for the
n ISused to load the R3 . count-
register.
o
COUNT EQU 25

MOV R3,#COUNT

_When executing the instruction "MOV R3, #COUNT", the register R3 will
be loaded with the value 25 (notice the # sign). What is the advantage of using
EQU? Assume that there is a constant (a fixed value) used in many different places
in the program, and the programmer wants to change its value throughout. By the
use of EQU, the programmer can change it once and the assembler will change all
of its occurrences, rather than search the entire program trying to find every occur-
rence.

END directive

Another important pseudocode is the END directive. This indicates to the


assembler the end of the source (asm) file. The END directive is the last line of an
8051 program, meaning that in the source code anything after the END directive
is ignored by the assembler. Some assemblers use" . END" (notice the dot) instead
of "END".

Rules for labels in Assembly language


By choosing label names that are meaningful, a programmer can make a
program much easier to read and maintain. There are several rules that names must
follow. First, each label name must he unique. The names used for labels in
Assembly language programming consist of alphabetic letters in both uppercase
and lowercase, the digits 0 through 9, and the special characters question mark C),
period (.), at (@), underline U, and dollar sign ($). The first character of the label
must be an alphabetic character. In other words it cannot be a number. Every
assembler has some reserved words that must not be used as labels in the program.
Foremost among the reserved words are the mnemonics for the instructions. For
example, "MOY" and "ADD" are reserved since they are instruction mnemonics.
In addition to the mnemonics there are some other reserved words. Check your
assembler for the list of reserved words.

Review Questions
I. The directive is always used for ASCII strings.
2. How many bytes are used by the following?
DATA 1: DB "AMERICA"
3. What ~ the advantage in using the EQU directive to define a constant value?
4. How many bytes are set aside by each of the following directives?
(a) ABC DATA: DB "1234" (b) MY_DATA: DB "ABC1234"
5. State the contents of memory locations 200H - 205H for the following:
ORG 200H
MYDATA: DB "ABC123"

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 51


SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER

Like any other microprocessor, the 8051 has a flag register to indicate
arithmetic conditions such as the carry bit. The flag register in the 8051 is called
the program status word (PSW) register. In this section we discuss various bits of
this register and provide some examples of how it is altered.

PSW (program status word) register


The program status word (PSW) register is an 8-bit register. It is also
referred to as the flag register. Although thc PSW register is 8 bits wide, only 6
bits of it arc used by the 8051. The two unused bits are user-definable flags. Four
of thc flags arc called conditional flags, meaning that they indicate some condi-
tions that result after an instruction is executed. These four are CY (carry), AC
(auxiliary carry), P (parity), and OV (overflow).
As seen from Figure 2-4, the bits PSW.3 and PSW4 are designated as RSO
and RS I, respectively, and are used to change the bank registers. They are
explained in the next section. The PSWS and PSWl bits are general-purpose sta-
tus flag bits and can be used by the programmer for any purpose. In other words,
thcy are user definable. See Figure 2-4 for the bits of the PSW register.

L-,C_Y__ A_C_,--_FO_I RSl I RSO I OV P

CY pswL Carry flag.


AC PSW6 Auxiliary carry flag.
FO PSWS
Available to the user for general purpose.
RSI PSW.4
RegIster Bank selector bit I.
R 0 PSW.3 Register Bank selector bit O.
OV PSW2 Overflow flag.
PSWI User-definable bit.
P PSW.O
Parity flag. Set/cleared by hardware each instuction cycle
10indicate an odd/even number of I bits in the accumulator.

RSt RSO Register Bank


0 0 Address
0
0 I OOH - 07H
I
I 0 08H - OFH
2
I I 10H - 17H
3
18H - IFH

The fOllOWingis a bricf ex I .


istcr, Thc impact of instructions o~ ~natlon of four of the flag bits of the PSW reg-
cse registers IS then discussed
2 .
CY, the carry flag

This flag is set whenever there is a carry out from thb D7 bit. This flag bit
is affected after an 8-bit addition or subtraction. It can also be set to 1 or 0 direct-
ly by an instruction such as "SETB C" and "CLR . C" where "SETB C" stands for
"set bit carry" and "CLR C" for "clear carry". More about these and other bit-
addressable instructions will be given in Chapter 8.
A C, the auxiliary carry flag

If there is a carry from D3 to D4 during an ADD or SUB operation, this bit


is set; otherwise, it is cleared. This flag is used by instructions that perform BCD
(binary coded decimal) arithmetic. See Chapter 6 for more information.
P, the parity flag

The parity flag reflects the number of Is in the A (accumulator) register


only. If the A register contains an odd number of Is, then P = I. Therefore, P = 0
if A has an even number of 1 s.
OV, the overflow flag

This flag is set whenever the result of a signed number operation is too
large, causing tbe high-order bit to overflow into the sign bit. In general, the carry
flag is used to detect errors in unsigned arithmetic operations. The overflow flag
is only used to detect errors in signed arithmetic operations and is discussed in
detail in Chapter 6.

ADD instruction and PSW ,


Table 2-1: Instructions That Affect
Next we examine the impact Flag Bits
of the ADD instruction on the flag bits
CY, AC, and P of the PSW register. Instruction CY OV AC
Some examples should clarify their ADD X X X
status. Although the flag bits affected ADDC X X X
by the ADD instruction are CY (carry SUBB X X X
flag), P (parity flag), AC (auxiliary MUL 0 X
carry flag), and OV (overflow flag) DIV 0 X
we will focus on flags CY, AC, and P DA X
for now. A discussion of the overflow RRC X
flag is given in Chapter 6, since it RLC X
relates only to signed number arith- SETB C J

metic. How the various flag bits are CLRC 0


used in programming is discussed in CPLC X
future chapters in the context of many ANL C, bit X
ANLC, /bit X
applications.
ORL C, bit X
See Examples 2-2 through 2-4
ORL C, /bit X
for the impact on selected flag bits as
MOVC, bit X
a result of the ADD instruction.
CJNE X
Note: X can be 0 or I .

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 53


Example 2-2
Show the status of the CY, AC, and P flags after the addition of 38H and 2FH in the fol-
lowing instructions.
MOV A,#38H
ADD A,#2FH ;after the addition A=67H, CY=O

Solution:
38 00111000
+ 2F 00101111
67 0110011 I

CY = 0 since there is no carry beyond the 07 bit.


AC = 1 since there is a carry from the 03 to the 04 bit.
P = I since the accumulator has an odd number of Is (it has five Is).
Example 2-3

Show the status of the CY, AC, and P flags after the addition of9CH and 64H in the fol-
lowing instructions.
MOV A,#9CH
ADD A,#64H ;after addition A=OO and
CY=l
Solution:
9C 1001 I 100
+ 64 01100100
100 00000000

CY = I since there is a carry beyond the 07 bit.


AC = 1 since there is a carry from the 03 to the 04 bit.
p = 0 since the accumulator has an even number of Is (it has zero Is).
Example 2-4

Show
lowmgthe status of the CY, AC, and P flags after the addition of 88H and 93H in the II0 1-
mstruetlons.
MOV A,#88H
ADD A,#93H
;after the
addition A=lBH,CY=l
Solution:
88 10001000
+ 93 100100] I
liB
00011011

Y = I since there is a carry beyond the 07 bi


A_ = ~ since there is no carry from the 03 to ~~e .
p - 0 smee the accumulator has a D4 bit,
n even number of Is (it has four Is).
Review Questions
I. The flag register in the 8051 is called .
2. What is the size of the flag register in the 805 I ?-l?6rJ.'i
3. Which bits of the PSW register are user-definable?
4. Find the CY and AC flag bits for the following code.
MOV A,#OFFH
ADD A, #01
5. Find the CY and AC flag bits for the following code.
MOV A,#OC2H
ADD A, #3DH

SECTION 2.7: 8051 REGISTER BANKS AND STACK

The 8051 microcontroller has a total of 128 bytes of RAM. In this section
we discuss the allocation of these 128 bytes of RAM and examine their usage as
registers and stack.

RAM memory space allocation in the 8051


There are 128 bytes of RAM in the 8051 (some members, notably the
8052, have 256 bytes of RAM). The 128 bytes of RAM inside the 8051 are
assigned addresses 00 to 7FH. As we will see in Chapter 5, they can be accessed
directly as memory locations. These 128 bytes are divided into three different
groups as follows.
I. A total of 32 bytes from locations 7F

00 to 1F hex are set aside for reg-


ister banks and the stack. Scratch Pad RAM
2. A total of 16 bytes from locations
30
20H to 2FH are set aside for bit-
addressable read/write memory. A 2F
Bit-Addressable RAM
detailed discussion ofbit-address- 20
able memory and instructions is IF
given in Chapter 8. Register Bank 3
3. A total of 80 bytes from locations 18
30H to 7FH are used for read and 17
Register Bank 2
write storage, or what is normally 10
called a scratch pad. These 80
OF
locations of RAM are widely used Register Bank 1 (Stack)
,
for the purpose of storing data and 08
parameters by 8051 programmers. 07
We will use them in future chap- Register Bank 0
00
ters to store data brought into the .. "
CPU via I/O ports. Figure 2-5, RAM Allocation In the 8051

Register banks in the 8051


As mentioned earlier, a total of 32 bytes of RAM are set aside for the reg-
ister banks and stack. These 32 bytes are divided into 4 banks of registers in which

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 55


each bank has 8 registers, RO - R7. RAM locations from 0 to 7 are set aside for
bank 0 afRO - R7 where RO is RAM location 0, RI is RAM location I, R2 is loca-
tion 2, and so on, until memory location 7, which belongs to R7 of bank O. The
second bank of registers RO - R7 starts at RAM location 08 and goes to location
OFH. The third bank of RO - R7 starts at memory location 10H and goes to loca-
tion 17H. Finally, RAM locations 18H to 1FH arc set aside for the fourth bank of
RO- R7. The following shows how the 32 bytes are allocated into 4 banks:

Bank 0 Bank I Bank 2 Bank 3


71 R7 FI R7 171 R7 I IFI R7 I
61 R6 EI R6 161 R6 I lEI R6 I
51 R5 01 R5 151 R5
,I 10~
41 R4 Cl R4 141 R4 rc R4
31 R3 R3 131 R3 I
BI IBI R3 I
21 R2 AI R2 121 R2 I IAI R2 I
II RI 91 RI III RI I 191 RI I
01 RO s[ RO 101 RO I lsi RO I
Figure 2-6. 8051 Register Banks and their RAM Addresses

_ As we can see from Figure 2-5, bank J uses the same RAM space as the
stack.
. This IS a major problem m programming the 8051 W
. c must.' ert h er not use
register bank I, or allocate another area of RAM for the stack. This will b dis-
cussed below. I e IS
Example 2-5

State the contents of RAM locations after the foil owing


. program:

MOV RO,#99H ;load RO with value 99H


MOV Rl,#8SH ;load Rl with
MOV R2,#3FH ;load R2 with value 8SH
with value 3FH
MOV
MOV
R7,#63H
RS,#12H
;load
;load
R7
RS with ~:i~:
63H
12H
Solution:

AIter the execution of the abov


RAM location 0 has value 99He pro~am we have the fOllowing:
RAM location 2 has value 3FH RAM location I has value 85H
RAM location 5 has value 12H AM location 7 has value 63H

Default register bank


If RAM locations 00 IF
register bank ofRO _ R7'd - are set aside for the four register b k .
~nswer is r.egisler bank 0;0t;:t ~:v~~sls to when the 8051 is powc:~~ ~p~~~h
accessed with the nam ' ocauon, 0 I 2 3 4 . e
the 8051 It' es RO,R I, R2, R3 R4 R5 R6' , , , ,5, 6, and 7 are
R I, and ~o~I~,~~~h:ya~~e:.to refer to the;e RAM ioea;i~~~ ~~hwhen programming
ir memory locations E 1 names SUchas Ro
56 . xamp e 2-6 clarifies this concept:
Example 2-6

Repeat Example 2-5 using RAM addresses instead ofregister names.

Solution:

This is called direct addressing mode and uses the RAM address location for the desti-
nation address. See Chapter 5 for a more detailed discussion of addressing modes.

MOV OO,#99H ;load RO with value 99H


MOV Ol,#85H ;load Rl with value 85H
MOV 02,#3FH ;load R2 with value 3FH
MOV 07,#63H ;load R7 with value 63H
MOV OS,#12H ;load R5 with value 12H
How to switch register banks
As stated above, register bank 0 is the default when the 8051 is powered
up. We can switch to other banks by use of the PSW (program status word) regis-
ter. Bits D4 and D3 of the PSW are used to select the desired register bank as
Table 2-2: PSW Bits Bank Selection shown in Table 2-2.
RSI (PSW.4) RSO (pSW.3) The D3 and D4 bits of register
Bank 0 o 0 PSW are often referred to as PSW.4 and
Bank I o I PSW,3 since they can be accessed by the
Bank 2 I 0 bit-addressable instructions SETB and
Bank 3 I I CLR. For example, "SETB PSW. 3"
will make PSW.3 = J and select bank
register 1. See Example 2-7,
Example 2-7
State the contents of the RAM locations after the following program:

SETB PSW.4 ;select bank 2


MOV RO, #99H ;load RO with value 99H
MOV Rl, #8SH ;load Rl with value 85H
MOV R2,#3FH ;load R2 with value 3FH
MOV R7, #63H ;load R7 with value 63H
MOV R5,#12H ;load R5 with value 12H

Solution:

By default, PSW.3=O and PSw'4=O; therefore, the instruction "SETB PSW,4" sets
RS 1= I and RSO=O, thereby selecting register bank 2. Register bank 2 uses RAM loca-
tions IOH - 17H. After the execution of the above program we have the following:

RAM location IOH has value 99H RAM location J JH has value 85H
RAM location 12H has value 3FH RAM location 17H has value 63H
'RAM location ISH has value J2H

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 57


Stack in the 8051
The stack is a section of RAM used by the CPU to store information tem-
porarily. This information could be data or an address. The CPU needs this storage
area since there are only a limited number of registers.

How stacks are accessed in the 8051


If the stack is a section of RAM, there must be registers inside the CPU to
point to it. The register used to access the stack is called the SP (stack pointer) reg-
ister. The stack pointer in the 8051 is only 8 bits wide, which means that It can take
values of 00 to FFH. When the 8051 is powered up, the SP register contains value
07. This means that RAM location 08 is the first location used for the stack by the
8051. The storing ofa CPU register in the stack is called a PUSH, and pulling the
contents off the stack back into a CPU register is called a POP. In other words, a
register is pushed onto the stack to save it and popped off the stack to retrieve it.
The job of the SP is very critical when push and pop actions arc performed. To see
how the stack works, let's look at the PUSH and POP instructions.
Pushing onto the stack
In the 8051 the stack pointer (SP) points to the last used location of the
stack. As we push data onto the stack, the stack pointer (SP) is incremented by one.
Notice that this is different from many microprocessors, notably x86 processors in
which the SP is decremented when data is pushed onto the stack. Examining
Example 2-8, we see that as each PUSH is executed, the contents of the register
arc saved on the stack and SP is incremented by I. Notice that for every byte of
data saved on the stack, SP IS incremented only once. Notice also that to push the
registers onto the stack we must usc their RAM addresses. For example the
msrrucnoi, "PUSH 1" pushes register R I onto the stack. '
Example 2-8

Show the stack and stack pointer for the following. Assume the default stack area and
register 0 is selected.
MOV R6,#25H
MOV Rl,#12H
MOV R4,#OF3H
PUSH 6
PUSH 1
PUSH 4
Solution: After PUSH 6 After PUSH I
After PUSH 4
OB
OB OB OB
OA
OA OA OA F3
09
09 09 12
09 12
08
08 25 08 25
08 25
Start SP: 07 Sp: 08
SP - 09
SP OA
S8
Popping from the stack

Popping the contents of the stack back into a given register is the opposite
process
. of. pushing . With every pop, t he top byte of the stack IS
. copied
. to the reg-
ister specified by the instruction and the stack pointer is decremented once.
Example 2-9 demonstrates the POP instruction. .

Example 2-9
Examining the stack, show the contents of the registers and SP after execution of the
following mstrucnons, All values are in hex.

POP 3 ;POP stack into R3


POP 5 ;POP stack into RS
POP 2 ;POP stack into R2

Solution:

After POP 3 After POP 5 After POP 2


08 54 OB OB OB

OA F9 OA F9 OA OA

09 76 09 76 09 76 09

08 6C 08 6C 08 6C 08 6C

Start SP = OB SP=OA SP=09 SP= 08

The upper limit of the stack


As mentioned earlier, locations 08 to IF in the 805 J RAM can be used for
the stack. This is because locations 20 - 2FH of RAM are reserved for bit-address-
able memory and must not be used by the stack. If in a given program we need
more than 24 bytes (08 to 1FH = 24 bytes) of stack, we can change the SP to point
to RAM locations 30 - 7FH. This is done with the instruction "MOV SP, #xx",

CALL instruction and the stack


Lnaddition to using the stack to save registers, the CPU also uses the stack
to save the address of the instruction just below the CALL instruction. This is how
the CPU knows where to resume when it returns from the called subroutine. More
information on this will be given in Chapter 3 when we discuss the CALL instruc-
tion.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 59


Example 2-10 .
h f Il OlN -ing
Show the stack and stack pointer for teo 1 instructions,

MOV SP,#5FH ,'make RAM location . 60H


,'first stack locatlon
MOV R2,#25H
MOV Rl,#12H
MOV R4,#OF3H
PUSH 2
PUSH 1
PUSH 4

Solution:

After PUSH 2 After PUSH 1 After PUSH 4


63 63 63 63
62 62 62 62 F3
61 6\ 61 12 61 12
60 60 25 60 25 60 25

Start SP = 5F SP= 60 SP= 61 SP= 62

Stack and bank 1 conflict

Recall (rom our earlier discussion that the stack pointer register points to
the current RAM location available for the stack. As data is pushed onto the stack,
SP is incremented. Conversely, it is decremented as data is popped off the stack
into the registers. The reason that the SP is incremented after the push is to make
sure that the stack is growing toward RAM location 7FH, from lower addresses to
upper addresses. If the stack pointer were decremented after push instructions, we
would be using RAM locations 7, 6, 5, ctc., which belong to R7 to RO of bank 0,
the default register bank. This incrementing of the stack pointer for push instruc-
tions also ensures that the stack will not reach location 0 at the bottom of RAM,
and consequently run out of space for the stack. However, there is a problem with
the default setting of the slack. Since SP = 07 When the 8051 is powered up, the
first location of the stack is RAM location 08, which also belongs to register RO
or register bank I. In other words, registcr bank 1 and the stack are using the same
mcmory space. If in a given program we need to usc register banks I and 2, we
can reallocatc another section of RAM to the slack. For cxample, we can allocate
RA M locations 60H and higher to the stack as Shown in Example 2-10.

60
Viewing registers and memory with a simulator
Many assemblers and C compilers come with a simulator. Simulators
allow us to view the contents of registers and memory after executing each instruc-
tion (single-stepping). We strongly recommend that you use a simulator to single-
step some of the programs in this chapter and future chapters. Single-stepping a
program with a simulator gives us a deeper understanding of microcontroller
architecture, in addition to the fact that we can use it to find errors in our programs.
Figures 2-7 through 2-10 show screen-shots for 8051 simulators from Proview 32
and Keil. See www.MicroDigitalEd.com for tutorials on how to use the simula-
tors.

Main Registers (FIG2-7) , J: -, ~~


CPlJ Bani< Data Hardware
fPc 10003 RB 00
'ACC roo- RO 00
PSW [00' R1 00
SP f57 R2 00
DPT~R3 00

IB roo R4 00
C 0 R5 00
lEA ro- R6 00
IE roo R7 00

Figure 2-7. Register's Screen from ProView 32 Simulator

" ..' Data (FIG2-8) "f:i .


00: 11 00 00 00 00 00 00 00 .......
08: 00 00 00 00 00 00 00 00 · .......
10: 00 00 00 00 00 00 00 00 · .......
18: 00 00 00 00 00 00 00 00 · .......
20: 00 00 00 00 00 00 00 00 · .......
28: 00 00 00 00 00 00 00 00 · .......
30: 00 00 00 00 00 00 00 00 · .......
38: 00 00 00 00 00 00 00 00 · .......
40: 00 00 00 00 00 00 00 00 · ... ," ...
48: 00 00 00 00 00 00 00 00 · .......
50: 00 00 00 00 00 00 00 00 · .......
58: 00 00 00 00 00 00 00 00 · .......
60: 00 00 00 00 00 00 00 00 · .......
68: 00 00 00 00 00 00 00 00 · .......
70: 00 00 00 00 00 00 00 00 · .......
78: 00 00 00 00 00 00 00 00 · . . . . . . .
---- --' -------------------
I
Figure 2-S. 12S-Byte Memory Space from Pro View 32 Simulator

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 6J


pet Workspace " ,
.

Re!)isle, Volue
-. Regs
10 0.00
,1 0.00
12 0.00
13 0.00
14 0.00
,5 0.00
,6 0.00
17 0.00
- Sys
a 0.00
b 0.00
sp 0.07
sp_max 0.07
dpl, 0.0000
PC $ C:O:<OOOO
states 0
sec 000000000
" psw 0,00

Figure 2-9. Register's Screen from Keil Simulator

GllU.fIltmffli.l
C:OxOOOO
C:OxOOlO 0000000000000000. 0000000000000000 '" ' ~
c. Ox0020 00 00 00 00 00 00 00 00 • 00 00 00 00 00 00 00 00 ......•.•...
C:Ox0030 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ........•••....
c. 0](00400000000000000000.0000000000000000 ....•.
C:OX0050 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ............•...
c. Ox0060 00 00 00 00 00 00 00 00 • 00 00 00 00 00 00 00 00 ....•.•......•..
C:Ox0070 00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 ..
00 00 00 00 00 00 00 00 . 00 00 00 00 00 00 00 00 .......••.......
>0 OOh. 7Fh
DEFINE OIR D1Splay
(.!..l!JlU\~C;~ .....~-,. - ....

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


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, decrement-
ed) by I. .
4. On power-up, the 8051 uses RAM location . as the first location of the
stack.
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 fol-
lowing 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 count-
er) 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 pro-
grammers 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 instruc-
tions 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 bina-
ry, 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 /, '')
PROBLEMS(I- 1{tf+<rl';5~
SECTION 2.1: INSIDE THE 8051

I .
Most registers . tear
In h 8051 e __ ._ bits
. wide.
. Registers RO - R7 arc all __ bits wide
2. Registers ACC and Bare __ bits wide.
; Name a l6-b; t register in the S05 I. .. (necessary,
. To load R4 with the value 65H, the pound slg~ IS _

5. 0 tional) in the instruction "MOV R4, #65H . '. ,)


6. What is the result of the following code and where IS It kept.
MOV A,#15H
MOV R2, #13H
ADD A,R2
7. Which of the following is (arc) illegal')
(a) MOV R3, #500 (b) MOV Rl, #50
(c) MOV R7, #00
(d) MOV A, #255H (e) MOV A, #50H
(I) MOV A, #FSH
(g) MOV R9, #50H .
8. Which of the following is (are) Illegal? ( R4
(a) ADD R3, #50H (b) ADD A, #50H c) ADD R7,
(d) ADD A, #25SH (e) ADD A, RS (I) ADD A, #FSH
(g) ADD R3, A . "?

9. What is the result of the following code and where IS It kept.


MOV R4,#25H
MOV A,#lFH
ADD A,R4
10. What is the result of the following code and where is it kept?
MOV A,#lS
MOV RS,#lS
ADD A,RS

SECTION
AND 22: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING

SECTION 2.3: ASSEMBLING AND RUNNING AN 8051 PROGRAM

II. Assembly language is a (low, high) -level language while C is a


- - (low, high) -level language,
12. Of C and Assembly language, which is more efficient in tenns of code gener-
ation (i.e., the amount of ROM space it uses)?
13. Which program produces the "obj" file?
14. True or false, The Source file has the extension "src" or "asm".
15, Which file provides the listing of error messages?
16. True or fal e. The SOurce code file can be a non-ASCII file.
17. True or false. Every source file must have ORG and END directives.
18. Do the ORG and END directives produce opcodes')
19. Why are the ORG and END directives also called pseudoCode?
20. True Or false. The ORG and END directives appear in the "Jst" file.
6-1
SECTION 2.4: THE PROGRAM COUNTER' AND ROM SPACE IN THE 8051

21. Every 8051 family member wakes up at address __ when it is powered up.
22. A programmer puts the first opcode at address 100H. What happens when the
microcontroller is powered up?
23. Find the number of bytes each of the following instructions takes.
(a) MOV A, #55H (b) MOV R3, #3 (c) INC R2
(d) ADD A, #0 (e) MOV A, R1 (I) MOV R3, A
(g) ADD A, R2
24. Pick up a program listing of your choice, and show the ROM memory address-
es and their contents.
25. Find the address of the last location of on-chip ROM for each of the following.
1i1"'. (a) DS5000-16 (b) 085000-8 (c) OS5000-32-1I=-f
(d) AT89C52 (e) 8751 (I) AT89C51-l.\.~
(g) DS5000-64· oFI1-
26. Show the lowest and highest values (in hex) that the 8051 program counter
can take.
27. A given 805 J has 7FFFH as the address of its last location of on-chip ROM.
What is the size of on-chip ROM for this 8051?
28. Repeat Question 27 for 3FFH.

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES

29. Compile and statc the contents of each ROM location for the following data.
<,
ORG 200B r- ~
I " "'ll.-I.."'\ .. r:
MYDAT_1: DB "Eartf':'.-~ W--
MYDAT_2: DB "987-65" -~~\V
MYDAT_3: DB "GABEH 98" 2:9
30. Compile and state the contents of each ROM location for the following data.
ORG 340H
DAT 1: DB 22,56H,10011001B,32,OF6H,11111011B

SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER

31. The PSW is a(n) -bit register.


32. Which bits of PSW are used for the CY and AC flag bits, respectively?
33. Which bits of PSW are used for the OV and P flag bits, respectively?
34. In the ADD instruction, when is CY raised?
35. In the ADD instruction, when is AC raised?
36. What is the value of the CY flag after the following code?
CLR C iCY = 0
CPL C ;complement carry
37. Find the CY flag value after each of the following codes.
(a) MOV A, #54H (b) MOV A, #00 (c) MOV A, #250
ADD A,#OC4H ADD A,#OFFH ADD A,#05
38. Write a simple program in which the value 55H is added 5 times.

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMING 65


SECTION 2.7: 8051 REGISTER BANKS AND STACK

39. Which bits of the PSW are responsible for selection of the register banks?
40. On power-up, what is the location of the first stack?
41. In the 8051, which register bank conflicts with the stack?
42. In the 8051, what is the size of the stack pointer (SP) register?
43. On power-up, whieh of the register banks is used?
44. Give the address locations of RAM assigned to various banks.
45. Assuming the use of bank 0, find at what RAM location each of the following
Jines stored the data.
(a) MOV R4,#32H (b)MOV RO,#12H
(e)MOV R7,#3FH (d)MOV R5,#55H
46. Repeal Problem 45 for bank 2.
47. After power-up, show how to select bank 2 with a single instruction.
48. Show the stack and stack pointer for each line of the following program
ORG
MOV RO,#66H
° .
MOV R3,#7FH
MOV R7,#SDH
PUSH 0
PUSH 3
PUSH 7
CLR A
MOV R3,A
MOV R7,A
POP 3
POP 7
POP °
49. In Problem 48, does the sequence of POP instru .
ues of registers RO, R3, and R7? If not h ctrons restore the original val-
nons ,s ow the correct sequence of instruc.
50. Show the staek and stack pointer for each line of the foil .
ORG 0 oWlllg program.
MOV SP,#70H
MOV RS,#66H
~10V R2,#7FH
MOV R7,#SDH
PUSH 5
PUSH 2
PUSH 7
CLR A
MOV R2,A
MOV R7,A
POP 7
POP 2
POP 5

CHAP
ANSWERS TO REVIEW QUESTIONS

SECTION 2.1: fNSIDE THE 8051

I. MOY A,#34H
MOY B,#3FH
ADDA,B
2. MOY A,#16H
ADDA,#OCDH
MOYR2,A
3. False
4. FF hex and 255 in decimal
5. 8

SECTION 2.2: INTRODUCTION TO 8051 ASSEMBLY PROGRAMMING

I. The real work is performed by instructions such as MOY and ADD. Pseudo-instructions, also
called assembler directives, instruct the assembler in doing its job.
2. The instruction mnemonics, pseudo-instructions
3. False
4. All except (c)
5. Assembler directive
6. True
7. (c)

SECTION 2.3: ASSEMBLING AND RUNNING AN 8051 PROGRAM

I. True
2. True
3. (a)
4. (b) and (d)
5. (d)

SECTION 2.4: THE PROGRAM COUNTER AND ROM SPACE IN THE 8051

I. 16
2. True
3. OOOOH
4. 2
5. With 8K bytes, we have 8192 (8 x 1024 = 8192) bytes, and the ROM space is 0000 to IFFFH.

SECTION 2.5: 8051 DATA TYPES AND DIRECTIVES

I. DB
2. 7
3. If the value is to be changed later, it can be done once in one place instead of at every occur-
rence.
4. (a) 4 bytes (b) 7 bytes
5. This places the ASCII values for each character in memory local ions starting at 200H. Notice
that all values are in hex.
200 = (41)
201 = (42)
202 = (43)
203 = (31)
204 = (32)
205 = (33)

CHAPTER 2: 8051 ASSEMBLY LANGUAGE PROGRAMMfNG 67


SECTION 2.6: 8051 FLAG BITS AND THE PSW REGISTER

I. PSW (program status register)


2. 8 bits
3. 01 and OS, which are referred to as PSw. J and PSW.5. respectively.
4.
Hex binary
FF 1111 1111
+ --.l + ----"1
100 10000 0000
This leads to CY=I and AC=1.

5.
Hex binary
C2 1100 0010
+ 1Q +.QQll 1101
FF 1111 1111
This leads to CY = a and AC = O.

SECTION 2.7: 8051 REGISTER BANKS AND STACK

I. 8-bit
2. Incremented
3. Decremented
4. 08
5. 0
6. 0-7
7. Register bank 3
8. RAM locations 18H to I FH

68
I

JUMP, LOOP, AND CALL


INSTRUCTIONS

OBJECTIVES

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

» Code 8051 Assembly language instructions using loops


» Code 8051 Assembly language conditional jump instructions
» Explain conditions that determine each conditional jump instruction
» Code long jump instructions for unconditional jumps
» Code short jump instructions for unconditional short jumps
» Calculate target addresses for jump instructions
» Code 8051 subroutines
» Describe precautions in using the stack in subroutines
» Discuss crystal frequency versus machine cycle
» Code 8051 programs to generate a time delay

69
In the sequence of instructions to be executed, it is often neee sary [0 trans-
fer program control to a different location. There arc many instruction in the 8051
to achieve this. This chapter covers the control transfer instructions available in
8051 Assembly language. In the first section we discuss instructions used for loop-
ing, as well as instructions for conditional and unconditional jumps. ln the second
section wc examine CALL instructions and their uses. ln the third section, time
delay subroutines are described for both the traditional 8051 and its newer gener-
ation.

SECTION 3.1: LOOP AND JUMP INSTRUCTIONS

In this section we first discuss how to perform a looping action in the 8051
and then talk about j limp instructions, bothconditional and unconditional.
Looping in the 8051

Repeating a sequence of instructions a certain number of times is called a


~ooP.T~e loop IS one of most Widely used actions that any microprocessor per-
lonns ,~th 051 the loop action is perform d by the instruction "DJNZ re
abel. this mstnlctJon, tliClegister is decremented' if it is not zero it i g,
to the target address referred to by the label. Prior to th~ start of the loo~ IthJumps
rsrer IS loaded With the COunter for the number of .. . .e reg-
lIlstruction both the register decrement and the d. .repetitions. Notice that In this
a smgle instruction. eelSlon to Jump arc Combmed Into
Example 3-1
Write a program to
(a) clear ACC, then
(b) add 3 to the accumulator ten times,

Solution:

;This program dd
a s value 3 to the ACe ten times
Mav A,#O
Mav R2,#10 ;A~O, clear ACe
AGAIN: ADD A.#03 ;load COunter R2~lO
DJNZ R2,AGAIN ;add 03 to ACe
MaV RS,A ;repeat until R2~O(lO
•. Sa ve A in RS times)

In the program in Exam Ie 3


COunter is first set t lOP -I, the R2 register IS
in
checks its value. f~ R2' each ileration the instruction DJ~ed as a COUnter, The
the label "AGAJN" Th s not zero, It jumps to the target d; decrements R2 and
R2 becomes zero i; fall IS ~oopmg action Continues until ~2 ~ess aSSociated with
ately below it in ;h' strough the loop and exceut he : eeOmes zero. After
. '. IS case the "MOV R " ' es t e lllStruct" .
Notice rn the DJNZ i ,5, A Instruction Ion Immedl_
COUntercan also be a RAM ;lSITUCtlonthallhe registers ca ' b
Ocatlon as we will s . , n e any ofRO - R7. Th
70 ec 1/1 Chapter 5. e
Example 3-2

What is the maximum number of times that the loop in Example 3-1 can be repeated?

Solution:

Since R2 holds the count and R2 is an 8-bit register, it can hold a maximum of FFH
(255 decimal); therefore, the loop can be repeated a maximum of 256 times.

loop inside a loop

As shown in Example 3-2, the maximum count is 256. What happens if we


want to repeat an action more times than 256? To do that, we use a loop inside a
loop, which is called a nested loop. In a nested loop, we use two registers to hold
the count. See Example 3-3.

Example 3-3

Write a program to (a) load the accumulator with the value 55H, and (b) complement
the ACC 700 times.

Solution:

Since 700 is larger than 255 (the maximum capacity of any register), we use two regis-
ters to hold the count. The following code shows how to use R2 and R3 for the count.
Ol..<.-D
MOV A,#55H ;A=55H
MOV R3,#10 ;R3=10, the outer loop count
NEXT: MOV R2,#70 ;R2=70, the inner loop count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times (inner loop)
DJNZ R3,NEXT
b'10\)
In this program, R2 is used to keep the inner loop count. In the instruction "DJNZ
R2 ,AGAIN", whenever R2 becomes 0 it falls through and "DJNZ R3, NEXT" is exe-
cuted. This instruction forces the CPU to load R2 with the count 70 and the inner loop
starts again. This process will continue until R3 becomes zero and the outer loop is fin-
ished.

Other conditional jumps


Conditional jumps for the 8051 are summarized in Table 3-1. More details
of each instruction are provided in Appendix A. In Table 3-1, notice that some of
the instructions, such as JZ (jump if A = zero) and IC (jump if carry), jump only if
a certain condition is met. Next we examine some conditional jump instructions
with examples.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 71


JZ Uump if A = 0) . the content a I' reg istcr A is checked,
. d
lfit is zero, it jumps
In this instruction I I k at the following co e.
to the target ad d ress. For examp e, 00

MOV A,RO ;A=RO


JZ OVER ;jump .if A o
MOV A,Rl ;A=Rl
JZ OVER ;jump l·f A o
OVER:
Table 3-1: 8051 Conditional Jump Instructions
In this program, if either 'Instruction Action
RO or R J is zero, it jumps to the JZ Jump if A 0
label OYER. Notice that the JZ JNZ Jump if A"" 0
instruction can be used only for DJNZ Decrement and jump if
register A. It can only check to register", 0
sec whether the accumulator IS CJNE A, data Jump if A", data
zero, and it docs not apply to any CJNE reg, #data Jump iI' byte", #data
other register, More importantly, JC Jump ifCY I
you don't have to perform an JNC Jump ifCY 0
arithmetic instruction such as JB .lump ifbit - I
decrement to use the JNZ instruc- JNB
tion. See Example 3-4. Jump if bit - 0 .
JBC
Jump if bit I and clear bit
Example 3-4

Write a program to determine if R5 contains the value O. If so, put 55H in it.
Solution:
MOV A,RS ;eopy RS to A
JNz NEXT
MOV ;jump if A is not zero
R5,#SSH
NEXT:

JNC Uump if no carry, jumps if CY = 0)


In this instruction, the carry flag bit in the flag (PSW) register is used to
make the decision Whether to jump. In executing "JNC label", the processor
looks at the carry flag to sec if it is raised (CY ~ I). If it is not, the CPU starts to
fetch and execute instructions from the address of the label. If CY ~ I, it will not
jump but will exCCute the next instruction below JNC.
Note that there is also a "JC label" instruction, In the .IC instruction, if
Y ~ 1 it jumps to the target addrcss, We will give more examples of these instruc_
tions in the Context of applications in future chapters.
There arc also JB (jump ifbit is high) and JNB (jump ifbit is low) instruc_
arc
tion diseu·sed.
. These arc diScussed in Chapters 4 and 8 When bit manipulation instructions

72
--- Example 3-5

Find the sum of the values 79H, FSH, and E2H. Put the sum in registers RO (low byte)
and RS (high byte).

Solution:

MOV A,#O ;clear A(A=O)


MOV R5,A ;clear R5
ADD A,#79H ;A=O+79H=79H
JNC N 1 ;if no carry, add next number
INC R5 ;if CY=1, increment R5
N 1: ADD A,#OFSH ;A=79+F5=6E and CY=1
JNC N 2 ;jump if CY=O
INC R5 ;If CY=1 then increment R5(R5=1)
N 2: ADD A,#OE2H ;A=6E+E2=50 and CY=1
JNC OVER ;jump if Cy=o
INC R5 ;if CY=1, increment 5
OVER:
I
MOV RO,A ;Now RO=50H, and R5=02

All conditional jumps are short jumps


It must be noted that all conditional jumps are short jumps, meaning .that
the address of the target must be within -128 to + 127 bytes of the contents of the
program counter (PC). This very important concept is discussed at the end of this
section.

Unconditional jump instructions


The unconditional jump is a jump in which control is transferred uncondi-
tionally to the target location. In the 80S I there are two unconditional jumps:
UMP (long jump) and SlMP (short jump). Each is discussed below.
LJMP (long jump)
LJMP is an uncon Itionallongjump. t IS a 3'JJyte instruct'Q in hich tHe
first byte is the opcooe, an the second and thir by es re resent the l6-bit addre.",ss"--J
of the target location. he 2-byte target address allows a jump to any memory loca-
tion from 0000 to FFFFH.
Remember that although the program counter in the 8051 is 16-bit, there-
by giving a ROM address space of 64K bytes, not all 80S 1 family members have
that much on-chip program ROM. The original 80S I had only 4K bytes of on-chip
ROM for program space; consequently, every byte was precious. For this reason
there is also an SlMP (short jump) instruction, which is a 2-byte instruction as
opposed to the 3-byte LJMP instruction. This can save some bytes of memory in
many applications where memory space is in short supply. SJMP is discussed next.
SJMP (short jump)
In this 2-byte instruction, t e first byte is the olJ£Q.deand the second byte
is e relative address of the target location. The relati e address range of 00 - FFH

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 73


. . hin - I28 to + 127 bytes of
. ard and backward jumps; that IS, W:~I~ counter). If the jump is
is divided mto fOl:the address of the current PC (pro; b tes from the current PC.
memory relative r ddress can be within a space of I 2 bYwithin _ I28 byres from
forward, the targeta . d the target address can e
dd IS backwar ,
If the target a ress. I' d in detail next.
the eurrenJ PC. This IS exp arne
. the short jump address
Calculating di
P' t ction all con trion
al J'urnps such as INC, JZ,
.
In addition to the SJM m~e~o th; fact that they are all two-byte mstruc-
and DJNZ arc also short Jumps d b e is thc opcodc and the second byte IS the
tions. In these rnstrucuons the first ~c1ative to the value ofthc program counter.
relative address. The target address IS d byte is added to the PC of the mstruc-
To calculate
lion the target address,
immediatelybelow the ;econderstand
the Jump. 0 un
this, look at Examplc 3-6.

Example 3-6 .
Using the following Jist file, verify t e Jump
. he i forward address calculatIon.
Line PC Opcode
01 0000 Mnemonic Operand
02 0000 7800
ORG 0000
03 0002 7455 MOY RO, #0
04 0004 6003 MOY A, #55H
as 0006 08 JZ NEXT
06 OOQ] _ 04 INC RO
07 0008- AGA~ INC A
08 ~
-0009 2477 INC A
Q2 OOOB NEXT: ADD A, #77h
5005
10 OOOD JNC OYER
E4
11 OOOE CLR A
F8
12 OOOF MOY RO,A
F9
13· 0010 FA May Rl,A
14 0011 MOy R2,A
FB
15 0012 MaY R3,A
2B OVER:
16 0013 50F2 ADD A,R3
17 0015
18
80FE
HERE: JNc AGAIN
0017 SJMP HERE
END
Solution:

First notice that the J2 and INC instructions both jump forward. The target address for
a forward jump is calculated by adding the PC of the follOWing instruction to the sec-
ond byte of the short jump instruction, which is called the relative address. In line 4 the
instruction "JZ NEXT" has opeode of 60 and operand of 03 at the addresses of 0004
and 0005. The 03 is the relative address, relative to the address of the next instruction
INC RO, which is 0006. By adding 0006 to 3, the target address of the label NEXT,
which is 0009, is generated. In the same way for line 9, the "JNC OVER" instruction
has 0pcode and operand of 50 and 05 Where 50 is the 0pcode and 05 the relative address.
address
Therefore,
of label
05 is OVER.
added to 0000, the address of instruction "CLR A", giving 12H, the
Example 3-7

Verify the calculation of backward jumps in Example 3-6.

Solution:

In that program list, "JNC AGAIN" has opcode 50 and relative address F2H. When the
relative address of F2H is added to ISH, the address of the instruction below the jump,
we have 15H + F2H = 07 (the carry is dropped). Notice that 07 is the address of label
AGAIN. Look also at "SJMP HERE",which has 80 and FE for the opcode and rela-
tive address, respectively. The PC of the following instruction, OOI7H, is added to FEH,
the relative address, to get 0015H, address of the HERE label (l7H + FEH = 15H).
Notice that FEH is -2 and 17H + (-2) = 15H. For further discussion of the addition of
negative numbers, see Chapter 6.

Jump backward target address calculation


While in the case of a forward jump, the displacement value is a positive
number between 0 to 127 (00 to 7F in hex), for the backward jump the displace-
ment is a negative value of 0 to -128 as explained in Example 3-7.
It must be emphasized that regardless of wbether the SJMP is a forward or
backward jump, for any short jump the address of the target address can never be
more than -128 to + j 27 bytes from the address associated with the instruction
below the SJMP.lf any attempt is made to violate this rule, the assembler will gen-
erate an error stating the jump is out of range.

Review Questions
I. The mnemonic DJNZ stands for
---
2. True or false. "DJNZ R5, BACK" combines a decrement and a jump in a sin-
gle instruction.
3. "JNC HERE" is a -byte instruction.
4. In "JZ NEXT"" which register's content is checked to see if it is zero?
5. LlMP is a -3 -byte instruction.

SECTION 3.2: CALL INSTRUCTIONS

Another control transfer instruction is the CALL mstruction, which is used


to call a subroutine Suor utines are often usea to eifo ta ks that need to be
performed freguentl . This makes a program more structured in addition to saving
memory space. In the 8051 there are two instructions for call: LCALL (long call)
and ACALL (absolute call). Deciding which one to use depends on the target
address. Each instruction is explained next.

LCALL (long call)


In his 3-bYle mstruction, t e first oxte is the-opcode and the second an
third byte are use iorJliejloc!ress Qfjb_etarget su routine. Therefore, LCALL can
be used to call subroutines located anywhere within the 64K-byte address space of

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 75


the 80S I. To make sure that after execution of the called subroutine the 80S I
knows where to come back to, the processor automatically saves on the stack the
address of the instruction immediately below the LCALL. When a subroutine is
called, control is transferred to that subroutine, and the processor saves the PC
(program counter) on the stack and begins to fetch instructions from the new loca-
tion. After finishing execution of the subroutine, the mstrucnon RET (return)
transfers control back to the caller. Every subroutine needs RET as the last instruc-
tion. Sec Example 3-8.
The following points should be noted for the program in Example 3-8.
I. Notice the DELAY subroutine. Upon executing the first "LCALL DELAY",
the address of the instruction right below it, "MOV A, #OAAH",is pushed onto
the stack, and the 80S I starts to execute instructions at address 300H.
2. In the DELAY subroutine, first the counter RS is set to 255 (RS = FFH); there-
fore, the loop is repeated 256 times. When R5 becomes 0, control falls to the
RET instruction, which pops the address from the stack into the program
counter and resumes executing the instructions after the CALL.
Example 3-8
Write a program to toggle all the bits of port 1 by sending to it the values SSH and AAH
continuously Put a time delay in between each issuing of data to port I. This program
will be used to test the ports of the 80S J in the next chapter.

Solution:.

ORG o
BACK: MOV A, #55H ;load A with 55H
MOV Pl,A ;send 55H to port 1
LCALL DELAY ;time delay
MOV A,#OAAH ;load A with AA (in hex)
MOV Pl,A ;send AAH to port 1
LCALL DELAY
SJMP BACK 'keep do i hi
---this is the delaY'SUbrou~t~~ t 1S 1ndefinitely
ORG 300H ;put time d 1
DELAY: MOV R5,#OFFH 'R5 _ 255 e ~y at address 300H
AGAIN: DJNZ R5,AGAIN ;sta~ her~FF tlnlhex),the counter
RET . un 1 R5 becomes 0
END :return to caller (when R5 = 0)
,end of asm file
The amount of time delay 111 Exarnpl 3 8 d
80S I. How to calculate the exact time 'Ileb' epends on the frequency of the
e explall1ed
H owever you can increase the time deja WIbv usi d '1'
111 etai 111 Chapter 4.
y y usmg a nested loop as shown bel
D~M: ~
;nested loop delay
MOV R4,#255
NEXT: ;R4 = 255(FF
MOV RS,#25S in hex)
AGAIN: ;RS = 2SS(FF
DJNZ R5,AGAIN in hex)
;stay here until
DJNZ R4,NEXT R5 becomes 0
;decrement R4
;keep loading
RET RS until R4
;return (when R4 = 0
= 0)
76

-c
CALL instruction and the role of the stack
. The stack and stack pointer were covered in the last chapter. To understand
the Importance of the stack in microcontrollers, we now examine the con tenis of
the stack and stack pointer for Example 3-8. This is shown in Example 3-9.
Example 3-9

Analyze the stack contents after the execution of the first LCALL in the following.

Solution:

001 0000 ORG 0


002 0000 7455 BACK: MOV A, #55H ;load A with 55H
003 0002 F590 MOV P1,A ;send 55H to port 1
004 0004 120300 LCALL DELAY ;time delay
005 0007 74AA MOV A,#OAAH ;load A with AAH
006 0009 F590 MOV P1,A ;send AAH to port 1
007 OOOB 120300 LCALL DELAY
008 OOOE 80FO SJMP BACK ;keep doing this
009 0010
010 0010 this is the delay subroutine
011 0300 ORG 300H
012 0300 DELAY;
013 0300 7DFF MOV R5,#OFFH ;R5=255
014 0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here
015 0304 22 RET ;return to caller
016 0305 END ;end of asm file

When the first LCALL is executed, the address of the instruction


"MOV A, # OAAH" is saved on the stack. Notice that the low byte OA
goes first and the high byte is last. The last instruction of the called
subroutine must be a RET instruction, which directs the CPU to 09 00
POP the top bytes of the stack into the PC and resume executing
at address 07. The diagram shows the stack frame after the 08 07
first LCALL.
SP= 09

Use of PUSH and POP instructions in subroutines


Upon calling a subroutine, the stack keeps track of where the CPU should
return after completing the subroutine. For this reason, we must be very careful in
any manipulation of stack contents. The rule is that the number of PUSH and POP
instructions must always match in any called subroutine. In other words, for every
PUSH there must be a POP. See Example 3-10.

Calling subroutines
In Assembly language programming it is common to have one main pro-
gram and many subroutines that are called from the main program. This allows
you to make each subroutine into a separate module. Each module can be tested
separately and then brought together with the main program. More importantly, in
a large program the modules can be assigned to different programmers in order to
shorten development time.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 77


Example 3-10
Analyze the stack for the first LCALL instruction in the following program.

01 0000 ORG 0
02 0000 "'1455BACK: MOV A,#55H ;load A with 55H
#-
03 0002 F590 MOV P1,A ;send 55H to port 1

..
04 0~04 7C99
05 0006 7D67
MOV R4,#99H
MOV R5,#67H
06 0d'08 120300 LCALL DELAY ;time delay
~
07 OOOB 74M MOV A,#OAAH ;load A with AA
08 O~OD F590 MOV P1,A ;send AAH to port 1
09 O~OF 120300 LCALL DELAY
10 0~12 80EC SJMP BACK ;keep doing this
11 0014 -------this is the delay subroutine
12 0300 ORG 300H
13 0300 C004 DELAY: PUSH 4 ;PUSH R4
14 0302 COOS PUSH 5 ;PUSH RS
15 0304 7CFF MOV R4,#OFFH ;R4=FFH
16 0306 7DFF NEXT: MOV R5,#OFFH ;R5=255
17 0308 DDFE AGAIN: DJNZ R5,AGAIN
18 030A DCFA DJNZ R4,NEXT
19 030C D005 POP 5 ;POP into R5
20 030E D004 POP 4 ;POP into R4
21 0310 22 RET ;return to caller
22 0311 END r end of asm file
Solution:

First notice that for the PUSH and POP instructions we must specify the direct address
of the register being pushed or popped. Here is the stack frame.

It needs [0 be emphaSized that' .


ubroutine can be anywhere with: I III uSlllg LCALL, the target address of the
. I III t lC 64K-byt
1 not the ease for the other call i [' c memory space of the 8051. This
ins ruction ACALL hi .
, ,w ich IS explaincd next.
78
Figure 3-1. 8051 Assembly Main Program That Calls Subroutines
ACALL (absolute call) / :z ¥
.-c----':"":""'~".....
ACALL is a 2-by c ins ction in ontraSl to CALI which is 3 byt s
Since ACALL is a 2-byte instruction, the target address of the subroutine must be
within 2K bytes because only II bits of the 2 bytes are used for the address. :rliere
is no difference etwcen ACALL an LCALL in terms of saving the rogram
counter on the stack or the function of the RE ·nstruction. hc only difference is
that the target address for LCALL can be anywhere within the 64K-byte address
space of the 8051 while the target address of ACALL must be within a 2K-byte
range. In many variations of the 8051 marketed by different companies, on-chip
ROM is as low as 1K byte. In such cases, the use of ACALL instead of LCALL
can save a number of bytes of program ROM space.

Example 3-11
A developer is using the Armel AT89CI051 microcontroller chip for a product. This
chip has only IK byte of on-chip flash ROM. Which instruction, LCALL or ACALL, is
more useful in programming this chip?

Solution:
The ACALL instruction is more useful since it is a 2-byte instruction. It saves one byte
each time the call instruction is used.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 79


Of course in addition to using compact mstruc
. tiIOns, wee can program cffe-
.
cicntly by having' a detailed knowledge of all the instructions supported by a given
microprocessor, and using them wisely, Look at Example 3-12.

Example 3-12
Rewrite Example 3-8 as efficiently as you can.

Solution:
ORG 0
MOV A,#55H ;load A with 55H
BACK: MOV Pl,A ;issue value in reg A to port
ACALL 1
DELAY ;time delay
CPL A ;complement reg A
SJMP BACK ;keep doing this indefinitely
-------this is the delay subroutine
DELAY:
MOV
AGAIN: DJNZ R5,#OFFH ;R5=255(FF in hex), the counter
RET
R5,AGAIN ;stay here until R5 becomes 0
;return to caller
END ;end of asm file

Notice in this program that register A is set to 55H. By complementing 55H, we have
AAH; and by complementing AAH we have 55H. Why? "0101OIOJ" in binary (55H)
becomes "10 I 0 I0 I0" in binary (AAH) when it is complemented; and "1010 1010"
becomes "0) 0 I0 101" if it is complemented.

Review Questions

I. What do the mnemonics "LCALL" and "ACALL" stand for?


2. True or false. In the 8051, control can be transfcrred anywhere within the 64K
bytes of code space if using the LCALL instruction.
3. How ~~ei.~~~ CPU know where to return to after executing the RET instrue-
lIon? t'U-WUUKJ .(J) eN UL\ ~
4. Descnbe briefly the function of the RET instruction.
5. The LCALL instruction is a0
-byte instruction.

SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS

. h In the la t section we used the DELAY subroutine. In this section we dis-


cuss ow to generate various time del d I I
and DS89C4xO. . ays an ca cu ate exact delays for the 8051
Machine cycle for the 8051
The CPU takes a certain number of I k _ .
In the 8051 family these clock I c oc cycles to execute an mstruction.
. the list of, 8051 instru eyc
provides ti
es are
d' referred to as mac'hitne eye Ies. Table A- J
die
cay, we usc this list. In the 8051 f '1 their
Ions an h machine cy e Ies.. t0 ca J culate a time
.

ami y, t e length of the machine cycle depends


80
on the frequency of the crystal oscillator connected to the 8051 system. The crys-
tal oscillator, along with on-chip circuitry, provide the clock source for the 8051
CPU (see Chapter 8). The frequency of the crystal connected to the 8051 family
can vary from 4 MHz to 30 MHz, depending on the chip rating and manufacturer.
Very often the I .0592 MHz ystal oscillator is used to make the 805 I-based sys-
tem compatible with the serial port of the IBM PC (see Chapter 10). In thc origi-
nal 8051, one machine cycle lasts 12 oscillato perioils. Therefore, to calculate the
machine cycle for the 8051, we laKe 1/12 of the crystal frequency, then take its
inverse, as shown in Example 3-13.

Example 3-13

The following shows crystal frequency for three different 8051-based systems. Find the
period of the machine cycle in each case.
(a) 11.0592 MHz (b) 16 MHz (c) 20 MHz

Solution:

(a) 11.0592 MHz/12 = 921.6 kHz; machine cycle is 11921.6 kHz = 1.085 us (microsec-
ond)
(b) 16 MHz/12 = 1.333 MHz; machine cycle (MC) = 111.333 MHz = ().75 us
(c) 20 MHz/I2 = 1.66 MHz; MC = 1/1.66 MHz = 0.60 us
Example 3-14 '
For an 8051 system of 11.0592 MHz, find how long it takes to execute each of the fol-
lowing instructions.

(a) MOV R3, #55 (b) DEC R3 (c) DJNZ R2, target
(d) LJMP (e) SJMP (I) NOP (no operation)
(g) MUL AB

Solution:

The machine cycle for a system of 11.0592 MHz is 1.085 us as shown in Example 3-
13. Table A-I in Appendix A shows machine cycles for each of the above mstructions.
Therefore, we have:

Instruction Machine cycles Time to execute


(a) MOV R3,#55 1 lxl.085 ~s = 1.085 ~s
(b) DEC R3 1 lxl.085 ~s = 1. 085 us
(c) DJNZ R2,target 2 2xl.085 ~s = 2.17 ~s
(d) LJMP 2 2xl.085 us = 2.17 ~s
(e) SJMP 2 2xl.085 us = 2.17 ~s
(f) NOP 1 lxl.085 ~s = 1. 085 us
(g) MUL AB 4 4xl.085 ~s = 4.34 ~s

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 8]


I t" n for 8051
Delay calcu a 10 , nsists of two parts: (I) set-
' delay subroutine co
As seen in the last secnon, a f h time delay is performed by teo h b d Y of
d
ting a counter, an ,(2) a loop, Most
, -15 0 t e
the loop, as shown m Example 3 ,

Example 3-15 "ftheprogram,


' 0 f the delay in the following
Find the Size 1
crystal frequency is 11,0592
MHz.

Mav A,#55H -load A with 55H


AGAIN: Mav Pl,A ,r-issue va 1 ue l'
n reg A to port 1
ACALL DELAY ,r t i me delay
CPL A ;complement reg A ..
SJMP AGAIN ;keep doing this indeflnltely
r.----Time delay
DELAY: Mav R3,#200 ;load R3 with 200
HERE: DJNZ R3,HERE ;stay here until R3 become 0
RET ,'return to caller

Solution:

From Table A-I in Appendix A, we have the following machine cycles for each instruc-
tion of the DELAY subroutine.
Machine Cycle
DELAY: MOV R3,#200 1
HERE: DJNZ R3,HERE 2
RET
2

Therefore, we have a time delay of [(200 x 2) + I + 2] x 1.085 us ~ 436.255 us,

Very often we calculate the time dclay based on the instructions inside the
loop and ignore the clock cycles associated with the instructions outside the loop.
In Example 3-15, the largest value the R3 register can take is 255; there-
fore, one way to increase the delay is to usc NOP instructions in the loop. NOP,
which
3-16. stands for "no operation," simply wastes time. This is shown in Example

Loop inside loop delay

called aAnother way to


nested loop. SecgetExample
a large delay
3-17. is to usc a loop inside a loop, which is also

82
Example 3-16
For an 8051 system of 11.0592 MH z, find th e time
. delay for the followmg
.. subroutme:

Machine Cycle
DELAY: MOV R3,#250 1

HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 2

RET 2

Solution:

The time delay inside the HERE loop is [250( I + 1 + I + I + 2)] x 1.085 /1S= 1500 x
1.085 /1S= 1627.5 I1S.Adding the two instructions outside the loop we have 1627.5 /1S+
3 x 1.08511s = 1630.755I1S.

If machine cycle timing is critical to your system design, make sure that you check the
manufacture's data sheets for the device specification. For example, the DS89C420 has
3 machine cycles instead of 2 machine cycles for the RET instruction.

Example 3-17
For a machine cycle of 1.085 I1S,find the time delay in the following subroutine.

DELAY: Machine Cycle


MOV R2,#200 cP
AGAIN: MOV R3,#250 1
HERE: NOP 1
NOP 1
DJNZ R3,HERE 2
DJNZ R2,AGAIN 2
RET G>
For the HERE loop, we have (4 x 250) xl.085 /1S= 1085 I1S.The AGAIN loop repeats
the HERE loop 200 times; therefore, we have 200 X I085 /1S= 217000, if we do not
include the overhead. However, the instructions "MOV R3, #250" and "DJNZ
R2 ,AGAIN" at the beginning and end of the AGAJN loop add (3 x 200 x 1.085 I1s) =
651 I1Sto the time delay. As a result we have 217000 + 651 = 217651 /1S= 217.651 mil-
liseconds for total time delay associated with the above DELAY subroutine. Notice that
in the case of a nested loop, as in all other time delay loops, the time is approximate
since we have ignored the first and last instructions in the subroutine.

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 83


Delay calculation for other versions of 8051
In creating a time delay using Assembly language instructions, one must be
mindful of two factors that can affect the accuracy of the delay.
I. The crystal frequency: The frequency of the crystal oscillator connected 10
the X I - X2 input pins is one factor in the lime delay calculation. The duration
of the clock period for the machine cycle is a function of this crystal frequen-
cy.
2. The 8051 Design: Since the original 80S I was designed in 1980, both the field
of IC technology and the architectural design of microprocessors have seen
great advancements. Due 10 the limitations of IC technology and limited CPU
design experience at that time, the machine cycle duration was set at 12 clocks.
Advances in both IC technology and CPU design in recent years have made
the I-clock machine cycle a common feature of many new 80S I chips. Indeed,
one way to increase the 80S I performance without losing code compatibility
with the original 80S I is to reduce the number of clock cycles it takes to exe-
cute an instruction. For these reasons, the number of machine cycles and the
number of clock periods per machine cycle varies among the different versions
of the 80S 1 mieroeontrollers. While the original 80S I design used 12 clock
periods per machine cycle, many of the newer generations of the 80S I use
much fewer clocks per machine cycle. For example, the OS5000 uses 4 clock
periods per machine cycle while the OS89C4xO uses only one clock per
machine cycle. The 80S I
products from Phili s Tab~e 3-2: Clocks ~er Machine Cycle (MC) for
.
S enucon d uctors h ave the P Various 8051
--_ ......... Versiens
__ =;,;,;;.. _
option of using either 6 or 12 Chip/Maker
clocks per machine cycle. AT89CSI Atmel Clocks per Machine Cycle
Table 3-2 shows some of the P89CS4X2 Philips 12
80S 1 versions with their OSSOOODallas Semi 6
machine cycles. 4
0589C420/30/40/S0 Oallas Semi

Example 3-18

From Table 3-2, find the period of th hi


XTAL = 11.0S92 MHz, and discuss the' e mac me cycle (MC) 111 each case if
(a) AT89CSI (b) P89CS4X2 (c) OS~:;ct ~d~~~~o;~~~~e.
Solution:

(a) 11.0592MHzil2 = 921.6 kHz; MC is 1/92J 6 k _ .


b) 11.0S92 MHzi6 = 1.8432 MHz. MC . . Hz - J .08Sl-Is(mlCTOseeond)= I08S ns
(c) 11.0592 MHzi4 = 2.7648 MHz: Mc .IS 1/1.8432 MHz = 0.S42S I-Is= 542 ns
(d) 11.0592 MHzil = 11.0S92 MH' . M IS 1/2.7648 MHz = 0.361-1s= 360 ns
z; C IS I/J I.OS92 MHz = 0.09041-1s = 90 ns
This mcans tbat if we connect Ii
same frequency we get approximater ~T~~CSJ and a DS89C4xO to a crystal of the
o 89C4xOChtpoveTiheAT89CSI Se'eYE 10 times performance boost for the
. xample 3-20.
84
Delay calculation for DS89C4xO
In the ease of the DS89C4xO, since the number clocks per machine eycle
was reduced from 12 to I, the number of machine eycles used to execute an
mstruction
. had to be ch ange d ta re fl ect this
" reality. Table 3-3. compares the
machine eycles for the DS89C4xO and 8051 for some instructions. .

Table 3-3: Comparison of 8051 and DS89C4xO Machine Cycles

Instruction 8051 DS89C4xO


MOY R3,#Value 1 2
DEC Rx I 1
Dmz 2 4
LIMP 2 3
SJMP)-----------'2~--:?.3 -----
NOP I 1
MULAB 4 9

See the following Web sites for DS89C420/30/40/50


instructions and timing:

www.maxim·ic.com

www.MicroDigitaIEd.com

Example 3-19
For an AT8051 and D889C420/30/40/50 system of 11.0592 MHz, find how long it takes
to execute eaeh of the following instructions.

(a) MOV R3, #55 (b) DEC R3 (c) DJNZ R2, target
(d) LJMP (e) SJMP (f) NOP (no operation)
(g) MUL AB

Solution:
The machine cycle time for theAT8951 and DS89C420/30 was shown in Example 3-18.
Table 3-3 shows machine cycles for each of the above instructions. Therefore, we have:

Instruction AT80S1 DS89C420130140lS0


(a) MOV R3, #55 1x1085 TIS 1085
= TIS 2x90 TIS = 180 TIS

(b) DEC R3 1x1085 TIS 1085 TIS 1x90 TIS = 90 TIS


(c) DJNZ R2, .. 2x1085 TIS = 2170 TIS 4x90 TIS = 360 TIS
(d) 2x1085 TIS = 2170 TIS 3x90 TIS 270 TIS
LJMP
2x1085 TIS 2170 TIS 3x90 TIS 270 TIS
(e) SJMP
(f) NOP 1x1085 TIS = 1085 TIS 1x90 ns = 90 TIS

4x1085 TIS = 4340 TIS 9x90 TIS 810 TIS


(g) MUL AB

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 85


Example 3-20
Find the time delay for the loop section of the following subroutine if it is run on a
DS89C420/30 chip, assuming a crystal frequency of 11.0592 MHz.

DS89C420/30 Machine Cycle


DELAY: MOV R3,#250

HERE: NOP 1
NOP 1
NOP 1
NOP 1
DJNZ R3,HERE 4

RET

Solution:

The time delay inside the HERE loop is [250( I + I + 1 + I + 4)] x 90 ns = 2000 x 90 ns
= J 80 us, Comparing this with Example 3-16, we see DS89C4xO is about 9 times faster.
(1627 us I 180 ps = 9)

Example 3-21
Write a program to toggle all the bits of PI every 200 ms. Assume that the crystal fre-
quency is 11.0592 MHz, and that the system is using the AT89C51.

Solution:
;Tested for AT89C51 of 11.0592 MHz.

MOV A,#55H
AGAIN: MOV P1,A
ACALL DELAY
CPL A
SJMP AGAIN

;----Time delay
DELAY: MOV R5,#2
HERE1: MOV R4,#180
HERE2: MOV R3,#255
HERE3: DJNZ R3,HERE3
DJNZ R4,HERE2
DJNZ R5,HERE1
RET

2 x 180x 255 x 2 MC x 1.085 us = 199,206 us

86
Example 3-22
Write a program to toggle all the bits of P I every 200 ms. Assume crystal frequenc is
11.0592 MHz and the system is using DS89C420/30/40/50. y

Solution:

;Tested for DS89C420 of 11.0592 MHz.


MOV A,#55H
AGAIN: MOV Pl,A
ACALL DELAY 200m
CPL A
SJMP AGAIN

;----Time delay
DELAY 200m:
MOV R5,#9
HEREl: MOV R4, #242
HERE2: MOV R3,#255
HERE3 : DJNZ R3,HERE3
DJNZ R4,HERE2
DJNZ R5,HEREI
RET

Delay 9 x 242 x 255 x 4 MC x 90 ns = 199,940 IlS

Use an oscilloscope to measure the system square wave period to verify delay.

From the above discussion we conclude that use of the instruction in gen-
erating time delay is not the most reliable method. To get more accurate time
delay we use timers as described in Chapter 9. Meanwhile, to get an accurate time
delay for a given 8051 microcontroller, we must use an oscilloscope to measure
the exact time delay.

See the following Web sites for 8051 products and their
features from various companies:

www.8052.com

www.MicroDigitaIEd.com

87
CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS
SJMP to itself using $ sign . d t short jump to itself
. ograrn we nee 0 h
here there is no monitor pr., f doing that is to use t e
. order Intocases
keep w.
the rrucrocontro IIer busy. A simple way 0
I$n.
sign. That means in plaee of this

HERE: SJMP HERE

we can usc the following:

SJMP $

Review
I.
Questions clesof the '0".
True or false. In the 8051, the machine cycle lasts 12 clock cy

2.
~~:r~;~~~~~ number of machine cycles needed to execute an 8051 instruc-

3. For
tion Question
IS _. 2, what IS
. t h e rnaximu
. m number of cycles needed, and for which
instructions? f 12 MH
. hi c1e for a crystal frcquency 0 z. .
4. Find the mac me cy f 12 MHz find the time delay associated with
5. Assuming a crystal frequency 0 DE1LAy'Subroutine
the loop section of the followmg .
DELAY: MaV R3,#lOO
HERE: Nap
Nap
Nap
DJNZ R3,HERE
RET
6.
True or false. In the DS89C420/30, thc machine cycle lasts 12 clock cycles of
the crystal frequency.

7. Find the machine cycle for a DS89C420/30 if the crystal frequency is


11.0592 MHz.{ 00) <15

SUMMARY

Thc now of a program proceeds sequentially, from instruction to instruc.


tion, unless a Controllransfer instruction is executed. The various types of Control
transfer and
jumps, instructions in Assembly language includc Conditional and unconditional
cal! instructions.

Thc looping action in 8051 ASscmbly language is performed using a spe-


cial instruction, which decrements a COunter and jumps to the top of the loop if the
COunter is nOI zero. Other jump instructions jump conditionally, based on the value
of the carty nag, the accumulator, or bits of the 110 POrt. Unconditional jumps can
be long or shon, depending on the relative value of the target addrcss. Special
tack.
attention IJ1U t be given to the effect of LCALL and ACALL instructions on the

88

CHAPT
PROBLEMS

SECTION 3.1: LOOP AND JUMP INSTRUCTIONS

L In the80SI, ~ing action with the instruction "DJNZ Rx, re I address"


IS limited to iterations .
-- .
2. If a conditional jump is not taken, what is the next instruction to be executed?
3. In calculating the target address for a jump, a displacement is added to the con-
tents of register .. ..
4. The mnemonic SJMP stands for and it is a _-byte instruction.
5. The mnemonic LJMP stands for and it is a _-byte instruction.
6. What is the advantage of using SJMP over LJMP?
7. True or false. The target ofa short jump is within-128 to +127 bytes of the
current PC,
8. True or false. All 8051 jumps are short jumps.
9. Which of the following instructions is (are) not a short jump?
(a) JZ (b) JNC (c) LJMP (d) DJNZ .
10. A short jump is a _-byte instruction. Why?
II. True or false. All conditional jumps are short jumps.
j 2. Show code for a nested loop to perform an action 1000 times.
13. Show code for a nested loop to perform an action 100,000 times.
14. Find the number of times the following loop is performed.
MOV R6,#200
BACK: MOV RS,#100
HERE: DJNZ RS,HERE
DJNZ R6,BACK
15. The target address of a jump backward is a maximum of bytes from
, the current Pc.
16. The target address of a jump forward is a maximum of bytes from
the current PC.

SECTION 3.2: CALL INSTRUCTIONS

17. LCALL is a ~ -byte instruction.


18, ACALL is a .2, -byte instruction.
19, Thc ACALL target address is limited to ~_ bytes from the present Pc.
20, The LCALL target address is limited to bytes from the present Pc.
21, When LCALL is executed, how many bytes of the stack are used?
22. When ACALL is executed, how many bytes of the stack are used?
23. Why do the PUSH and POP instructions in a subroutine need to be equal in
number? K-ap ~ '1~ . .
24. Describe the action associated wah the POP mstruction.
25. Show the stack for the following code.
OOOB 120300 LCALL DELAY
OOOE 80FO SJMP BACK ;keep doing this
0010
0010 _____ this is the delay subroutine

CHAPTER 3: JUMP, LOOP, AND CALL INSTRUCTIONS 89


0300 ORG 300H
0300 DELAY:
0300 7DFF MOV R5, #OFFH ;R5=255
0302 DDFE AGAIN: DJNZ R5,AGAIN ;stay here
0304 22 RET ;return
26. Reassemble Example 3-10 at ORG 200 (instead of ORG 0) and show the stack
frame for the first LCALL instruction.

SECTION 3.3: TIME DELAY FOR VARIOUS 8051 CHIPS

27. Find the system frequency if the machine cycle = 1.2 ~s.t{)Mrlt.
~Find the machine cycle if the crystal frequency is 18 MHz.
29. Find the machine cycle if the crystal frequency is 12 MHz.
JD. Find the machine cycle if the crystal frequency is 25 MHz.
31. True or false. LJMP and SJMP instructions take the same amount of time to
execute even though one is a 3-byte instruction and the other is a 2.byte
instruction.
32. Find the time delay for the
delay subroutine shown to
DELAY:
HERE:
MOV
NOP
R3,#150.] ';i-,
the right, if the system has
an 8051 with frequency of
NOP
NOP
."
., r
• ;;t. ~
,
"-
11.0592 MHz. DJNZ R3,HERE
RET
~
33. Find the time delay for the
delay subroutine shown to DELAY: MOV R3,#200
the right, if the system has HERE: NOP
an 805 J with frequency of NOP
16 MHz. NOP
DJNZ R3,HERE
RET

34. Find the time delay for the


DELAY: MOV
delay subroutine shown to BACK: R5,#100-'
the right, if the system has OV R2,#200· I
AGAIN: MOV
an 8051 with frequency of HERE: R3,#250~ (
11.0592 MHz.
NOP
NOP -:'\.lln.
DJNZ R3,HERE_~j
DJNZ R2 'AGAIN ~
DJNZ R5,BACK 1.
RET
35. Find the time delay for the
delay Subroutine Shown to DELAY; MOV
the right, if the system has AGAIN: R2',# J,dQ )..
MOV R3,#250Ql-
an 8051 with frequency of HERE: op I

G
16 MHz. NOP I
NOp
I
JNZ R3,HERE II
JNZ R2,AGAIN l{-
RET
90

CHAP'
38. Repeat proplem 34 for DS89C420/30.
;J.9~Repeat problem 35 for DS89C420/30.
40. In an AT89C51-based system, explain performance improvement if we replace
the AT89C51 chip with a DS89C420/30. Is it 12 times faster?

ANSWERS TO REVIEW QUESTIONS

SECTION 3.\: LOOP AND JUMP INSTRUCTIONS

I. Decrement and jump if not zero


2. True
3. 2
4. A
5. 3

SECTJON 3.2: CALL INSTRUCTIONS

I. Long CALL and Absolute CALL


2. True
3. The address of where to return is in the stack.
4. Upon executing the RET instruction, the CPU pops off the top two bytes of the slack into the
program counter (PC) register and starts to execute from this new location.
5. 3

SECTION 3.3: TiME DELAY FOR VARIOUS 8051 CHIPS

I. True
2. 1
3. MUL and DIY each lake 4 machine cycles.
4. 12 MHz /12 = I MHz, and MC = 1/1 MHz = 1 us,
5. [100(1 + I + I + 2)] x J us = 500 us = 0.5 milliseconds.
6. False. 11takes 1 clock.
7. 11.0592 MHz/I = 11.0592 MHz; machine cycle is 1/11.0592 MHz = 0.0904 us = 9004 ns

91
CHAPTER 3: JUMP, LO()P, AND CALL INSTRUCTIONS
92
CHAPTER 4

I/O PORT
PROGRAMMING

OBJECTIVES

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

» List the 4 ports of the 8051


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

93
This chapter describes the I/O port programming of the 8051 with many
examples. In Section 4.t, we describe I/O access using byte-size data, and in
Section 4.2, bit manipulation of the IIO ports is discussed in detail.

SECTION 4.1: 8051 I/O PROGRAMMING

In the 8051 there are a total of four ports for 1/0 operations. Examining
Figure 4-1, note that of the 40 pins, a total of 32 pins are set aside for the four ports
PO, P J, P2, and P3, where each port takes 8 pins. The rest of the pins arc desig-
nated as Vrco GND, XTALI, XTAL2, RST, EA, ALE/PROG and PSEN are dis-
cussed in Chapter 8.

PDIP/Cerdip

Pl.0 1 40 Vee
Pl.1 2 39 POO (ADO)
Pl.2 3 38 POl (AD1)
Pl.3 4 37
P1A
8051 P02 (AD2)
5 36 PO.3 (AD3)
P1.5 6
(8031 )
35 POA (AD4)
Pl.6 7 (89420) 34 P05 (ADS)
Pl.7 8 33 P06 (AD6)
RST 9 32 PO.7 (AD7)
(RXD) P3.0 10 31 ENVPP
(TXD) P3.1 11 30 ALEfPROG
(INTO) P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TO) P3A 14 27 P2.6 (A14)
(T1) P3.5 15
26 P25 (A13)
(WR) P3.6 16
25 P2A (A12)
(RD) P3.7 17
24 P2.3 (Al1)
XTAL2 18
23 P2.2 (Al0)
XTALl 19
22 P2.1 (A9)
GND 20
21 P20 (A8)

Figure 4-1. 8051 Pin Diagram

I/O port pins and their functions


The foor ports Pf), P J, P2, and P3 eac . .
A lithe ports upon RESET are confi urcd a. h use 8 pms, making them 8-bit ports.
When the first 0 is written to a pongt b s II1puts, Ica.dy to be used as input pons
. , I ecornes an .
mput, a I must be sent to the port T output. To reconfigurc it as an
mu I. be programmed, as we wi'·t 0 ~se any of these ports as an input port it
de cribc each port. exp am throughout this section F· t '
. Irs, we

94
Port 0
Vec
Port 0 occupies a 10 K

total of 8 pins (pins 32 - ~~~~~~~~


39). It can be used for
r------,
:;: :;: := :;: :~ :;: ~ ~
input or output. To use PO.O1-"'--1-+--+--+-+--+-+-
the pins of port 0 as both PO.11-~~+-+-+-+-:~+- lJ
P02 0
input and output ports, 8051 P03 ~
each pin must be con- POA 0
PO.5j--,------"---+-+_
nected externally to a PO.61---------+--+--
10K-ohm pull-up resistor. PO.7t---------oL--
This is due to the fact that
PO is an open drain, I
unlike PI, P2, and P3 as
'11 '
:--'======-.
'=
Figure 4-2. Port 0 with Pull-Up Resistors
~ __ .-J
we WI soon see. Open
drain is a term used for MOS chips in the same way that open collector is used for
TTL chips. In any system using the 805 j /52 chip, we normally connect PO to pull-
up resistors. See Figure 4-2. In this way we take advantage of port 0 for both input
and output. For example, the following code will continuously send out to port a
the alternating values of 55H and AAH.

;Toggle all bi ts of PO
BACK: MOV A,#55H
MOV PO,A
ACALL DELAY
MOV A,#OAAH
MOV PO,A
ACALL DELAY
SJMP BACK
lt must be noted that complementing 55H (01010101) turns it into AAH
(10 1a 1a I0). By sending 55H and AAH to a given port continuously, we toggle all
the bits of that port.

Port 0 as input

With resistors connected to port 0, in order to make it an input, the 'port


must be programmed by writing I to all the bits. In the following code, port 0 is
configured first as an input port by writing Is to it, and then data is received from
that port and sent to PI.

;Get a byte from PO and send it to P1


MOV A,#OFFH ;A = FF hex
MOV PO,A ;make PO an input port
;by writing all 1s to it
BACK: MOV A,PO ;get data from PO
MOV P1,A ;send it to port 1
SJMP BACK ;keep doing it

95
CHAPTER 4: I/O PORT PROGRAMMING
Dual role of port 0
As shown in Figure 4-1, port 0 is also designated as ADO - AD7, allowing
it to be used for both address and data. When connecting an 8051/31 to an exter-
nal memory. port 0 provides both address and data. The 8051 multiplexes address
and data through port 0 to save pins. We discuss that in Chapter 14.

Port 1
Port I occupies a total of 8 pins (pins I through 8). It can be used as input
or output. In contrast to port 0, this port does not need any pull-up resistors since
it already has pull-up resistors internally. Upon reset, port I is configured as an
input port. The following code will continuously send out to port I the alternating
values 55H and AAH.
;Toggle all bits of PI continuously
MOV A,#55H
BACK: MOV Pl,A
ACALL DELAY
CPL A ;complement (Invert) reg. A
SJMP BACK
Port 1 as input

. .1f port I has been configured as an output port, to make it an input port
agam, It must programmed as such by writing I to all its bits. The reason for this
is discussed in Appendix C.2. In the following code, port I is configured first as
an input port by wntmg Is to it, then data is received from that port and saved in
R7, R6, and R5.

MOV A,#OFFH ;A=FF hex


MOV Pl,A ;make PI an input port
;by writing all Is to it
MOV A, PI ;get data from PI
MOV R7,A ;save it In reg R7
ACALL DELAY ;wait
MOV A,PI ;get another data from PI
MOV R6,A ;save it in reg R6
ACALL DELAY ;wait
MOV A,PI ;get another data from
MOV R5,A PI
isave it in reg R5
Port 2

Port 2 occupies a total of 8 pins ( ins 2


input or output. Just like PI t2d P I through 28). It can be used as
, por oes not need a II . .
already has pull-up resistors intern II U ny pu -up resistors since it
' a y. pon reset port 2 . f .
port. Th e following code will s d .' IS con igurcd as an input
en out contll1uousl t 2
ue 55H and AAH. Thai is all tl . b' f y 0 port the alternating val-
, ie Its 0 P2 toggle continuously.
96

CHAPT
MOV A,#55H
BACK: MOV P2,A
ACALL DELAY
CPL A ;complement reg. A
SJMP BACK
Port 2 as input
. To make port 2 an input, it must programmed as such by writing I to all its
bits. In the following code, port 2 is configured first as an input port by writing Is
to It. Then data IS received from thai port and is sent to PI continuously.

;Get a byte from P2 and send it to PI


MOV A,#OFFH ;A=FF hex
MOV P2,A ;make P2 an input port by
;writing all Is to it
BACK: MOV A,P2 ;get data from P2
MOV Pl,A ;send it to Port 1
SJMP BACK ;keep doing that

Dual role of port 2


In many systems based on the 8051, P2 is used as simple I/O. However,
in 803 l-based systems, port 2 must be used along with PO to provide the 16-bit
address for external memory. As shown in Figure 4-1, port 2 is also designated as
A8 - A 15, indicating its dual function. Since an 8051131 is capable of accessing
64K bytes of extcmal memory, it needs a path for the 16 bits of the address. While
PO provides the lower 8 bits via AO - A7, it is the job of P2 to provide bits A8 -
A 15 of the address. In other words, when the 8051/31 is connected to external
memory, P2 is used for the upper 8 bits of the 16-bit address, and it cannot be used
for I/O. This is discussed in detail in Chapter 14.
From the discussion so far, we conclude that in systems based on 8751,
89C51, or DS589C4xO microcontrollers, we have three ports, PO, PI, and P2, for
I/O operations. This should be enough for most microcontroller applications.
That leaves port 3 for interrupts as well as other signals, as we will see next.
Table 4-1: Port 3 Alternate
Port 3 Functions
Port 3 occupies a total of 8 pins, pins 10 Function Pin
P3 Bit
through 17. It can be used as input or output. P3 RxD 10
P3.0
does not need any pull-up resistors, just as PI TxD II
P3.J
and P2 did not. Although port 3 is configured as P3.2 INTO 12
an input port upon reset, this is not the way it is P3.3 TNTI 13
most commonly used. Port 3 has the additional P3.4 TO 14
function of providing some extremely important P3.5 TI 15
signals such as interrupts. Table 4-1 provides P3.6 WR 16
these alternate functions ofP3. This information P3.7 RD 17
applies to both 8051 and 8031 chips.

97
TER 4: I/O PORT PROGRAMMING

P3.0 and P3.1 are used for the RxD and TxD serial communications sig-
nals. See Chapter 10 to see how they are connected. Bits P3.2 and P3.3 are set
aside for external interrupts, and are discussed in Chapter II. Bits P3.4 and P3.5
are used for timers 0 and I, and are discussed in Chapter 9 where timers are dis-
cussed. Finally, P3.6 and P3.7 are used to provide the WR and RD signals of
external memories connected in 803 I-based systems. Chapter 14 discusses how
they arc used in 803 I-based systems, In systems based on the 8751, 89C51, or
DS89C4xO, pins 3.6 and 3.7 are used for I/O while the rest of the pins in port 3 are
normally used in the alternate function role,

Example 4-1
Write a test program for the DS89C420/30 chip to toggle all the bits of PO, PI, and P2
every 1/4 of a seeond. Assume a crystal frequency of 11.0592 MHz.

Solution:

;Tested for the DS89C420!30 with XTAL = 11.0592 MHz.


ORG o
BACK: MOV A,#55H
MOV PO,A
MOV Pl,A
MOV P2,A
ACALL QSDELAY
;Quarter of a second delay
MOV A,#OAAH
MOV PO,A
MOV Pl,A
MOV P2,A
ACALL QSDELAY
SJMP BACK
;-----------1/4 SECOND DELAY
QSDELAY:
MOV R5, #11
H3: MOV R4, #248
H2: MOV R3, #255
Hl: DJNZ R3, H1
DJNZ ;4 MC for DS89C4xO
R4, H2
DJNZ R5, H3
RET
END

Delay = 11 x 248 x 255 x 4 Me


x 90 ns = 250,430 us
Usc an oscilloscope to verify th d I .
e e ay size.

98
Different ways of accessing the entire 8 bits
In the following code, as in many previous I/O examples, the entire 8 bits
of port 1 are accessed.
BACK: MOV A,#55H
MOV Pl,A
ACALL DELAY
MOV A,#OAAH
MOV Pl,A
ACALL DELAY
SJMP BACK

The above code toggles every bit of PI continuously. We have seen a vari-
ation of the above program before. Now we can rewrite the above code in a more
efficient manner by accessing the port directly without going through the accumu-
lator. This is shown next.

BACK: MOV Pl,#55H


ACALL DELAY
MOV Pl,#OAAH
ACALL DELAY
SJMP BACK

The following is another way of doing the same thing.

MOV A,#55H ;A=55 HEX


BACK: MOV Pl,A
ACALL DELAY
CPL A ; complement reg. A
SJMP BACK

Wc can write another variation of Table 4-2: Reset Value of Some


the above code by using a technique called 8051 Ports
read-modify-write. This is shown at the
Register Reset Value (Binary)
end of this chapter. 11111111
PO
Ports status upon reset Pl 11111111
P2 11111111
Upon reset all ports have value FFH 11111111
P3
on them as shown in Table 4-2. This makes
them input ports upon reset.

Review Questions
tal of ports in the 80S I and each has . bits.
l. Th ere area to -- b hi d
2. ~ I All f the 8051 ports can be used for ot input an output.
T rue or ra se. a .?
3. Which 80S I ports need pull-up resis/tors to funCtIOnfjasandI/O porttp'torts
4. True or s:ra Ise. U pan power-up , the I 0 pins are can igure as ou up.
5. Show simple statements to send 99H to ports P I and P2.
99
CHAPTER 4: 110 PORT PROGRAMMING
SECTION 4.2: 1/0 BIT MANIPULATION PROGRAMMING
\

In this section we further examine 8051 ]/0 instructions. We pay special


attention to I/O bit manipulation since it is a powerful and widely used feature of
the 8051 family.

I/O ports and bit-addressability


Sometimes we need to access only 1 or 2 bits of the port instead of the
entire 8 bits. A powerful feature of80511/0 ports is their capability to access indi-
vidual bits of the port without altering the rest of the bits in that port. Of the four
8051 ports, we can aecess either the entire 8 bits or any single bit without altering
the rest. When accessing a port in single-bit manner, we use 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. For example. "SETB Pl. 5" sets high bit 5 of port
I. Remember that DO is the LSB and D7 is the MSB. For example, the follow-
ing code toggles bit P 1.2 continuously.

BACK: CPL P1.2 ;complement PI.2 only


ACALL DELAY
SJMP BACK

;another variation of the above program follows


AGAIN: SETB PI.2 ;change only PI.2=high
ACALL DELAY
CLR PI.2 ;change only PI.2=low
ACALL DELAY
SJMP AGAIN

bit i Notice that Pl.2 is the third bit of PI, since the first bit is PI.O, the second
It IS P 1.1, and so on. Table 4- 3 shows the bits of the 8051 I/O rt S E
4-2 for an example of bit manipulation of I/O bits Not. pOE s. ele xample
d . . Ice III xamp e 4-2 that
unuse portions of ports I and 2 are undisturbed. This single-bit addressability of
I/O ports IS one of most powerful features of the 8051 . .
mlcroeontroller and IS
among t IlC reasons that many designers choose tl 8051 .
t II W ·11 lC over other rmcrocon-
ro ers. e WI see the use of the bit-addrcssability f I/O . fu
ters. ° ports 111 ture chap-

Table 4-3: Single-Bit Addressability of Porls


PO PI P2 P3 Pori Bit
PO.O P 1.0 no P10 DO
PO.I PI.I P2.J Pli 01
PO.2 P 1.2 P2.2 P12 02
POJ P 1.3 P2.3 P3J 03
POo4 PIA P204 P304 04
PO.5 PI.5 P2.5 P15 05
PO.6 P 1.6 P2.6 P3.6 06
PO.7 PI.7 P2.7 P3.7 07
Example 4-2
Write the following programs.
(a) Create a square wave of 50% duty cycle on bit 0 of port I.
(b) Create a square wave of 66% duty cycle on bit 3 of port 1.

Solution:

(a) The 50% duty cycle means that the "on" and "off' states (or the high and low
portions of the pulse) have the same length. Therefore, we toggle Pl.O with a
time delay in between each state.

HERE: SETB PI. 0 ;set to high bit 0 of port 1


LCALL DELAY ;call the delay subroutine
CLR PI. 0 ; Pi. 0=0
LCALL DELAY
SJMP HERE ;keep doing it

Another way to write the above program is:

HERE: CPL PI. 0 ;complement bit o of port 1


LCALL DELAY ;call the delay subroutine
SJMP HERE ;keep doing it

8051

Pl.D I-- J
(b) The 66% duty cycle means the "on" state is twice the "off' state.

Pl.3 ;set port 1 bit 3 high


BACK: SETB
DELAY ;call the delay subroutine
LCALL
;call the delay subroutine again
LCALL DELAY
;clear bit 2 of port 1(Pl.3=low)
CLR Pi.3
;call the delay subroutine
LCALL DELAY
SJMP BACK ;keep doing it

8051

P1.3 I-- J
101
CHAPTER 4: 1/0 PORT PROGRAMMING
Table 4-4: Single-Bit Instructions
Instruction Function
SETB bit Set the bit (bit I)
CLR bit Clear the bit (bit 0)
CPL bit Complement the bit (bit NOT bit)
JB bit,target Jump to target if bit I (jump ifbit)
JNB bit,target Jump to target ifbit 0 (jump ifno bit)
JBC bit.target Jump to target ifbit - I, clear bit (jump if bit, then clear)

Table 4-4 lists the single-bit instructions for the 8051. We will see the use
of these instructions throughout future chapters.

Checking an input bit


The JNB (jump if no bit) and JB (jump if bit = I) instructions arc also
widely used single-bit operations. They allow you to monitor a bit and make a
decision depending on whether it is 0 or I. Instructions JNB and JB can be used
for any bits of lIO ports 0, 1,2, and 3, since all ports arc bit-addressable. However,
most of port 3 is used for interrupts and serial communication signals, and typi-
cally is not used for any I/O, either single-bit or byte-wise. This is discussed in
Chapters 10 and II. Table 4-5 shows a list of instructions for reading the ports.

Example 4-3

Write a program to perform the following:


(a) keep monitoring the Pl.2 bit until it becomes high
(b) when P 1.2 becomes high, write value 45H to port 0
(c) send a high-to-Iow (H-to-L) pulse to P2,3

Solution:

SETB PI.2
MOV A,#45H ;make PI.2 an input
AGAIN: ;A=45H
JNB PI.2,AGAIN
MOV PO ,A ;get out when PI.2=1
SETB P2.3 ;issue A to PO
CLR P2.3 ;make P2. 3 high
;make P2.3 low for H-to-L
In this program, instruction "JNB PI 2 AG" .
stays in the loop as long as P 1.2 is low WhenPI' AIN (JNB means Jump if no bit)
writes the value 45H to port 0 and' H·2 becomes high, It gets out of the loop
lions SETB and CLR. ' creates an -to-L pulse by the sequence of instruc~
Table 4-5: Instructions For Reading an Input Port
Mnemonic Example Description
MOV A, PX MOV A, P2 Bring into A the data at P2 pins
JNB PX. Y, .. JNB P2. I, TARGET Jump if pin P2.l is low
JB PX. Y, .. JB Pl. 3, TARGET Jump if pin P1.2 is high
MOV C, px. Y MOV C, P2.4 Copy status of pin P2.4 to CY

Example 4-4
Assume that bit P2.3 is an input and represents the condition of an oven. If it goes high,
it means that the oven is hot. Monitor the bit continuously. Whenever it goes high, send
a high-to-low pulse to port P 1.5 to tum on a buzzer.

Solution:

HERE:JNB P2.3,HERE ;keep monitoring for high


SETB Pl. 5 ;set bit P1.5=1
CLR Pl. 5 ;make high-to-Iow
SJMP HERE ;keep repeating
vee
SwitchJ
-1
8051

4.7k
.~
.....
: i>
---IP2.3

74LS04

Example 4-5
A switch is connected to pin P 1.7. Write a program to check the status of SW and per-
form the following:
(a) If SW=O, send letter 'N' to P2.
(b) IfSW=I, send letter 'Y'toP2.

Solution:
;make Pl.? an input
SETB Pl.?
JB Pl.2,OVER ;jump if Pl. ?=l
AGAIN: ;SW=O, issue 'N' to P2
MOV P2,#'N'
;keep monitoring
SJMP AGAIN
;SW=l, issue 'Y' to P2
OVER: MOV P2,#'Y'
'keep monitoring
, i
SJMP AGAIN

103
CHAPTER 4: I/O PORT PROGRAMMING
Reading a single bit into the carry flag
We can also use the carry flag to save or examine the status of a single bit
of the port. To do that, we use the instruction "Mav C, Px. v" as shown in the
next two examples.

Example 4-6
A switch is connected to pin PI. 7. Write a program to check the status of the switch and
perform the following:
(a) If switch = 0, send letter 'N' to P2.
(b) Ifswitch = I, send letter 'Y'toP2.

Use the carry flag to check the switch status. This is a repeat of the last example.

Solution:

SETB PI. 7 ;make PI. 7 an input


AGAIN: Mav C,Pl.2 ;read the sw status into CF
JC OVER ;jump if SW = 1
MaV P2,#'N' ;SW = 0, issue 'N' to P2
SJMP AGAIN ;keep
OVER: monitoring
MOV P2,#'Y' ;sw = 1, issue 'y' to P2
SJMP AGAIN ;keep monitoring

Example 4-7

A switch is connected to pin PI.O and an LED to pin P2.7.


status of the switch and send it to the LED Write a program to get the

Solution:

SETB PI. 7
AGAIN: Mav
Mav
C, PI.
P2.7,C
° ;make
;read
Pl.7 an input
the SW status into CF
SJMP ;send the SW status to LED
AGAIN
;keep repeating

Note: The instruction "Mav P2 7


. . , PI
not exist, However, "MaV P2 PI"'·
" .
°
IS wr .
'. ong since such an instruction does
' IS a valid Instruction.

Notice in Examples 4-6 and 4-7


data (rom the port. how the carry flag is used to get a bit of
Reading input pins vs. port latch

In reading a port, some instructions read the status of port pins while oth-
ers read the status of an internal port latch. Therefore, when reading ports there
are two possibilities:

I. Read the status of the input pin.


2. Read the internal latch of the output port.

We must make a distinction between these two categories of instructions


since confusion between them is a major source of errors in 8051 programming,
especially where external hardware is concerned. We discuss these instructions
briefly. However, readers must study and understand the material on this topic and
on the internal working of ports that is given in Appendix C.2.
Instructions for reading input ports
As tated earlier, to make any bit of any 8051 pan an input port, we must
write I (logic high) to that bit. After we configure the port bits as input, we can
use only certain instructions in order to get the external data present at the pins into
the CPU. Table 4-6 shows the list of such instructions.

Reading latch for output port


Some instructions read the contents of an internal port latch instead of
reading the status of an external pin. Table 4-6 provides a list of these instructions.
For example, look at the "ANL PI, A" instruction. The sequence of actions taken
when such an instruction is executed is as follows.
I. The instruction reads the internal latch of the port and brings that data into the
CPU.
2. This data is ANDed with the contents of register A.
3. The result is rewritten back to the port latch.
4. The port pin data is changed and now has the same value as the port latch.

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


Mnemonic Example
ANL Px ANL PI,A
ORL Px ORL P2,A
XRL Px XRL PO,A
JBC PX.Y,TARGET JBC PI.I,TARGET
CPL PX.Y CPL PI.2
INC Px INC PI
DEC Px DEC P2
DJNZ PX.Y,TARGET DJNZ PI,TARGET
MOV PX.Y,C MOV PI.2,C
CLR PX.Y CLR P2.3
SETB PX.Y SETB P2.3
Note: x is 0, I, 2, or 3 for PO - P3.

105
CHAPTER 4: 1/0 PORT PROGRAMMING
From the above discussion, we conclude that the instructions that read the
port latch normally read a value, perform an operation (and possibly change it),
then rewrite it back to the port latch. This is often called "Read-Modify-Write".

Read-modify-write feature
The ports in the 8051 can be accessed by the read-modify-write technique.
This feature saves many lines of code by combining in a single instruction all three
actions of (I) reading the port, (2) modifying its value, and (3) writing to the port.
The following code first places 01010101 (binary) into port I. Next, the instruc-
tion "XLR P1, #OFFH" performs an XOR logic operation on PI with 1111 1111
(binary), and then writes the result back into PI.
MOV P1,#55H ;P1 = 01010101
AGAIN: XLR P1, #OFFH ;EX-OR P1 with 11111111
ACALL DELAY
SJMP AGAIN
Notice that the XOR of S5H and FFH gives AAH. Likewise, the XOR of
AAH and FFH gives 551-l.Logic instructions arc discussed in Chapter 6.

Review Questions
I. True or false. The instruction "SETB P2. 1" makes pin P2.1 high while leav-
ing other bits of P2 unchanged.
2. Show one way to toggle the pin P 1.7 continuously using 8051 instructions
3. Using the mstructim, "JNB P2 . 5, HERE" assumes that bit P2.5 is' an
____ (input, output). .
4. Write instructions to get the status of P2.7 and put it on P2.0.
5. Write instructions to toggle both bits of PI 7 a d PI 0 .
. n . continuously.

CAUTION
We strongly recommend that you study Section C 2 (A di .
you are connecting any external hard
Failure to use the right instruction or the
can damage the ports of your 8051 system.
:r~t
. ppen IX C) If
~o your 8051 system.
onneclton to port pins

SUMMARY

This chapter foeused on the 110 orts otr .


8051, PO, PI, P2, and P3, each use . p . of the 8051. The four ports of the
can be used for input or output P 8 Plns, making them 8-bit ports. These port
a
3 ean be used to provide inle~u ~~ndcan be used for e.ither address or data. Po~
In tructiong of the 8051 were cxpfained :enal commul1lcation signals. Then 110

also showed the bit-addrcssability ofth~ 8nadsIIlumerous


examples were given We
POrts. .
106
PROBLEMS

SECTION 4.1: 8051 I/O PROGRAMMING

I. The. 8051 DIP package is a __ -pin package.


2. Which pms are assigned to Vee and GND?
3. In the 8051, how many pins are designated as I/O port pins?
4. How many pins are designated as PO and which number are they in the DIP
package?
5. How many pins are designated as PI and which number arc they in the DIP
package?
6. How many pins are designated as P2 and which number arc they in the DIP
package? .
7. How many pins are designated as P3 and whieh number are they in the 01 P
package?
8. Upon RESET, all the bits of ports are configured as __ (input, output).
9. In the 8051, which port needs a pull-up resistor in order to be used as I/O?
10. Which port of the 8051 does not have any alternate function and can be used
solely for I/O?
II. Write a program to get 8-bit data from PI and send it to ports PO, P2, and P3.
12. Write a program to get 8-bit data from P2 and send it to ports PO and Pl.
13. In P3, which pins are for RxO and TxO?
14. At what memory location does the 8051 wake up upon RESET? What is the
implication of that?
15. Write a program to toggle all the bits of PI and P2 continuously
(a) using AAH and 55H (b) using the CPL instruction.

SECTION 4.2: [/0 BIT MANIPULATION PROGRAMMING

16. Which ports of the 8051 are bit-addressable?


17. What is the advantage of bit-addressability for 805 I ports?
18. When PI is accessed as a single-bit port, it is designated as _
19. Is the instruction "CPL Pl" a valid instruction?
20. Write a program to toggle P 1.2 and P 1.5 continuously without disturbing the
rest of the bits.
21. Write a program to toggle P1.3, P1.7, and P2.5 continuously without disturb-
ing the rest of the bits.
22. Write a program to monitor bit P1.3. When it is high, send 55H to P2.
23. Write a program to monitor the P2.7 bit. When it is low, send 55H and AAH
to PO continuously.
24. Write a program to monitor the P2.0 bit. When it is high, send 99H to PI. If
it is low send 66H to PI.
25. Write a ~rogram to monitor the P1.5 bit. When it is high, make a low-to-high-
to-low pulse on P1.3.
26. Write a program to get the status of P 1.3 and put it on P 1.4.
27 The PI 4 refers to which bit of PI?
28'. W··rite a progra m to get the status of PI .7 and PI.6 and put them on PI.O and
PI. 7, respectively.
107
CHAPTER 4: I/O PORT PROGRAMMING
---
ANSWERS TO REVIEW QUESTIONS

scno 4.1' 051 110 PROGRAMMING

I 4.
2. lruc
) PO
4 False
5. M V 1'1.# 9H
\1 V 1'2.#9911

'''ClI , 4.2: I/O BII' MANIPULATIO PROGRAMMING

I True

2 III: l'l.PI.7
JMP III

3 Inpul

M V '.1'2.7
M V no.
5. III PLPI.7
PL 1'1.0
JMP III
CHAPTER 5 (;\JtV\5

8051 ADDRESSING
MODES

OBJECTIVES

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

» List the fiveaddressing modes of the 8051 microcontroller


» Contrast and compare the addressing modes
» Code 8051 Assembly language instructions using each addressing mode
» Access RAM using various addressing modes
» List the SFR (special function registers) addresses
» Discuss how to access the SFR ,

» Manipulate the stack using direct addressing mode


» Code 8051 instructions to manipulate a look-up table
» Access RAM, 110, and ports using bit addresses
» Discuss how to access the extra 128 bytes of RAM space in the 8052

109
The CPU can access data in various ways. The data could be in a register,
or in memory, or be provided as an immediate value. These various ways of
accessing data are called addressing modes. In this chapter we discuss 8051/52
addressing modes in the context of some examples. ..
The various addressing modes of a microprocessor arc determined when It
is designed, and therefore cannot be changed by the programmer. The 8051 pro-
vides a total of five distinct addressing modes. They are as follows:

(1 ) immediate-'\).\o. ~ ~~ .
(2) register :~\"~ .&l&.... ')¢\"\tr'\Q'l"O"'Wc(>.-{IiN'
(3) direct ~-. . . ~~
(4) register indirect ~~ ~'Io~
(5) indexed .

In Section 5.1 we look at immediate and register addressing modes. In


Section 5.2 we cover accessing memory using the direct, register indirect, .and
indexed addressing modes. Section 5.3 discusses the bit-addressability of RAM,
registers, and 1/0 ports. In Section 5.4 we show how to access the extra 128 bytes
of RAM in the 8052.

SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES

In this section, first we examine immediate addressing mode and then reg-
ister addressing mode.

Immediate addressing mode

In this addressing mode, the source operand is a constant. In immediate


addressing mode, as the name implies, when the instruction is assembled, the
operand comes Immediately after the opcodc: otiee tllat tile 'mmediate data must
be preceded ,tjy the pound sign, "#". This adaressing mo e can be used to 10 d
linFormation into any of the registers, including the DPTR.register. Examples fol-
ow.

MOV A.1I25H ;load 25H into A


MOV R4.1162 ;load the decimal
MOV B.#40H value 62 into R4
;load 40H into B
MOV DPTR.#4521H
;DPTR=4512H

Although the DPTR register is 16 bi .


registers, DPH and DPL where DPH' -hl\'t can also be accessed as two 8-bit
Look at the folloWing code. IS t c rgh byte and DPL is the low byte.

MOV DPTR.#2550H
is the same as:
MOV DPL. #50H
MOV DPH. #25H

110
Also notice that the following would produce an error since the value is
larger than 16 bits. ,

MOV DPTR,#68975 ;illegal!! value> 65535 (FFFFFH)

We can usc the EQU directive to access immediate data as shown below.

COUNT EQU 30

MOV R4,#COUNT ;R4~IE(30~IEH)


MOV DPTR,#MYDATA ;DPTR~200H

ORG 200H
MYDATA: DB "Amer i cav

Notice that we can also use immediate addressing mode to send data to
8051 ports. For example, "MOV PI,#55H" is a valid instruction.

Register addressing mode


Register addressing mode involves 'the use of registers to hold the data to
be manipulated. Examples ofregister addressing mode follow.

MOV A,RO ;copy the contents of RO into A


MOV R2,A iCOPY the contents of A into R2
ADD A, R5 iadd the contents of R5 to contents of A
ADD A,R7 iadd the contents of R7 to contents of A
MOV R6,A ;save accumulator in R6

It should be noted that the source and destination registers must match in
size. In other words, coding "MOV DPTR, A" will give an error, since the source
is an 8-bit register and the destination is a 16-bit register. See the following.

MOV DPTR,#25F5H
MOV R7,DPL
MOV R6,DPH

Notice that we can move data between the accumulator and Rn (for n = 0
to 7) but movement of data between Rn registers is not allowed. For example, the
instruction "MOV R4, R 7" is invalid.
In the first two addressing modes, the operands are either inside one of the
registers or tagged along with the instruction itself. In most programs, the data to
be processed is often in some memory location of RAM or in the code space of
ROM. There are many ways to access this data. The next section describes these
different methods.

CHAPTER 5: 8051 ADDRESSING MODES III


Review Problems . ?

. controller make up
C th programmer 0 f a micro . newR3 addressing mode .
I. an e. . I d 10000000 (binary) Into .
2 Show the instrucuon to oa DPTR"
. . h f, II ing invalid? "MOV R2, b d
3. ~:~ ~~ ~a~seoDOp~Ris a 16-bit register that is also accessible in low- ytc an
4.

high-byte
5. Is formats, counter ) a Iso available in low-byte and high-byte formats?
the PC (program

SECr/ON 5.2: ACCESSING MEMORY USING VARIOUS


ADDRESSING MODES

We can usc direct or register indirect addressing modes to access data


stored cirhcr in RAM or registers of the 8051. This topic win be discussed thor-
oughly in this section. We will also show how to access on-chip ROM contammg
data using indexed addressing mode.

Direct addressing mode

As mentioned in Chapter 2, there are 128 bytes of RAM in the 8051. The
RAM has been assigned addresses 00 to 7FH. The following is a summary of the
allocation of these 128 bytes.
I. RAM locations 00 - IFH are assigned to the register banks and stack.
2. RAM locations 20 - 2FH arc set aside as bit-addressable space to save single-
bit data. This is discussed in Section 5.3.
3. RAM locations 30 - 7FH arc available as a place to save byte-sized data.
Although the entire 128 bytes of RAM can be accessed using direct
addressing mode, it is most often used to access RAM locations 30 _ 7FH. This is
due to the fact that register bank locations arc accessed by the register names of
RO- R7, but there is no such name for other RAM locations. In the direct address-
ing mode, the data is in a RAM mcmory location whose address is known, and this
address is given as a part of the instruction. Contrast this with immediate address-
ing mode, in which the operand itself is provided with the instruction. The "#"
sign distinguishes between the two modes. Sec the examples below, and note the
absence of the "#" sign.

Mav RO,40H
Mav 56H,A ;save Content of RAM lOcation 40H in RO
nov R4, 7FH ;save content of A in RAM location 56H
;mOve contents of RAM location 7FH to R4

As diseusscd earlier, RAM locations 0 to 7 are allocated to bank 0 registers


RO - R7. These registers can be acceSsed in two ways, as shown below.
Mav A,4
;is same as
MaV A, R4
;which means
copy R4 into
A
Mav A,7
iis same as
MaV A,R7
;which means
copy R7 into
A
112
MOV A,2 ;is the same as
MOV A,R2 ,which means copy R2 into A

MOV A,O ;is the same as


MOV A, RO ,which means copy RO into A

. The above examples should reinforce the importance of the "#" sign in
8051 msrructrons. See the following code.

MOV R2, #5 ,R2 with value 5


MOV A,2 ;copy R2 to A (A~R2~05)
MOV B,2 ;copy R2 to B (B~R2~05)
MOV 7,2 ;copy R2 to R7
;since "MOV R7,R2" is invalid

Although it is easier to use the names RO - R7 than their memory address-


es, RAM locations 30H to 7FH cannot be accessed in any way other than by their
addresses since they have no names.

SFR registers and their addresses


Among the registers we have discussed so far, we have seen that RO - R7
are part of the 128 bytes of RAM memory. What about registers A, B, PSW, and
DPTR? Do they also have addresses? The answer is yes. In the 8051, registers A,
B, PSW, and DPTR are part of the group of registers commonly referred to as SFR
(special function registers). There are many special function registers and they are
widely used, as we will discuss in future chapters. The SFR can be accessed by
their names (which is much easier) or by their addresses. For example, register A
has address EOH, and register B has been designated the address FOH, as shown in
Table 5-1. Notice how the following pairs of instructions mean the same thing.

MOV OEOH,#55H ;is the same as


MOV A,#55H ;which means load 55H into A (A~55H)

MOV OFOH,#25H ;is the same as


MOV B,#25H ;which means load 25H into B (B~25H)

MOV OEOH,R2 ;is the same as


MOV A,R2 ;which means copy R2 into A

MOV OFOH,RO ;is the same as


MOV B,RO ;which means copy RO into B

MOV PI, A ;is the same as


MOV 90H,A ,which means copy reg A to PI

113
CHAPTER 5: 8051 ADDRESSING MODES
Table 5-1 lists the 8051 special function registers (SFR) and their address-
. The following two points should be noted about the SFR addresses,

I. The pecial function registers have addresses between 80H and FFH. These
addrc se arc above 80H, since the addresses 00 to 7FH arc addresses of RAM
mem ry in ide the 8051 , .
2. 'ot all the addres space of 80 to FF is used by the SFR, The unused locations
80H to FFH arc reserved and must not be used by the 8051 programmer.

Table 5-1: 8051 pecial Function Register (SFR) Addresses


yrnbol Name Address
• Accumulator OEOH
B register OFOH
Program starus word ODOH
tack pointcr 81 H
Data pointer 2 bytes
Low byte 82H
High byte 83H
Port 0 80H
Port I 90H
Port 2 OAOH
Port 3 OBOH
Interrupt priority control OB8H
Intcrrupt enable control OA8H
Timer/counter mode control 89H
Timer/counter control 88H
Timer/counter 2 control OC8H
Timer/counter mode control OC9H
8CH
8AH
8DH
8BH
OCDH
Timer/counter 2 low byte
OCCH
T/ 2 capture register high byte
OCBH
OCAH
erial control
98H
Serial data buffer
P 0 Power control 99H
• Bit-addrc sable 87H

Regarding direct addressing mod '


addre ' aluc is limited [0 one byte, 00 _ei:;otlee the fOllowing two points: (a) the
I~ limited to accessing RAM I' H, which means this addressing In d
ccanons and rcgi 't I' 0 e
you examme the 1st file for an A b IS crs ocated inside the 8051 (b) if
FR . , ssem ly languag . I
, regl ters name arc replaced with tl . d e program, you will sec that the
icrr a dresses as listed in Table 5-1,
114
Example 5-1

Write eode to send 55H to ports P I and P2, using (a) their names, (1:» their addresses.

Solution:

(a) MOV A,#55H ;A;55H


MOV Pl,A ;Pl;55H
MOV P2,A ;P2;55H

(b) From Table 5-1, PI address = 90H; P2 address == AOH


MOV A,#55H ;A;55H
MOV 90H,A ;Pl;55H
MOV OAOH,A ;P2;55H

,
Stack and direct addressing mode
Another major use of direet addressing mode is the stack. In the 8051 fam-
ily, only direet addressing mode is allowed for pushing onto the stack. Therefore,
an instruetion such as "PUSH A" is invalid. Pushing the accumulator onto the
staek must be coded as "PUSH OEOH" where OEOH is the address ofregister A.
Similarly, pushing R3 of bank 0 is coded as "PUSH 03".Direct addressing mode
must be used for the POP instruction as well. For example, "POP 04" will pop
the top of the stack into R4 of bank O.
Example 5-2
Show the code to push R5, R6, and A onto the staek and then pop them baek them into
R2, R3, and B, where register B = register A, R2 = R6, and R3 = R5.

Solution:

PUSH 05 ;push R5 onto stack


PUSH 06 ;push R6 onto stack
PUSH OEOH ;push register A onto stack
POP OFOH ;pop top of stack into register B

illOW register B register A


;

POP 02 ;pop top of stack into R2


;TIOW R2 R6
;

POP 03 ;pop top of stack into R3


;TIOW R3 ; R5

Register indirect addressing mode


In the register indirect addressing mode, a register is used as a pointer to
the data. If the data is inside the CPU, only registers RO and R I are used for this
purpose. In other words, R2 - R7 cannot be used to hold the address of an operand
located in RAM when using this addressing mode. When RO and RI are used as

115
CHAPTER 5: 8051 ADDRESSING MODES
pointers, that is, when they hold the addresses of RAM locations, they must be pre-
ceded by the "@" sign, as shown below.

Mav A,@RO ;move contents of RAM location whose


;address is held by RO into A
MaV @Rl,B ;move contents of B into RAM location
;whose address is held by Rl

Notice that RO (as well as R I) is preceded by the "@" sign. In the absence
of the "@" sign, MOY will be interpreted as an instruction moving the contents of
register RO to A, instead of the contents of the memory location pointed to by RO.
Example 5-3

Write a program to copy the value 55H into RAM memory locations 40H to 45H using
(a) direct addressing mode,
(b) register indirect addressing mode without a loop, and
(c) with a loop.

Solution:
(a)
MaV A, #55H ;load A with value 55H
Mav 40H,A ;copy A to RAM location 40H
Mav 41H,A ;copy A to RAM location 41H
Mav 42H,A ;copy A to RAM location 42H
Mav 43H,A ;copy A to RAM location 43H
Mav 44H,A ;copy A to RAM location 44H
(b)
MOV A,#55H ;load A with value 55H
Mav RO,#40H ;load the pointer. RO=40H
MOV @RO,A r copy A to RAM location
INC RO RO points to
;increment pointer. Now RO=41H
MaV @RO,A ;copy A to RAM location RO
INC RO points to
;increment pointer. Now RO=42H
MOV @RO,A ;copy A to RAM location
INC RO RO points to
;increment pointer. Now RO=43H
MOV @RO,A ;copy A to RAM location RO
INC RO points to
;increment pointer. Now RO=44H
MOV @RO,A
(c)
MOV A,#55 ;A=55H
MOV RO,#40H ;load pointer.
MOV RO=40H, RAM address
R2,#05 ;load counter, R2=5
AGAIN: MOV
@RO,A ;copy 55H to RAM location RO .
INC RO .' , pOlnts to
DJNZ ,lncrement RO pointer
R2,AGAIN ;loop until
counter = zero

116
Advantage of register indirect addressing mode
. . One of the advantages of register indirect addressing mode is that it makes
aeeessmg data dynamic rather than static as in the ease of direct addressing mode.
Exa~pl.e 5-3 shows two eases of copying 55H into RAM locations 40H to 45H.
Notice 111 solution (b) that there are two instructions that are repeated numerous
tImes: We can create a loop with those two instructions as shown in solution (c).
Solution (c) IS the most efficient and is possible only because of register indirect
addressing mode. Looping is not possible in direct addressing mode. This is the
main difference between the direct and register indirect addressing modes.
Example 5-4

Write a program to clear 16 RAM locations starting at RAM address 60H.

Solution:
CLR A ;A=O
MOV Rl,#60H ;load pointer. Rl=60H
MOV R7,#16 ;load counter, R7=16 (10 in hex)
AGAIN: MOV @Rl,A ;clear RAM location R1 points to
INC Rl ;increment R1 pointer
DJNZ R7,AGAIN ;loop until counter = zero

An example of how to use both RO and RI in the register indirect address-


ing mode in a block transfer is given in Example 5-5.
Example 5-5
Write a program to copy a block of 10 bytes of data from RAM locations starting at 35H
to RAM locations starting at 60H.

Solution:
MOV RO,#35H ;source pointer
MOV Rl,#60H ;destination pointer
MOV R3,#10 ;counter
BACK: MOV 'A,@RO ;get a byte from source
;copy it to destination ,
MOV @Rl,A
INC RO ;increment source pointer
INC Rl ,'increment destination pointer
DJNZ R3,BACK ;keep doing it for all ten bytes

Limitation of register indirect addressing mode in the 8051


As stated earlier, RO and RI are the only registers that can be used for
pointers in register indirect addressing mode. Since RO and RI are 8 bits wide,
their use is limited to accessing any informarion in the mtemal RAM (scratch pad
memory of 30H - 7FH, or SFR). However, there are times when we need to access
data stored in external RAM or in the code space of on-chip ROM. Whether
accessing externally connected RAM or on-chip ROM, we need a 16-bit pointer.
In such eases, the DPTR register is used, as shown next.

117
CHAPTER 5: 8051 ADDRESSING MODES
Indexed addressing mode and on-chip ROM access
Indexed addressing mode is widely used in accessing data elements of
look-up table entries located in the program ROM space of the 8051. The instruc-
tion used for this purpose is "MOVCA, @A+DPTR". The 16-bit register DPTR and
register A are used to form the address ofthc data clement stored in on-chip ROM.
Because the data clements are stored in the program (code) space ROM of the
8051, the instruction MOVC is used instead ofMOV. The "C" means code. In this
instruction the contents of A arc added to the 16-bit register DPTR to form thc 16-
bit address of the needed data. See Example 5-6.

Example 5-6

In this program, assume that the word "USA" is burned into ROM locations starting at
200H, and that the program is burned into ROM locations starting at O.Analyze how the
program works and state where "USA" is stored after this program is run.

Solution:

ORG OOOOH
;burn into ROM starting at 0
MOV DPTR,#200H
;DPTR;200H look-up table address
CLR A ;clear A(A;O)
MOVC A,@A+DPTR
;get the char from code space
MOV RO,A
;save it in RO
INC DPTR
;DPTR;201 pointing to next char
CLR A
;clear A(A=O)
MOVC A,@A+DPTR
;get the next char
MOV Rl,A
;save it in Rl
INC DPTR
;DPTR;202 pointing to next char
CLR A
; clear A (A=O)
MOVC A,@A+DPTR
;get the next char
MOV R2,A
;save it in R2
HERE:SJMP HERE
;stay here
;Data is burned into
code space starting at 200H
ORG 200H
MYDATA: DB "USA"
END
;end of program

In the above program ROM locations 200H 2


200= ('U') 20h ('S') 202= ('A")- 02H have the following contents.
Wc start with DPTR = 200H, and A = 0 The inst . "
the contents of ROM location 200H 200H 0 ~ctlOn MOVC.A, @A+DPTR"moves
tains 55[-[,the ASCII value for "U" Th: . + - 200H) to register A. Register A con-
to make DPTR = 20 IH A is set t 0 IS IS moved to RO. Next, DPTR is incremented

20 IH, which holds cha~acter "S"o A~~e:1I1hto get the contents of the next ROM location
53H, and R2 = 41H the ASCII 'I ,t IS program IS run, we have RO = 55H Rl =
) va ues lor the characters "U", "S" and "A", '
118
Example 5-7

Assuming that R~M space starting at 250H contains "America", write a program to
transfer the bytes II1toRAM locations starting at 40H.

Solution:
; (a) This method uses a counter
ORG 0000
MOV DPTR,#MYDATA ;load ROM pointer
MOV RO,#40H ;load RAM pointer
MOV R2,#7 ;load counter
BACK: CLR A ;A = 0
MOVC A,@A+DPTR ;move data from code space
MOV @RO,A ;save it in RAM
INC DPTR ;increment ROM pointer
INC RO ;increment RAM pointer
DJNZ R2,BACK ;loop until counter=O
HERE: SJMP HERE

;----------On-chip code space used for storing data


ORG 250H
MYDATA: DB "AMERICA"
END

; (b) This method uses null char 'for end of string


ORG 0000
MOV DPTR,#MYDATA ;load ROM pointer
MOV RO,#40H ;load RAM pointer
BACK: CLR A ;A=O
MOVC A,@A+DPTR ;move data from code space
JZ HERE ;exit if null character
MOV @RO,A ;save it in RAM
INC DPTR ;increment ROM pointer
INC RO ;increment RAM pointer
SJMP BACK ;loop
HERE: SJMP HERE

;----------On-chip code space used for storing data


ORG 250H
MYDATA: DB "AMERICA", 0 ;notice null char for
;end of string
END

Notice the null character, 0, indicating the end of the string, and how we use the
JZ instruction to detect that.

119
CHAPTER 5: 8051 ADDRESSING MODES
Look-up table and the MOVe instruction
The look-up table is a widely used concept in microprocessor program-
ming. It allows access to elements of a frequently used table with minimum oper-
ations. As an example, assume that for a certain application we need x2 values in
the range of 0 to 9. We can use a look-up table instead of calculating it. This is
shown in Example 5-8.
Example 5-8
Write a program to get the x value from P I and send x2 to P2, continuously.

Solution:
ORG o
MOV DPTR,#300H ,load look-up table address
MOV A, #OFFH ,A=FF
MOV Pl,A ,configure PI as input port
BACK: MOV A,Pl ;get X
MOVC A,@A+DPTR ,get X squared from table
MOV P2,A ,issue it to P2
SJMP BACK ;keep doing it

ORG 300H
XSQR_TABLE:
DB 0,1,4,9,16,25,36,49,64,81
END

Notice that the first instruction could be replaced with "MOV DPTR, #XSQR TABLE"

Example 5-9
Answe~ the following questions for Example 5-8.
(a) Indicate the content of ROM locations 300 _ 309H.
(b) At what ROM location is the square of 6, and what value should b ?
(c) Assume that PI bas a value of9' What I . P '. e there.
. va ue IS at 2 (in binary)?
Solution:

(a) All values are in hex.


300 = (00) 301 = (01) 302
304 = (10) = (04) 303 = (09)
4 x 4 = 16
305 = (19) = 10 in hex
5 x 5 = 25
306 = (24) = 19 in hex
6 x 6 = 36
307 = (31) = 24H
308 = (40) 309
(51)=
(b) 306H; it is 24H

(c) OIOIOOOIB, whieh is 51H and 81 in decimal (92 = 81).

120
In addition to being used to access program ROM, DPTR can be used to
access memory externally connected to the 805 I. This is discussed in Chapter 14.
. . Another register used in indexed addressing mode is the program counter.
This IS discussed In Appcndix A.
In many of the examples above, the MOVinstmction was used for the sake
of clarity, even though one can use any instruction as long as that instruction sup-
ports the addressing mode. For example, the instruction "ADD A,@RO" would
add the contents of the memory location pointed to by RO to the contents of regis-
ter A. We wi II see more examples of using addressing modes with various instruc-
tions in the next few chapters.

Indexed addressing mode and MOVX instruction


As we have stated earlier, the 8051 has 64K bytes of code space under the
direct control of the Program Counter register. We just showed how to use the
MOVC instruction to access a portion of this 64K-byte code space as data memo-
ry space. In many applications the size of program code does not leave any room
to share the 64K-byte code space with data. For this reason the 8051 has another
64K bytes of memory space set aside exclusively for data storage. This data mem-
ory space is referred to as external memory and it is accessed only by the MOVX
instruction. In other words, the 8051 has a total of l28K bytes of memory space
since 64K bytes of code added to 64K bytes of data space gives us 128K bytes.
One major difference between the code space and data space is that, unlike code
space, the data space cannot be shared between code and data. This is such an
important topic that we have dedicated an entire chapter to it: Chapter 14.

Accessing RAM Locations 30 . 7FH as scratch pad


As we have seen so far, in accessing registers RO - R7 of various banks, it
is much easier to refer to them by their RO - R7 names than by their RAM loca-
tions. The only problem is that we have only 4 banks and very often the task of.
bank switching and keeping track of register bank usage is tedious and prone to
errors. For this reason in many applications we use RAM locations 30 - 7FH as
scratch pad and leave addresses 8 - IFH for stack usage. That means that we. use
RO - R7 of bank 0, and if we need more registers we simply use RAM locations
30 - 7FH. Look at Example 5- IO.

Example 5-10
Write a program to toggle PI a total of 200 times. Use RAM location 32H to hold
your counter value instead of registers RO - R7.

Solution:
MOV PI,#55H ;PI=55H
MOV 32H,#200 ,.load counter value into RAM loc 32h
LOPI:CPL PI ;toggle PI
ACALL .DELAY
DJNZ 32H,LOPI ;repeat 200 times

121
CHAPTER 5: 8051 ADDRESSING MODES
Review Questions
I. The instruction "MOV A, 4 OR" uses addressing mode. Why?
2. What address is assigned to register R2 of bank 0'1
3. What address is assigned to register R2 of bank 2'1
4. What address is assigned to register A? . de if
5. Which registers are allowed to be used for register indirect addressing mo e I
the data is in on-chip RAM?

SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM

Many microprocessors such as the 386 or Pentium allow programs to


access registers and I/O ports in byte size only. In other words, if you need to
check a single bit of an I/O port, you must read the entire byte first and then manip-
ulate the whole byte with some logic instructions to get hold of the desired single
bit. This is not the case with the 8051. Indeed, one of the most important features
of the 8051 is the ability to access the registers, RAM, and I/O ports in bits instead
of bytes. This is a very unique and powerful feature for a microprocessor made in
the early 1 980s. In this section we show address assignment of bits of I/O, regis-
ter, and memory, in addition to ways of programming them.

Bit-addressable RAM
Of the I28-byte internal RAM of the 8051, only 16 bytes arc bit-address-
able. The rest must be accessed in byte format, The bit-addressable RAM loca-
tions arc 20H to 2FH. These 16 bytes provide 128 bits of RAM bit-addressabili-
ty since 16 x 8 = 128. They arc addressed as 0 to 127 (in decimal) or 00 to 7FH.
Therefore, the bicaddres~ to 7 are for the firs\):>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 byte-
addressable 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)
(b) CLR 67H ; clear bit 67 SETB 28R ;set
(e) CLR bit 28H to 1
(c) CLR OFH ; clear bi t OFH (t) SETB1205;clear bit 12 (decimal)

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
ln order to avoi d
confusion regarding th e Byte
addresses 00 - 7FH, the fo 1- address
[owing two points must b e
7F
noted.
General-
r. The [28 bytes of RAM purpose
have the byte addresse S
of 00 - 7FH and can be
accessed in byte siz e
~'1je
(30
1>., RAM

2F 7F 7E 7D 7C 7B 7A 79 78
using various address - I
2E 77 7~ 75 74 7< 77 71 70
ing modes such a S 2D 6F 6E 6D 6C 6B 6A 69 68
direct and register-indi - I ?r Ih7 ~h ~" ~A h< h7 ~1 ~n

rect, as we have seen in "'c ?B I SF sE "D 5C SB SA Sg SR


.2
this chapter and previ - 57 56 55 54 53 52 51 50
ous chapters. These '"
o
.2
2A
/ 2Q 14F 4E 4n 4r 4B 4A 4q 4R
128 bytes are accessed "
~-,I 28 47 46 45 44 43 42 41 40
using byte-type instruc-
""'"' - '\ 27 3F 3E 3D 3C 3B 3A 39 38
tions.
"
."
-o
~ \ 26 37 36 35 34 33 32 31 30
" / 25 2F 2E 2D 2C 2B 2A 29 28
2. The 16 bytes of RAM ,~
I 24 27 2~ as 24 21 22 ?1 ?n
locations 20 - 2FH also
co
23 1F 1E 1D 1C 1B lA 19 18
have bit addresses of 00 ?? 117 '1-,:;...,.-.;---j-" 13 17 11 10
- 7FH since 16 x 8 = \ 71
I n"---n,, nn' rir np rvtv rv o nQ
128 (00 - 7FH). In order L-'-20 -0'7-0605 04 03 02 01 00
to access these 128 bits 'IF Bank 3
18
of RAM locations and 17 Bank 2
other bit-addressable 10
OF Bank I
space of 8051 individu- 08
ally, we can usc only 07 Default register bank for RO - R 7
00
the single-bit instruc-
tions such as SETB. Figure 5-1. 16 Bytes oflnternal RAM.
Table 5-2 provides a list Note: They are both bit- and byte-accessible.
of single-bit instruc-
tions. 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 indi-
rect 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 if bit, then clear
JBC bit,tar et

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
Byte
earlier in this chapter, every
address Bit address
SFR register is assigned a
byte address and ports PO - FF
P3 are part of the SFR. For FO F7 F6 F5 F4 F3 F2 Fl FO B
example, PO is assigned
byte address 80H, and PI EO E7 E6 E5 E4 E3 E2 El EO Ace
has address of 90H as
DO D7 D6 D5 D4 D3 D2 Dl DO psw
shown in Figure 5-2. While
all of the SFR registers are B8 -- BC BB 8A B9 88 IP
byte-addressable some of
them are also bit-address- BO B7 B6 85 B4 B3 82 Bl BO
P3
able. The PO - P3 are among
this category of SFR regis- AS AF AC AB AA A9 A8 IE
ters. From Figure 5-2 we
AD A7 A6 AS A4 A3 A2 Al
see that the bit addresses for AO P2
PO are 80H to 87H, and for
P I arc 90H to 97H, and so 99
not bit-addressable SBUF
on. 98 9F 9E 9D ge 9B 9A
99 98 seaN
Notice that when
code such as "SETB 90 97 96 95 94 93
92 91 90 PI
Pl.0" is assembled, it
becomes "SETB 90H" 8D
not bit-addressable T HI
since P 1.0 has the RAM 8e
not bit·addressable T HO
address of 90H. Also notice 88
not bit-addressable T Ll
from Figures 5-1 and 5-2 8A
not bit-addressable T LO
that bit addresses 00 - 7FH 89
not bit-addressable T MOD
belong to RAM byte 88 8F 8E 8D
8e 8B 8A 89 88 T eON
addresses 20 - 2FH, and bit 87
addresses 80 - F7H belong not bit-addressable P eON
[a SFR of PO, TCON, PI
83
SCON, P2, etc. The bi; not bit-addressable D PH
82
addresses for PO - P3 arc not bit-addressable D PL
81
shown in Table 5-3 , an d not bit-addressable sP
.
d iscusscd next. 80 87 86 85 84
83 82 81 80
Pa
Special Function Registers

Figure 5-2. SFR RA


M Address (Byte and Bit)

124
=
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


Addr PI Addr P2 Addr P3 Addr Port's Bit
PO
80 PI.O 90 P2.0 AO P3.0 BO DO
PO.O
81 P 1.1 91 P2.1 Al P3.1 Bl DI
PO.l
PI.2 92 P2.2 A2 P3.2 B2 D2
PO.2 82
P1.3 93 P2.3 A3 P3,3 B3 D3
POJ 83
PIA 94 <1'2.4 A4)-- P3.4 B4 D4
PO.4 84 e
P2.5 /\5 P3.5 B5 D5
PO.5 85 P1.5 95
96 P2.6 A6 P3.6 B6 D6
PO.6 86 Pl.6
P2.7 A7 P3.7 B7 D7
PO.7 87 P 1.7 97

Example 5-12
Use Table
For each of the following instructions, state to which port the bit belongs.
5-3. (d) SETB OA7H
(b)CLR 87H (c) SETB 92H
(a) SETB 86H

Solution:

(a) SETB 86H is for SETB PO. 6.


(b) CLR 87H is for CLR PO. 7.
(c) SETB 92H is for SETB Pl. 2.
(d) SETB OA7H is for SETB P2. 7.

125
CHAPTER 5: 8051 ADDRESSING MODES
Registers bit-addressability
While all VO ports arc bit-addressable, that is not the case with registers,
as seen from Figure 5-1. Only registers A, B, PSW, IP, IE, ACC, SCaN, and
TCON are bit-addressable. Of the bit-addressable registers, we will concentrate
on the familiar registers A, B, and PSw. The rest will be discussed in future chap-
ters.
Now let's see how we can use bit-addressabiJity of registers such as A and
PSw. As we discussed in Chapter 2, in the PSW register two bits are set aside for
the selection of the register banks. See Figure 5-3. Upon RESET, bank 0 is select-
ed. We can select any other banks using the bit-addressability of the PSW as was
shown in Chapter 2. The bit addressability of PSW also eliminates the need for
instructions such as JOV (Jump if Ov> I). Sec Example 5-14.
Examine the next few examples ofbit-addressabilty to gain a better under-
standing of this important feature of the 8051 .

I
RSI
Cy

RSO
AC FO RSl

Register Bank
RSO ov P

Address
0 0 0 OOH - 07H
0 I I 08H - OFH
J 0 2 lOB - 17H
I I 3 18H - IFH
Figure 5-3. Bits of the PSW Register
Example 5-13

Write a program to save the Accumulator in R7 of bank 2.

Solution:
CLR PSW.3
SETB PSW.4
MOV R7,A

Example 5-14

While there are instructions sueh as INC and JC to che .


are no such instructions for the overflow fl bi (a eek the carry flag bit (CY), there
check OV? ag Jl V). How would you write eode to

Solution:

The av flag is PSW.2 of the PSW re istcr P . .


we ean use the following instruction ~o h' ~~ IS a bit-addressable register; therefore
e ee t e av flag. '
JB PSW. 2 ,TARGET ; jump if OV;l
Example 5-15

Write a program to see if the RAM location 37H contains an even value. If so, send it
to P2. If not, make it even and then send it to P2.

Solution:
MOV A,37H ;load RAM location 37H into accumulator
JNB ACC. 0, YES ;is DO of reg A O? if so jump,
INC A ;it is odd, make it even
YES: MOV P2,A ;send it to P2

Example 5-16
Assume that bit P2.3 is an input and represents the condition of a door. If it goes high,
it means that the door is open. Monitor the bit continuously. Whenever it goes high,
send a low-to-high pulse to port P 1.5 to tum on a buzzer.

Solution:

HERE:JNB P2.3,HERE ;keep monitoring for high


CLR P1.5 ;Clear bit (P1.5 = 0)
ACALL DELAY
SETB PI. 5 ;PI. 5=1 (low-to-high pulse)
ACALL DELAY
SJMP HERE
vee
Switch
-f
J 8051

.....
---1P2.3
Buzzer
4.7k
P1.51---1

74LS04

Example 5-17
The status of bits P 1.2 and P 1.3 of I/O port P I must be saved before they are cha~ged.
. th tatus of PI 2 in bit location 06 and the status of P 1.3 In bit
Wnte a program to save e s .
location 07.

Solution:
;clear bit address 06
CLR 06
;clear bit address 07
CLR 07
.check bit P1.2,if 0 then jump
JNB P1.2,OVER
:if P1.2=1,set bit location 06 to 1
SETB 06
:check bit P1.3, if 0 then jump
OVER:JNB P1.3,NEXT
:if
, P1.3=1, set bit location 07 to 1
SETB 07
NEXT: ...
127
CHAPTER 5: 8051 ADDRESSING MODES
Example 5-18
Write a program to save the status 0f bit1 PI .7 on RAM address bit 05.

Solution:

MOV C,P1.7 ;get bit from port


MOV 05,C ;save bit

Example 5-19
Write a program to get the status of bit pin PI.7 and send it to pin P2.0.

Solution:

HERE: MOV C,Pl.7 ;get bit from port


MOV P2.0,C ;send bit to port
SJMP HERE ;repeat forever

Using BIT directive

The BIT directive is a widely used directive to assign the bit-addressable


I/O and RAM locations. The BIT directive allows a program to assign the 110 or
RAM bit at the beginning of the program, making it easier to modify them.
Examine the next few examples to see how we usc the BIT directive.

Example 5-20

Assume that bit P2J is an input and represents the condition of an oven. If it goes high,
it means that the oven is hot. Monitor the bit continuously. Whenever it goes high, send
a low-to-high pulse to port PI .5 to tum on a buzzer.
\
Solution:

OVEN HOT BIT P2.3


BUZZER BIT Pl.5

HERE:JNB OVEN_HOT,HERE
ACALL DELAY ;keep monitoring for HOT
CPL BUZZER
ACALL DELAY
;sound the buzzer
SJMP HERE

~~~~ s~~;:~~ ~xample 5-16, except the use of BIT directive allows us to assign the
gram f;r them. UZZER bit to any port. This way you do not have to search the pro-

128

.~",: -
" ".

- .
Example 5-21
An LED is connected to pin Pl.? Write a program to toggle the LED forever.

Solution:

LED BIT P.7 ;using BIT directive


HERE: CPL LED ;toggle LED
LCALL DELAY ;delay
SJMP HERE ;repeat forever

Example 5-22
A switch is connected to pin Pl.? and an LED to pin P2.0. Write a program to get the
status of the switch and send it to the LED.

Solution:

SW BIT Pl. 7 ;assign bit


LED BIT P2.0 ;assign bit
HERE: MOV C,SW ;get the bit from the port
MOV LED,C ;send the bit to the port
SJMP HERE ;repeat .forever

Example 5-23
Assume that RAM bit location 12H holds the status of whether there has been a phone
call or not. If it is high, it means there has been a new call since it was checked the last
time. Write a program to display "New Messages" on an LCD ifbit RAM 12H is high.
If it is low, the LCD should say "No New Messages".

Solution:

PHONBIT BIT 12H


;copy bit location 12H to carry
MOV C,PHONBIT
;check to see if is high
JNC NO
;yes, load address of message
MOV DPTR, #40 OH
;display message (see Chap. 12)
LCALL DISPLAY
SJMP EXIT ;get out
;load the address of No message
NO: MOV DPTR,#420H
LCALL DISPLAY ;display it
;exit
EXIT:
______________ data to be displayed on LCD
ORG 400H
DB "New MeSsages", 0
YES MG:
ORG 420H
DB "No New Messages", 0
NO MG:

129
CHAPTER 5: 8051 ADDRESSING MODES
Using EQU directive
Wc can also use the EQU directive to assign addresses, as shown in the
ncxt few examples, Notice that in Example 5-24 the ports arc defined by their
names, while in Example 5-25, they are defined by their addresses.

Example 5-24
A switch is connected to pin PI.? Write a program to check the status of the switch and
make the following decision.
(a) If SW = 0, send "NO" to P2.
(b) If SW = I, send "YES" to P2.

Solution:

SW EQU Pl. 7
MYDATA EQU P2

HERE: MOV C,SW


JC OVER
MOV MYDATA, #'N' ·;SW=O, send tlNOIl
MOV MYDATA,#'O'
SJMP HERE
OVER: MOV MYDATA,#'Y' r ;SW=l, send "YES"
MOV MYDATA,#'E'
MOV MYDl'iTA,#'S'
SJMP HERE
END

Example 5-25
A switch is connected to pin PI.? Write a r
makc the following decision. p ogram to check the status of the switch and
(a) If SW = 0, send '0' to P2.
(b)/fSW= I,send ']'toP2.
USC EQU to designate the I/O ports.

Solution:
SW EQU 97H
MYDATA ;P1.7 bit address
EQU OAOH
HERE: ;P2 address
MOV C,SW
JC OVER
MOV MYDATA,#'O'
SJMP HERE ; 00110000 to P2
OVER:
MOV MYDATA,#'l'
SJMP HERE ; 00110001 to P2
END

130
=
Review Questions
I. True or false. All I/O ports of the 805[ are bit-addressable.
2. True or false. All registers of the 8051 are bit-addressable.
3. True or false. All RAM locations of the 8051 are bit-addressable.
4. Indicate which of the following registers are bit-addressable.
(a) A (b) B (c) R4 (d) PSW (e) R7
5. Of the 128 bytes of RAM in the 8051, how many bytes are bit-addressable?
LIst them.
6. How would you check to see whether bit DO ofR3 is high or low?
7. Fmd out to which byte each of the following bits belongs. Give the address of
the RAM byte in hex.
(a) SETB 20 (b) CLR 32 (c) SETB I2H
(d) SETB 95H (e) SETB OE6H
8. While bit addresses 00 - 7FH belong to , bit addresses 80 - F7H
belong to .
9. True or false. PO, PI, P2, and P3 are part of SFR.
10. True or false. Register ACC is bit-addressable.

SECTION 5.4: EXTRA 128-BYTE ON-CHIP RAM IN 8052

The 8052 rnicrocontroller is an enhanced version of the 8051. In recent


years the 8052 has replaced the 8051 due to many of its new features.
OS89C420/30 is an example of 8052 architecture. One of the new features of the
8052 is an extra 128 bytes of on-chip RAM space. In other words, the 8051 has
only 128 bytes of on-chip RAM, while the 8052 has 256 bytes of it. To understand
it, first let's recall the following two facts from earlier discussion in this chapter
and Chapter 2.
1. The 805 \ has 128 bytes of on-chip RAM with addresses 00 - 7FH. They are
used for (a) register banks (addresses 00 - IFH), (b) bit-addressable RAM
space (addresses 20 - 2FH), and (c) the scratch pad (addresses 30 - 7FH).
2. Another 128 bytes of on-chip RAM with addresses 80 - FFH are designated as
Special Function Registers (SFRs). Again, the SFRs are accessed by direct
addressing mode as we saw earlier in tbis chapter.
In addition to the above two features, the 8052 has another 128 bytes of on-
chip RAM with addresses 80 - FFH. This extra 128 bytes of on-chip RAM is often
called upper memory to distinguish it from the lower 128 bytes of 00 - 7FH. The
only problem is, the address space 80 - FFH is the same address space assigned to
the SFRs. In other words, they are physically two separate memories, but they
have the same addresses. This parallel address space in the 8052 forces us to use
two different addressing modes to access them as described next.
I. To access the SFRs, we use direct addressing mode. The instruction "MOV
90H, #55H" is an example of accessing the SFR with direct addressing
mode. Since 90H is the address ofPl, this is same as "MOV PI, #55H".
2. To access the upper 128 bytes, we use the indirect addressing mode, which
uses RO and R I registers as pointers. Therefore, instructions "MOV @RO, A"
and "MOV @RI, A" are employed to access the upper memory as long as reg-
isters RO and R I have values of 80H or higher. For example, the following
131
CHAPTER 5: 8051 ADDRESSING MODES
codes will put 55H into address 90H ofthc upper 128 bytes of RAM,

MOV RO,#90H ;load the upper memory address


MOV @RO, #55H ;put 55H into an address pointed to
;by RO reg,

Figure 5-4 shows the parallel space shared between the SFR and the upper
128 bytes of RAM in the 8052, Example 5-26 shows how to access the upper 128
bytes of on-chip RAM in the 8052 microcontrollcr.

FF FF
Direct Access Indirect Access
(MOV 90H,#55H) (MOV@RO,A)

Special Function Upper RAM


Register Only
80 80
7F

20
1F
Accumulator,
Registers,
18 Program Status Word
Bank 3
17 Stack Pointer , '
Status and Control Bits
Ports, '
10 Bank 2 Timers,
OF Serial Control ,
Power Control, and
others
08 Bank 1
07

00 Bank 0

Figure 5-4, 8052 On-Chip RAM Add


ress Space
Example 5-26

Write a program for the 8052 to put 55H into the upper RAM locations of 90 - 99H.

Solution:

ORG o
MOV A,#55H
MOV R2,#10
MOV RO,#90H ;access the upper 128 bytes of on-chip 'RAM
BACK:MOV @RO,A ;use indirect addressing mode
INC RO
DJNZ R2,BACK ;repeat for all locations
SJMP $ ;stay here
END

Run the above program on your simulator and examine the upper memory to see the
result. (See Figures 5-5 and 5-6 for screen shots.)

Example 5-27
Assume that the on-chip ROM has a message. Write a program to copy it from code
space into the upper memory space starting at address 80H. Also, as you place a byte
in upper RAM, give a copy to PO.

Solution:

ORG 0
MOV DPTR, #MYDATA
MOV R1,#80H iaccess the upper 128 bytes of on-chip RAM
B1: CLR A
MOVC A,@A+DPTR ;copy from code ROM space
MOV @R1,A ;store in upper RAM space
MOV PO,A ;give a copy to PO
JZ EXIT ;exit if last byte
INC DPTR ;increment DPTR
INC R1 ;increment R1
SJMP B1 ;repeat until the last byte
EXIT: SJMP $ ;stay here when finished
i -----------
ORG 300H
MYDATA: DB "The Promise of World Peace", 0
END

R un teah bove program 0n your simulator and examine the upper memory to see the
result.

133
CHAPTER 5: 8051 ADDRESSING MODES
Simulators and Data RAM space
All the major 8051/52 simulators have ways of showing the data RAM
contents. Figures 5-5 and 5-6 show some of them.

Uala [upperspece] l1li


80: 00 00 00 00 00 00 00 00 · ....... &

88: 00 00 00 00 00 00 00 00 ·.......
90: 55 55 55 55 55 55 55 55 UUUUUUUU
98: 55 55 00 00 00 00 00 00 UU......
0: 00 00 00 00 00 00 00 00 · .......
8: 00 00 00 00 00 00 00 00 ·.... ...
BO: 00 00 00 00 00 00 00 00 · . . .....
B8: 00 00 00 00 00 00 00 00 · .......
CO: 00 00 00 00 00 00 00 00 · .......
C8: 00 00 00 00 00 00 00 00 · .......
DO: 00 00 00 00 00 00 00 00 · .......
08: 00 00 00 00 00 00 00 00 ·..... ..
EO: 00 00 00 00 00 00 00 00 · .......
EO: 00 00 00 00 00 00 00 00 · .......
FO: 00 00 00 00 00 00 00 00 · .......
F8: 00 00 00 00 00 00 00 00 · .......
rOO
,;J

Figure 5-5. Franklin Software's Pro View Upper Memory for the 8052

I:Ox80 00 00 00 00 00 00 00 00
I:Ox88 00 00 00 00 00 00 00 00 · .
I:Ox90 55 55 55 55 55 55 55 55 · .
I:Ox98 55 55 00 00 00 00 00 00 UUUUUUUu
I:OxAO 00 00 00 00 00 00 00 00 UU ......
I:OxA8 00 00 00 00 00 00 00 00 · .
I :OxBO 00 00 00 00 00 00 00 00 · .
I:OxB8 00 00 00 00 00 00 00 00 · .
I:OxCO 00 00 00 00 00 00 00 00 · .
I:OxC8 00 00 00 00 00 00 00 00 · .
I:OxDO 00 00 00 00 00 00 00 00 · .
I:OxD8 00 00 00 00 00 00 · .
I:OxEO 00 00 00 00 00 00
00 00 · .
I:OxE8 00 00 00 00 00 00
00 00 · .
I:OxFO 00 00 00 00 00 00
00 00 · .
I:OxF8 00 00 00 00 00 00
00 00 · .
> I:Ox80, OxFF
00 00 · .

<start address> , <end address> <cr>. ~•


I~
~•• 8IJiId c.mm'.d_~---'--f
Figure 5-6. Keil's "Vision Upper Memory for the 8052

134
Review Questions
I. True or false. The 8052 is an upgraded version of ;he 8051.
2. True or false. The 8052 has a total of256 bytes of on-chip RAM in addition to
the SFRs.
3. True or false. The extra 128 bytes of RAM in the 8052 is physically the same
RAM as the SFR.
4. Give the address for the upper RAM of the 8052.
5. Show how to put value 99H into RAM location F6H of upper RAM in the
8052.

SUMMARY

This chapter described the five addressing modes of the 8051. Immediate
addressing mode uses a constant for the source operand. Register addressing
mode involves the use of registers to hold data to be manipulated. Direct or reg-
ister indirect addressing modes can be used to access data stored in either RAM or
registers of the 8051. Direct addressing mode is also used to manipulate the stack.
Register indirect addressing mode uses a register as a pointer to the data. The
advantage of this is that it makes addressing dynamic rather than static. Indexed
addressing mode is widely used in accessing data elements ofJook-up table entries
located in the program ROM space of the 8051.
A group of registers called the SFR (special function registers) can be
accessed by their names or their addresses. We also discussed the bit-addressable
ports, registers, and RAM locations and showed how to use single-bit instructions
to access them directly.

PROBLEMS
SECTIONS 5.1 AND 5.2 IMMEDIATEAND REGISTERADDRESSING MODES I
ACCESSING MEMORY USING YARIOUS ADDRESSING MODES

I. Which of the following are invalid uses of immediate addressing mode?


(a) MOY A,#24H (b) MOY RI,30H (c) MOY R4,#60H
2. Identify the addressing mode for each of the following. T
(a) MOY B,#34H (b) MOY A,50lb (c) MOY R2,07,-
(d) MOY R3,#0 (e) MOY R7,0 (I) MOY R6,#7FH
(g) MOV'RO,A (h) MOY ~,A (i) MOY A,@RO
(j) MOY R7,A (k) MOY A,@RI .
3. Indicate the address assigned to each of the followmg.
(a) RO of bank 0 (b) ACC (c) R7 of bank 0
(d) R3 of bank 2 (e) B (f) R7 of bank 3
(g) R4 of bank I (h) DPL (i) R6 of bank 1
(j) RO of bank 3 (k) DPH (I) PO
4. Which register bank shares space with the stack? .
5. In accessing the stack, we must use addressmg mode.
135
CHAPTER 5: 8051 ADDRESSING MODES
6. What docs the following instruction do? "MOV A,OFOH"
7. What docs the following instruction do? "MOV A, I FH"
8. Write code to push RO,R I, and R3 of bank 0 onto thc stack and pop them back
into R5, R6, and R7 of bank 3.
9. Which registers are allowed to be used for register indirect addressing mode
when accessing data in RAM?
10. Write a program to copy FFH into RAM locations SOH to 6FH.
II. Write a program to copy 10 bytes of data starting at ROM address 400H to
RAM locations starting at 30H.
12. Write a program ttl find y where y = x2 + 2x + 5, and x is between 0 and 9.
13. Write a program to add the following data and store the result in RAM loca-
tion 30H.
ORG 200H
MYDATA: DB 06,09,02,05,07 ,
/
SECTION 5.3: BIT ADDRESSES FOR I/O AND RAM

14. "SETB A" is a(n) (valid, invalid) instruction.


IS. "CLR A" is a(n) (valid, invalid) instruction.
16. "CPL A" is a(n) (valid, invalid) instruction.
17. Which I/O ports of PO, PI, P2, and P3 arc bit-addressable?
18. Which register§. of the 8051 are j2it-addrcssablc?
19. Which of the following instructions arc valid? If valid, indicate which bit is
altered.
(a) SETB PI (b) SETB P2. 3 (e) CLR ACC. 5
(d) CLR 90H (e) SETB B. 4 (f) CLR 80H
(g) CLR PSW. 3 (h) CLR 87H
20. Write a program to generate a square wave with 75% duty eyele on bit P 1.5.
21. Write a program to generate a square wave with 80% duty eycle on bit P2.7.
22. Write a program to monitor PIA. When it goes high, the program will gener-
ate a sound (square wave of 50% duty cycle) on pin P2.7.
23. Write a program to monitor P2.1. When it goes low, the program will send the
value 55H to PO.
24. What bit addresses arc assigned to PO?
25. What bit addresses arc assigned to PI?
26. What bit addresses are assigned to P2?
27. What bit addresses are assigned to P3?
28. What bit addresses are assigned to the PCON register'?
29. What bit addresses arc assigned to the TCON register')
30. What bit addresses arc assigned to register A?
31 . What bit addresses arc assigned to register B?
32. What bit addresses are assigned to register PSW,?
I 33. The followmg arc bit addresses. Indieate where each one belongs
(a) 85H (b) 87H (e) 88H (d) 8DH (e) 93H (f) ASH .
(g)A 7H (h) B3H (i) D4H (j) D7H (k) F3H
34. Write a program to save registers A and B on R3 and R5 of ba k 2
lively. n , respee-

136

CHAP
35. Give another instruction for "CLR C".
36. In Problem 19, assemble each instruction and state if there is any difference
between them,
37. Show how you would check whether the OV flag is low.
38 Show how yO!! wo!!ld check whether the CY flag is high.
39. Show how you would check whether the P flag is high.
40. Show how you would check whether the AC flag is high.
41. Give the bit addresses assigned to the flag bit of CY, P, AC, and O'V,
42. Of the 128 bytes of RAM locations in the 8051, how many of them are also
assigned a bit address as well? Indicate which bytes those are.
43. Indicate the bit addresses assigned to RAM locations 20H to 2FH.
44. The byte addresses assigned to the 128 bytes of RAM are to .
45. The byte addresses assigned to the SFR are to -,-- ---
46. Indicate the bit addresses assigned to both of the following. Is there a gap
between them?
(a) RAM locations 20H to 2FH (b') SFR
47. The following are bit addresses. Indicate where each one belongs.
(a) 05H (b) 47H (c) 18H (d) 20H (e) 53H (0 ISH
(g) 67H (h) 55H (i) 14H (j) 37H (k) 7FH
48. True or false. The bit addresses of less than 80H are assigned to RAM loca-
tions 20 - 2FH.
49. True or false. The bit addresses of 80H and beyond are assigned to SFR (spe-
cial function registers).
50. Write instructions to save the CY flag bit in bit location 4.
51. Write instructions to save the AC flag bit in bit location 16H.
52 Write inill:uctiousJo save the P flag bit in bit location 12H.
53. Write instructions to sec whether the DO and 01 bits of register A are high. If
0, divide register A by 4.
54. Write a program to see whether the D7 bit of register A is high. If so, send a
me sage to the LCD stating that ACC has a negative number.
55. Write a program to see whether the D7 bit of register B is low. If so, send a
mes age to the LCD stating that register B has a positive number.
~ Write a program to set high all the bits of RAM locations 20H to 2FH ..using
the following methods:
(a) byte addresses (b) bit addresses
57. Write a program to see whether the accumulator is divisible by 8.
58. Write a program to find the number of zeros in register R2.

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

59. What is the total number of bytes of RAM in the 8052 including the SFR reg-
isters? Contrast that with the 8051. '~"l-'l-f.t\.
60. What addressing mode is used to access the SFR? .
61. What addressing mode is used to access the upper 128 bytes of RAM In the
8052? f . h
62. Give the address range of the lower and the upper 128 bytes 0 RAM In t e
8052.0Y'lFt-t >:, ~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 upp-
per RAM locations DO- DFH.

ANSWERS TO REVIEW QUESTIONS

SECTION 5.1: IMMEDIATE AND REGISTER ADDRESSING MODES

I. No
2. MOV R3,#10000000B
3, Source and destination registers' sizes do not match.
4. True '
5. No

SECTION 5.2: ACCESSING MEMORY USING VARIOUS ADDRESSING MODES

I. Direct; because there is no "#" sign


2. 02
3. 12H
4. EOH
5. RO and RI

SECTION 5.3: BIT ADDRESSES FOR 1/0 AND RAM

I. Tmc
2. False
3. False
4. A, B, and PSW
5. \6 bytes are bit-addressable; they are from byte location 20H to 2FH
6. MOY A,R3 .
JNB ACC.O
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 5.4: EXTRA I28-BYTE ON-CHIP RAM IN 8052

I. Tme
2, True
3. False
4. 80 - FFH
5. 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, multiplica-
tion, 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 rep-
resent 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 A,#OF5H
;A=F5 hex
ADD A,#OBH
;A=F5+0B=00

Solution:

F5H 1111 0101


+ OBH + 0000 1011
100R
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:

MOV RO,#40H ;load pointer


MOV R2,#5 ;load counter
CLR A ;A=O
MOV R7,A ;clear R7
AGAIN: ADD A,@RO ;add the byte pointer to A by RO
JNC NEXT ;if Cy=o don't accumulate carry
INC R7 ;keep track of carries
NEXT: INC RO ;increment pointer
DJNZ R2 ,AGAIN ;repeat until R2 is zero

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
ADDC (add with . usc d on such occasions. For example, look at the addi-
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 propa-
gated 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 and 3B8DH.
Place the sum in R7 and R6; R6 should have the lower byte.

Solution:

CLR C ;make CY=O


MOV A,#OE7H ;load the low byte now A=E7H
ADD A,#8DH ;add the low byte now A=74H and CY=l
MOV R6,A ;save the low byte of the sum in R6
MOV A,#3CH ;load the high byte
ADDC A,#3BH ;add with the carry
;3B + 3C + 1 = 78(all in hex)
MOV R7,A ;save the high byte of the sum

BCD (binary coded decimal) number system Digit BCD


0 0000
BCD stands for binary coded decimal. BCD is needed 1 0001
because in everyday life we usc the digits a to 9 for numbers not 2 0010
binary or hex numbers. Binary representation of a to 9 is called 3 0011
BCD (see Figure 6-1). In computer literature one encounters 4 0100
two terms for BCD numbers, (I) unpacked BCD, and (2) packed 5
BCD. We describe each one next. 0101
6 0110
Unpacked BCD 7 0111
8 1000
. In unpacked BCD, the lower 4 bits of the number repre- 9 1001
sent the BCD number, and the rest of the bits arc a F
I "0000 a " . . or exam-
p e, . I a I and "0000 a I a I" arc unpacked BCD for 9 and Figure 6-1. BCD Code
p
5, res ee.lIvely. Unpacked BCD requires I byte of memory or an
8-blt register to contain it.

142
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 prob-
lem, 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 micro-
processors 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 I is dis-
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 mnemon-
ic "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.

;A~47H first BCD operand


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

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
72) . Th e IDS u i register
'ng mode the destination must bee in . .
A in
d a f any addressl
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
I th
greater t han 9 . n a er, wo . .
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.

Hex BCD
29 0010 1001
+ 18 + 0001 1000
41 0100 0001 ACd
+ ---..2. + 0110
47 0100 0111

Since AC = 1 after the addition, "DA A" will add 6 to the lower nibble.
The final result is in BCD format.

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 RO,#40H ;load pointer


MOV R2,#5 ;load counter
CLR A ;A~O
MOV R7,A ;clear R7
AGAIN: ADD A,@RO
DA
;add the byte pointer to A by RO
A
;adjust for BCD
JNC NEXT
INC R7 ;if CY~O don't accumulate carry
NEXT: ;keep track of carries
INC RO
;increment pointer
DJNZ R2 ,AGAIN
;repeat until R2 is zero
Subtraction of unsigned numbers
SUBBA, source ;A ; A - source - CY
In many microprocessors there are two different instructions for subtrac-
tion: 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 sub-
tracter circuitry, For this reason, the 8051 uses adder circuitry to perform the sub-
traction command, Assuming that the 8051 is executing a simple subtract instruc-
lion 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 inter-
nal 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,

CLR C ; make CY;O


(A ; 3FH)
MOV A,#3FH ;load 3FH into A
23H)
;load 23H into R3 (R3
;

MOV R3,#23H in A
; subtract A - R3, place result
SUBB A,R3

Solution:

0011 1111 0011 1111


A ; 3F + 11011101 (2's complement)
R3; 23 0010 0011
1 0001 1100
1C
o CF;O (step ,3)

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 com-
plement of the operand; then the operand is incremented (INC) to get the 2 's com-
plement. 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 steps for "SUBE A, #6EH":


4C 0100 1100 0100 1100
6E 0110 1110 2's comp
1001 0010
-22 0 1101 1110
CY = 1, the 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 C
;CY = 0
MOV A,#62H
;A = 62H
SUEB A,#96H
MOV ;62H - 96H = CCH with CY = 1
R7,A
MOV ;save the result
A,#27H
;A=27H
SUEB A,#12H
MOV R6,A ;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
and B IS required since the multiplication and division instructions work only with
these two registers. Wc first discuss multiplication.

Multiplication of unsigned numbers


The 8051 supports byte-by-byte multiplication only. The bytes are
assumed to bc unsigned data. The syntax is as follows:

MUL AB ;A x B, 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 fol-
lowing example multiplies 25H by 65H. The result is a 16-bit data that is held by
the A and B registers.

MOV A,#25H ;load 25H to reg. A


MOV B,#65H ;load 65H in reg. B
MUL AB ;25H * 65H ~ E99 where
;B ~ OEB and A ~ 99H

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


Multiplication Operand I Operand 2 Result
byte x byte A B 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 quo-
tient is in A and the remainder is in B. See the following example.

A,#95 ;load 95 into A


MOV
B,#10 ;load 10 into B
MOV
DIV AB ,.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 Quotient Remainder
byte I byte A B A B
(If B = 0, then OV - I indicating an error)

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 A,#OFFH
MOV Pl,A
;make PI an input port
MOV A,Pl ;read data from PI
MOV B,#10 ;B=OA hex (10 dec)
DIV AB ;divide by 10
MOV R7,B ;save lower digit
MOV B,#10
DIV AB
;divide by 10 once more
MOV R6,B
;save the next digit
MOV RS,A
;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 quo-
tient 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 Remainder
FD/OA= 19 3 (low digit)
19/0A= 2 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 regis-
teres) _
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 regis-
ter 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 numbers, meaning that the
entire 8-bit operand was used for the magnitude. Many applications require signed
data. In this section the concept of signed numbers is discussed along with relat-
ed instructions. J f your applications do not involve signed numbers, you can
bypass this section.

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 num-
bers. 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 1sign I magnitUde
: I, it is negative. r----t"----- _

Positive numbers Figure 6-2. 8-Bit Signed Operand

The range of positive numbers that' can


be represented by the format shown in Figure
a 0000 0000
6-2 IS 0 to + 127. J f a positive number is larger
+1 0000 0001
than + 127, a 16-bit size operand must be used.
Since the 805J does not support 16-bit data we
will not discuss it. ' +5 0000 0101

Negative numbers +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 stlllimpor-
wor s . 0 convert to nega tiive num b er rep-
resentation (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. 0000 0101 5 in 8-bit binary


2. 1111 1010 invert each bit
3. 1111 1011 add 1 (which becomes 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.

0011 0100 34H given in binary


1.
1100 1011 invert each bit
2.
add 1 (which is CC in hex)
3. 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.

128 in 8-bit binary


l. 1000 0000
invert each bit
2. 0111 1111 add 1 (which becomes 80 in hex)
3. 1000 0000

Therefore -128 = 80H, the signed 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 1000 0000 80
-127 1000 0001 81
-126 1000 0010 82
.........
-2 1111 1110 FE
-1 1111 1111 FF
a 0000 0000 00
+1 0000 0001 01
+2 0000 0010 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 A,#+96
MOV R1,#+70 ;A = 0110 0000 (A = 60H)
ADD A,R1 ;R1 = 0100 0110 (R1 = 46H)
;A = 1010 0110
Solution: ;A = A6H = -90 decimal, INVALID!

+96 0110 0000


+ ±lQ 0100 011Q
+ 166 1010 0110 and OV=l

According
cate to the CPU, the result is -90, which is wrong. The CPU sets OV
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 A,#-128 ;A = 1000 0000 (A = 80H)


MOV R4,#-2 ~R4 = 1111 1110(R4 = FEH)
ADD A,R4 ,'A = 0111 1110 (A=7EH=+126, invalid)

Solution:

-128 1000 0000


+ -2 1111 1110
-130 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.

;A=l1l1 1110· (A=FEH)


MOV A,#-2
'R1=1111 1011 (R1=FBH)
MOV Rl,#-5
:A=1111 1001 (A=F9H=-7,correct,OV=01
ADD A,R1 r

Solution:

-2 1111 1110
±-=2 1111 1011
-7 1111 1001 and OV = 0

' 7 which is correct (OV = 0).


According to the CPU, the resu It IS - ,

153
GIC INSTRUCTIONS, AND PROGRAMS
CHAPTER 6: ARITHM ETIC , LO
Example 6-16
Examine the following, noting the role of Ov.

MOV A, #+7 ;A;OOOO 0111 (A;07H)


MOV R1,#+lB r'R1;0001 0010(R1;12H)
ADD A,R1 ;A;OOOI 1001 (A;19H;+25, correct,OV;O)

Solution:

7 0000 0111
+ -lJl 0001 0010
25 0001 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 addi-
tion, 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 addi-
tion 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 dis-
cussed 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 A
1'8 complement (Invert)
ADD A,#l
add 1 to make 2'8 complement

Review Questions

I. In an 8-bit operand, bit _ is used for the sign bit.


2. Convert -16H to Its 2's complement representation.
3. The range of byte-sizcd signed operands IS _ to +
4. 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
ANL destination,source ;dest = dest AND 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 accumula-
tor. 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
Example 6-17.
X
Y.
=D- X AND Y

Example 6-17
Show the results of the following.

MOV A,#35H ;A = 35H


;A A AND OFH (now A 05)
ANL A, #OFH

Solution:

35H 0011 0101


OFH 0000 1111
35H AND OFH 05H
05H 0000 0101

OR
;dest = dest OR source
ORL destination,source
Logical OR Function
The destination and source operands are Inputs Output
ORed and the result is placed in the destination. The
ORL instruction can be used to set certain bits of an x Y XORY
operand to l , The destination is normally the accu-
mulator. The source operand can be a register, In °° ° I °
I
memory or immediate. See Appendix A for more on
the addressing modes supported by this instruction.
I
1
° I
I
I
The ORL instruction for byte-size operands has no
~=r>-XORY
effect on any of the flags. See Example 6-18.

155
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
Example 6-18
Show the results of the following.
MOV A,#04 ;A 04
ORL A, #30H ;A A OR 30H (now A ; 34H)

Solution:
04H 0000 0100
30H 0011 0000
34H 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
Appendix A.I for the addressing modes of this Inputs Output
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.
Then we can use the JZ instruction to make a dcci-
~=J[)- X XOR Y

sion based on the result. See Example 6-20.


Example 6-19

Show the results of the following.


MOV A,#54H
XRL A, #78H

Solution:
54H 0101 0100
zaa 0111 1000.
2CH 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 it with
, e ears A, assummg that A = 45H.
Solution:
45H 0100 0101
-Wi 0100 0101
00
0000 0000
XOR a nUmber with itself
156 0
Example 6-21,
Read and test PII to see whether it has the value 45H. If it does, send 99H to P2; other-
Wise, It stays c eared. .

Solution:

MOV P2,#00 ;clear P2


MOV PI, #OFFH ;make PI an input port
MOV R3,#45H ;R3;45H
MOV A,P1 ;read PI
XRL A,R3
JNZ EXIT ;jump if A has value.other than 0
MOV P2,#99H
EXIT: ...

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
CPL A .now A;AAH Input Output
(AAH)
;01010101 becomes, 10101010 X NOT X
To get the 2's complement, all we, have to ~O ~I __
do is to add I to the I's complement. See Example :,.1 --"-0--
6-22. In other words, there is no 2's complement x --J>o- NOT X
instruction in the 8051. Notice that in comple-

Example 6-22
Find the 2 's complement of the value 8SH.

Solution: 85H ; 1000 0101


MOV A,#85H 0111 1010
i 1/ S compo l'S ;

CPL A + 1
i 2 IS compo
ADD A, #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 follow-
ing syntax.

CJNE destination, source, relative address

In the 8051, the actions of comparing and jumping are combined into a sin-
gle instruction called CINE (compare and jump ifnot equal). The CJNE instruc-
tion 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 exam-
pic, 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?

MOV #55H
A,
CJNE A,#99H,NEXT

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 Table 6-3: Carry Flag Setting
be In the accumulator or in one of the Rn For CJNE Instruction
registers.
. .
The SOurceoperand can bC In . a
register, In mcmory, or immediatc S Compare
Carry Flag
A d' . ~ destination> Source CY 0
. ppen .IX A for the addrcssing modes ofth'
II1structlOn.This instruction affects thc ca~; destination < source CY-I
~_a3g only. CY ISchanged as shown in Table

158
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 ;clear Rl


CJNE A,#99H,NEXT ;if A not equal to 99, then jump
MOV RI,#OFFH ;they are equal, make Rl = FFH
NEXT: . ;not equal so RI = 0
OVER: .

The following shows how the comparison works for all possible condi-
tions.

CJNE R5,#80,NOT_EQUAL ;checK R5 for 80


;R5=80
NOT_EQUAL: JNC NEXT ;jump if R5>80
;R5<80
NEXT:
Notice in the CJNE instruction that any Rn register can be compared with
an immediate value. There is no need for register A to be involved. Also notice
that CY is always checked for cases of greater or less than, but only after it is deter-
mined that they are not equal. See Examples 6-25 through 6-27.

Example 6-25
Assume that PI is an input port connected to a temperature sensor. Write a program to
read the temperature and test it for the value 75. According to the test results, place the
temperature value into the registers indicated by the following.

1fT = 75 thenA=75
1fT < 75 then Rl = T
1fT> 75 then R2 =T

Solution:

PI,#OFFH ;make PI an input port


MOV
A,PI ;read PI port, 'temperature
MOV 75
A,#75,OVER ;jump if A not equal to
CJNE
EXIT ;A=75, exit
SJMP
NEXT ;if CY=O then A>75
JNC
OVER: ;CY=I, A<75, save in Rl
MOV RI,A
;and exit
SJMP EXIT
;A>75, save it in R2
NEXT: MOV R2,A
EXIT:

CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS 159


Example 6-26 It should stop monitor-
Write a program to monitor P I continuously for the value 63H.
ing only if PI = 63H.

Solution:

MOV PI,#OFFH ,'make PI an input port


HERE: MOV A,PI ;get PI
CJNE A,#63,HERE ;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:
MOV R4,#O ;R4=O
MOV RO,#40H ;load pointer
MOV R2,#05 ;load counter
MOV A,#65 ;A=65, value searched for
BACK: CJNE A,@RO,NEXT;compare RAM data with 65
MOV R4,RO ;if 65, save address
SJMP EXIT ;and exit
NEXT: INC RO ;otherwise increment pointer
DJNZ R2,BACK ;keep checking until count=O
EXIT ...

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 not to jump?
CJNE 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 accu-
mulator right or left. We explore the rotate instructions next since they are wide-
ly 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 A ;rotate right A

In rotate right, the 8 bits of the accu-


mulator 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.

A,#36H ;A=OOl1 0110


MOV
;A=OOOl 1011
RR A
;A=lOOO 1101
RR A
; A=1100 0110
RR A
; A=0110 0011
RR A

;rotate left A
RL A

In rotate left, the 8 bits of the


accumulator are rotated left one bit, and
bit 07 exits from the MSB (most signif-
icant bit) and enters into DO (least sig-
nificant bit). See the code and diagram.

MOV A,#72H ;A=0111 0010


'A=1110 0100
RL A '
'A=1100 1001
RLA'
. . h RR d RL instructions that no flags are a ffected
ecte .
Notice III t e an

161
. OGIC INSTRUCTIONS, AND PROGRAMS
CHAPTER 6: ARITHMETIC, L
Rotating through the carry . h 805 J They involve the carry
There are two more rotate instructions In t e .
flag. Each is shown next.

RRC A ;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
[, MSB -~~ LSB 1--. cv ]
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 ;make CY=O


MOV A, #26H ,'A=0010 OUO
RRC A ,'A=OOOl 0011 CY=O
RRC A ;A=OOOO 1001 CY=l
RRC A ,'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
and enter the carry flag, and the CY
L -J MSB ..... 0--- LSB
]I
carry flag enters the LSB. In other - I .
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 ;A=OOOl 0101
RLC A ;A=0010 1011 CY=O
RLC A
;A=0101 0110 CY=O
RLC A
;A=1010 1100 CY=O
RLC A
;A=0101 1000 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 seri-

1. 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 trans-
fer are discussed in Chapter 10.
2. The second method of serializing data is to transfer data one bit at a time and
162
control the sequence of data and spaces in between them. In many new gen-
erations of devices such as LCD, ADC, and ROM, the serial versions of these
devices are becoming popular since they take less space on a printed circuit
board. 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 ;move the bit to CY


MOV Pl. 3, C ;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 ;high
SETB P2.1 ;high
MOV RS, #8
HERE:RRC A
;send the carry bit to P2.1
MOV P2 .1,C
DJNZ RS, HERE
SETB P2.1 ;high
SETB P2.1 ;high

PIN

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

07

163
LOGIC INSTRUCTIONS, AND PROGRAMS
CHAPTER6:A RlTHMETIC '
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 bring in bit
RRC A
DJNZ R5, HERE
MOV R2,A ;save it

PIN

I p2.7I-~·~El--·~D
...__... 07
R_EG_A 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 ;save status of PI.2 on Cy
MOV C, Pl.3 ;save carry in RAM bit location 06
MOV 07,C ;save status of PI.3 on CY
;save carry in RAM bit location 07
164
s

Table 6-4: Carry Bit-Relat ed Instruchons


.
I nstruction Function
SETS C make CY = I
CLR C clear carry bit (CY = 0)
CPL C complement carry bit.
MOY
MOY bCb C coPY carry status to btt. location (CY = b)
, coPY bit location status to carry (b = CY)
INC target lump to target if CY = 0
JC target jump to target if CY = I
ANL C ,bit AND CY WIt . h biIt and save it on CY
ANL C ,fbit . AND CY WIt . h Inverted
. bit. and save it on CY

ORL Cfbit
, ORCY wit. h iInverted bit and save it on CY

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:

SETB C ;CY = 1
ORL C,P2.2 iCY = P2.2 ORed with CY
MOV P2.2,C ;turn it "on" if not alr-eady "on"
CLR C ;CY = o
ANL C,P2.5 iCY = P2 .5 ANDed wi th CY
MOV P2.5,C ;turn it off if not already off

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

Solution:
;Rl keeps the number of Is
MOV Rl,#O
;counter = 08 rotate 8 times
MOV R7,#8
;find the number of Is in 97H
MOV A, #97H
;rotate it through the CY once
AGAIN: RLC A
NEXT ;check for CY
JNC ;if CY=1 then add one to count
INC Rl
;go through this 8 times
NEXT: DJNZ R7,AGAIN

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 II 03 - 00 I Sa~~p I 03 - 00 II 07 - 04 I

before: I 0111
" 0010
after:
SWAP 0010 " 0111

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 = 27H

(b)
MOV A, #72H ;A=Olll 0010
RL A ;A=lllO 0100
RL A
;A=llOO 1001
RL A
;A=lOOl 0011
RL A ;A=OOlO 0111

Review Questions

I. What is the value of register A after each of the f II '. .


MOV A, #25H 0 owing instructions?
RR A
RR A
RR A
RR A

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


RL A
RL A
RL A
RL A

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

SETB C
RRC A
SETB C
RRC A

4. Why does
. . "RLC R I" give . an error in the 805 I?
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 arith-
metic 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 ASCII (hex) Binary BCD (unpacked)
0 30 011 0000 00000000
1 31 Oil 0001 00000001
2 32 0110010 00000010
3 33 01100lJ 0000001 J
4 34 011 0100 00000100
5 35 0110101 00000101
6 36 0110110 00000110
7 37 011 0111 00000111
8 38 Oil 1000 00001000
9 39 011 1001 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 pro-
vides the time of day (hour, minute, second) and the date (year, month, day) con-
tinuously, 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
Unpacked BCD
29H ASCII
02H & 09H
0010 1001 32H & 39H
0000 0010 &
0011 0010 &
0000 1001
0011 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 BCD Packed BCD
4 34 00000100
7 37 00000111 01000111 or 47H

MOV A, #'4' ;A=34H, hex for ASCII char 4


ANL A, #OFH ;mask upper nibble (A=04)
SWAP A ;A=40H
MOV B, A
MOV A, #'7' ;R1=37H, hex for ASCII char 7
ANL A, #OFH ;mask upper nibble (R1=07)
ORL A, B ;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 A,#29H ;A=29H, packed BCD


MOV R2,A ;keep a copy of BCD data in R2
ANL A,#OFH ;mask the upper nibble (A=09)
ORL A,#30H ;make it an ASCII, A=39H ('9')
MOV R6,A ;save it (R6=39H ASCII char)
MOV A,R2 ;A=29H, get the original data
ANL A,#OFOH ;mask the lower nibble (A=20)
RR A ;rotate right
RR A ;rotate right
RR A ;rotate right
RR A ;rotate right, (A=02)
ORL A,#30H ;A=32H, ASCII char '2'
MOV R2,A ;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
ASCII character we nee .d
to tbe microcontroller. This is shown in Example 6-35.

169
CHAPTER 6: ARITHMETIC, LOGJC INSTRUCTIONS, AND PROGRAMS
Example 6-35 .

000 '0'
001 'I'
010 '2'
011 '3' .
100 '4'
101 '5'
110 '6'
III '7'

Solution:

MOV DPTR,#MYTABLE
MOV 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
,"-------- -------------

ORG 400H
MYTABLE DB '0' 'I' '2' '3' t4
I , , 1
t
I '5' I '6' I '71

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 check-
sum 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
detects the error.
~\:~~~rm
y
the checksum operation to ensure data
has been changed to 22H, show how checksum

Solution:

(a) Find the checksum byte.


25H
+ 62H
+ 3FH
+ 52H
118H (Dropping the carry of I, we have 18H. Its 2's complement is E8H.
Therefore the checksum byte is E8H.)

(b) Perform the checksum operation to ensure data integrity.


I .
25H
+ 62H
+ 3FH
+ 52H
+ E8H
200H (Dropping the carries, we see 00, indicating data is not corrupted.)

(c) 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 EQU 400H


COUNT EQU 4
RAM ADDR 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 byte


CAL CHKSUM:
MOV Rl,#RAM ADDR ;load data address
MOV R2,#COuNT ;load count
CLR A ;clear accumulator
H2: ADD A,@Rl ;add bytes and ignore carries
INC Rl i increment Rl
DJNZ R2,H2 ;repeat for all
CPL A ;1's complement
INC A ;2's complement(checksum byte)
MOV @Rl,A ;save it in data RAM
RET

;----------testing checksum byte


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

;----------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 bina-
ry (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 con-
verts 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 high-
location. 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
MOV@RO,A ,.save the last digit
RET
. Converting DEC digits to displayable ASCII digits
,
DEC ASCI CONVRT:
- MOV RO,#RAM_ADDR ;addr of DEC data
MOVR1,#ASCI_RSULT ;addr of ASCII data
MOVR2,#3 ; count
BACK: MOVA,@RO ;get DEC digit
t an ASCII digit
ORL A,#30H ;mak e 1
MOV@R1,A ;save lt .
INC RO ;next dlglt
INC R1 ; next .
DJNZ R2,BACK ;repeat untll the last one
RET ------- ------- ----------
j-----

END

173
OGIC INSTRUCTIONS, AND PROGRAMS
:HAPTER 6: ARITHME TIC , L
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, H ,
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.

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, mak-
ing 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 com-
plement. 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 (b) MOV A #99H
ADD A, #45H ADD A: #58H

174
--------

(c) MOV A,#OFFH (d) MOV A, #OFFH


SETB C ADD A,#l
ADDC A, #00
(e) MOV A,#OFEH (I) CLR C
SETB C MOV A, #OFFH
ADDC A, #01 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 250H
MYDATA: 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 250H
MYDATA: 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 (b) ORL A, B
(c) XRL A, #76H (d) ANL A, Rl
(e) XRL A,Rl (I) ORL A,Rl
(g) ANL A, #OFFH (h) ORL A, #99H
(i) XRL A, #OEEH 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 ORL A,#6BH
(c) MOV A, #9SH (d) MOV A, #SDH
XRL A,#OAAH MOV R3,#78H
ANL A,R3
(e) MOV A, #OCSH (I) MOV A, #6AH
MOV R6,#12H MOV R4,#6EH
ORL A,R6 XRL A,R4
(g) MOV A,#37H
ORL A,#26H
25. True or false. In using the ClNE . .
'.
t he destination IIlstructlon ' we must use tIic accumulator as
26. Is the following a valid instruction? "CJNE R
27. Does the 8051 have a "ClE" (' . 4, #67, HERE"
28 [ 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 cases
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 RS,#OFFH,NEXT (I) Mav A,#OAAH
A.."JL A, #55H
29. In Problem 28, indicate Whether 0 h CJNE
r not t e jurn h
°
A, # 0, NEXT
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 C (d) 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 (2)
;point (3)
NEXT:
177
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
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 '0'
0001 'I'
0010 '2'
0011 '3'
0100 '4'
0101 '5'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
1010 'A'
1011 'B'
1100 'C'
1101 '0'
1110 'E'
Ij II '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 '0'
0001 'I'
0010 '2'
0011 '3 '
0100 '4'
0101 '5'
0110 '6'
0111 '7'
1000 '8'
1001 '9'
ANSWERS TO REVIEW QUESTIONS

SECTION 6.1: ARITHMETIC iNSTRUCTIONS

I. A, B
2. A, B
3. No. We must use registers A and B for this operation.
4. A, B
5. A, B
6. No. We must use registers A and B for this operation.
7. A, the accumulator
8. No. We must usc registers A and B for this operation.
9. MOV A, R1
ADD A,R2
10. A, the accumulator
II. (a) A = 00 and CY = I (b) A = FF and CY ~ 0
12.
43H 0100 0011 0100 0'011
.:..Q.5.!:! 0000 0101 2' s complement + 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
-16H = EA in hex.
3. -128 to +127
4. +9 = 00001001 and -9 = 11110111 or F7 in hex.
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. (a) 02 (b) FFH (c) FDH


2. Zeros
3. One
4. All zeros
5. False
6. #53
7. 66H

SECTION 6.4: ROTATE iNSTRUCTION AND DATA SERIALIZATION

I. 52H
2. 2AH
3. COH
4. Because all the rotate instructions work with the accumulator only
5. SOH
6. CY =0
7. CY= I
8. CY= I
9. MOV C, P2. 7 i save status of P2.7 on CY
carry in RAM bit location 06
MOV 31,C jsave
10. MOV C,9 ;save statuS of RAM bit 09 in CY

MOV PI. 4, C jsave carry in Pl. 4

179
CHAPTER 6: ARITHMETIC, LOGIC INSTRUCTIONS, AND PROGRAMS
SECTION 6.5: BCD. ASCIJ, AND OTHER APPLICATION PROGRAMS

I. (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
7. 88H + 99H + AAH + BBH + CCH + DOH = 42FH. Dropping the carries we have 2FH, and
its 2's complement is OIH.
8. False
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 miero-
controller. 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 pro-
gram 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. It is easier and less time consuming to write in C than Assembly.


2. C is easier to modify and update.
3. You can usc code available in function libraries.
4. 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 dis-
cussed 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 small-
er hex files. In this section we focus on the specific C data types that are most use-
ful 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, includ-
ing 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 lim-
ited 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 com-
pilers 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 <reg51.h>
void main(void)
{
unsigned char Z;
for(z=O;z<=255;Z++)
Pl=z;

Run the above program' on your simulator to see how PI displays values 00 - FFH in
binary.

Example 7-2
Write an 8051 C program to send hex values for ASCII characters of 0, I, 2, 3, 4, 5, A,
S, C, and D to port PI.

Solution:
#include <reg51.h>
void main (void)
{
unsigned char mynum [] = "012345ABCD";
unsigned char Z;
for(z=O;z<=lO;Z++)
Pl=mynum[z] ;
}
. lator to see how PI displays values 30H, 3\ H,
Run the above program ~ ~~~ s;:;~ and 441-1the hex values for ASCII 0, 1, 2, and
32H, 33H, 34H, 35H, 41, " ,
so on.

183
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-3
Write an 8051 C program to toggle all the bits ofPl continuously,
Solution:
II Toggle PI forever
#include <regSI.h>
void main(void)
{
for (;;) Ilrepeat forever
(
PI=OxSS; Ilox indicates the data is in hex (binary)
Pl=OxAA;

Run the above program on your simulator to see how PI toggles continuously.
Examine the asm code generated by the C compiler.

Signed char

The signed char is an 8-bit data type that uses the most significant bit (07
of 07 - DO) to represent the - or + value. As a result, we have only 7 bits for the
magnitude of the signed number, giving us values from -128 to + 127. In situa-
tions where + and - are needed to represent a given quantity such as temperature,
the use of the signed char data type is a must.
Again notice that if we do not use the keyword unsigned, the default is the
signed value. For that reason we should stick with the unsigned char unless the
data needs to be represented as signed numbers.

Example 7-4

Write an 8051 C program to send values of --4 to +4 to port PI.

Solution:
Iisign numbers
#include <regSl.h>
void main (void)
{
char mynum[]= {+1,-1,+2/-2,+3,-3,+4,_4}j
unsigned char z;
for(z=O;z<=8;z++)
PI=mynum [zj .

Run the above program on your simulator to see how PI displays values of I FFH 2
FEH, 3, FDH, 4, and FCH, the hex values for + I _I +2 -2 d " ,
, , , ,an so on,

184
Unsigned int

The unsigned int is a lti-bit data type that takes a value in the range of 0 to
65535 (0000 - FFFFH). In the 8051, unsigned int is used to define l6-bit variables
such as memory addresses. It is also used to set counter values of more than 256.
Since the 8051 is an 8-bit microcontroller and the int data type takes two bytes of
RAM, wc must not use the int data type unless we have to. Since registers and
memory accesses are in 8-bit chunks, the misuse of int variables will result in a
larger hex file. Such misuse is not a big deal in PCs with 256 megabytes of mem-
ory, 32-bit Pentium registers and memory accesses, and abus speed of 133 MHz.
However, for 805\ programming do not use unsigned int in places where
unsigned char will do the job. Of course the compiler will not generate an error
for this misuse, but the overhead in hex file size is noticeable. Also in situations
where there is no need for signed data (sueh as setting counter values), we should
usc unsigned int instead of signed int. This gives a much wider range for data dec-
laration. Again, remember that the C compiler uses signed int as the default if we
do not use the keyword unsigned.

Signed int
Signed int is a 16-bit data type that uses the most significant bit (D 15 of
DIS - DO) to represent the - or + value. As a result, we have only 15 bits for the
magnitude of the number, or values from -32,768 to +32,767.

Sbit (single bit)


The sbit keyword is a widely used 8051 C data type designed specifically
to access single-bit addressable registers. It allows access to the single bits of the
SFR registers. As we saw in Chapter 5, some of the SFRs are bit-addressable.
Among the SFRs that are widely used and are also bit-addressable are ports PO -
P3. We can use sbit to access the individual bits of the ports as shown 111 Example
7-5.
Example 7-5
Write an 8051 C program to toggle bit DO of the port PI (P 1.0) 50,000 times.

Solution:
#include <reg5l.h>
sbit MYBIT = P1AO; //notice that sbit is
//declared outside of main
void main (void)
{
unsigned int z,
for (z=O; z<=50000; z++)
{
MYBIT = 0;
MYBIT = 1;
}
}
. 1 tor to see how P 1.0 toggles continuously.
Run the above program on your SII11U a
185
CHAPTER 7: 8051 PROGRAMMING IN C
Bit and sfr

The bit data type allows access to single bits of bit-addressabl~dmem~7


20 - 2FH. Notice that while the sbit data type IS used for bit-a ressa e
~a~~s the bit data type is used for the bit-addressable secuon of RAM~pae~120 _
2FH. ' To access the byte-size SFR registers, we use the sfr data type. e WI see
the use of sbit, bit, and sfr data types in the next section.
Table 7-1: Some Widely Used Data Types for 8051 C
Data Type Size in Bits Data RangelUsage
unsiged char 8-bit 0 to 255
(signed) char 8-bit -128 to +127
unsigned int 16-bit 0 to 65535
(signd) int 16-bit -32,768 to +32,767
sbit
I-bit SFR bit-addressable only
bit
l-bit RAM bit-addressable on Iy
sfr
8-bit RAM addresses 80 - FFH only

Time Delay

There are two ways to create a time delay in 8051 C:


I. Using a simple for loop
2. Using the 8051 timers .
In either case, when we write a time delay we must use the oscilloscope to
measure the duration of our time dclay. Next, we use the for loop to create time
delays. Discussion of the usc of the 8051 timer to create timc delays is postponed
until Chapter 9.
In creating a time delay using a for loop, we must be mindful of three fac-
tors that can affect the accuracy of the delay.
I. The 8051 design. Since the original 8051 was designed in 1980, both the fields
of IC technology and microprocessor architectural design havc seen great
advanccments. As we saw in Chapter 3, the numbcr of machine cycles and the
numbcr of clock periods per machine cycle vary among diffcrent versions of
the 8051/52 microcontroller. While the original 8051/52 design used 12 clock
periods per machine cycle, many of the newer gencrations of the 8051 use
fewer clocks per machine cycle. For example, the DS5000 uses 4 clock peri-
ods per machine cycle, while the DS89C420 uses only one clock per machine
cycle.
2. The crystal frequency connectcd to the XI - X2 input pins. The duration of the
clock period for the machine cycle is a function of this crystal frcquency.
3. Compi ler choice. The third factor that affccts the time delay is the compiler
used to compile the C program. When we program in Assembly language, we
ean control the exact instructions and their sequences used in thc delay sub-
routine. In the case of C programs, it is the C compilcr that Converts the C
statements and functions to Assembly languagc instructions. As a result, dif-
ferent compilers produce different code. In other words, ifwc compile a given
8051code.
hex C programs with differcnt compilers, each compiler produces different

. For the above reasons, When we write time delays lor C, we must use the
oscilloscopc to measure the exact duration. Look at Examples 7-6 through 7-8.
186
Example 7-6
Write an 8051 C program to toggle bits of Pl continuously forever with some delay.
Solution:
// Toggle PI forever with some de'lay in between "on" and "off".
#include <reg51.h>
void main (void)
{
unsigned int X;
fort; ;) //repeat forever
{
Pl=Ox55;
for(x=O;x<40000;x++); //delay size unknown
Pl=OxAA;
for(x=0;x<40000;x++) ;
}
}

Example 7-7
Write an 8051 C program to toggle the bits of PI ports continuously with a 250 ms
delay.
Solution:

The program below is tested for the DS89C420 with XTAL = 11.0592 MHz.

#include <reg51.h>
void MSDelay(unsigned inti;
void main (void)
{
while (1) //repeat forever
(
Pl=Ox55;
MSDelay (250) ;
Pl=OxAA;
MSDelay(250) ;
}

void MSDelay(unsigned int itime)


(
unsigned int i, j;
for(i=O;i<itime;i++)
for(j=0;j<1275;j++);
}
rainer and use the oscilloscope to measure the delay.
R un tea
h b ove program on your T

187
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-8 .

while (1) //another way to do it forever


{
PO;OX55;
P2;Ox55;
MSDelay(250) ;
PO;OxAA;
P2;OxAA;
MSDelay (250);

}
void MSDelay(unsigned int itime)
{
unsigned int i, j;
for(i;O;i<itime;i++)
for(j;0;j<1275;j++) ;

Review Questions

I. Give the magnitude of the unsigned char and signcd char data types.
2. Give the magnitude of the unsigned int and signed int data types.
3. If we are declaring a variable for a person's age, we should usc the _ data
type.

4. True or false. Using a for loop to create a time delay is not recommended if
you want your code be portable to other 8051 versions.
5. Give three factors that can affect the delay size.

SECTION 7.2: 1/0 PROGRAMMING IN 8051 C

In this section we look at C programming of the 1/0 ports for the 805J. We
look at both byte and bit 1/0 programming.

Byte size 1/0

As we slated in Chapter 4, ports PO - P3 are byte-accessible. We use the


PO - P3 labels as defined in the 8051/52 C header file. See Example 7-9. Examine
the next
8051 C. few examples to get a better understanding of how ports are accessed in

188
Example 7-9

LEDs are connected to bits P I and P2. Write an 8051 C program that shows the count
from 0 to FFH (0000 0000 to 1111 1111in binary) on the LEDs.

Solution:

#include <regs1.h>
#define LED P2 //notice how we can define P2
void main (void)
{
P1:OO; //clear P1
LED:O; //clear P2
for( ; ;) //repeat forever
{
Pl++i //increment P1
LED++ i //increment P2
}

Example 7-10
Write an 8051 C program to get a byte of data from PI, wait 112 second, and then send
it to P2.

Solution:

#include <regS1.h>
void MSDelay(unsigned int);
void main (void)
{
unsigned char mybyte;
P1:OxFF; //make P1 an input port
while (1)
{
mybyte:P1; //get a byte from P1
MSDelay (500) ;
p2:mybyte; //send it to P2

void MSDelay(unsigned int itime)


{
unsigned int i, j;
for(i:O;i<itime;i++)
for(j:O;j<127S;j++) ;

189
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-11
Write an 8051 C program to get a byte of data from PO. If it is less than 100, send it to
PI; otherwise, send it to P2.
Solution:

#include <regSl.h>
void main(void)

unsigned char mybyte;


PO=OxFF; //make PO an input port
while(l)
{
mybyte=PO; //get a byte from PO
if (mybyte<lOO)
P1=mybyte;
//send it to PI if less than 100
else
P2=mybyte;
//send it to P2 if more than 100
}

Bit-addressable I/O programming

The 1/0 ports of PO - P3 are bit-addressable. We can access a single bit


without disturbing the rest of the port. We usc the sbit data type to access a single
bit of PO- P3. One way to do that is to use the PX"y format where x is the port 0,
I, 2, or 3, and y is the bit 0 - 7 of that port. For example, PI "7 indicates PI. 7.
When using this method, you need to include the regS J.h file. Study the next few
examples to become familiar with the syntax.

Example 7-12

Writeof an
rest the8051 C P2.
bits of program to toggle only bit P2.4 continuously without disturbing the

Solution:

Iitoggling an individal bit


#include <regSI.h>
A

sbit main(void)
void mybit = P2 4; Iinotice the way single bit is declared
{
while (1)
{
mybit=l;
Ilturnonp2.4
mybit=O;
/Iturn off P2.4

190
Example 7-13

Write an 8051 C program to monitor bit P 1.5. If it is high, send 55H to PO; otherwise,
send AAH to P2.

Solution:
#include <regS1.h>
sbit mybit = P1AS; //notice the way single bit is declared
void main (void)
{
mybit=l; //make mybit an input
while (1)
(
if (mybit==l)
PO=OxSS;
else
P2=OxAA;
}
}

Example 7-14
A door sensor is connected to the PI.I pin, and a buzzer is connected to PI.7. Write an
8051 C program to monitor the door sensor, and when it opens, sound the buzzer. You
can sound the buzzer by sending a square wave of a few hundred Hz.

SOlution:

#include <regS1.h>
void MSDelay(unsigned intl ;
sbit Dsensor = P1A1; //notice the way single bit is defined
A
sbit Buzzer = P1 7;
void main(void)
{
Dsensor=l; //make P1.1 an input
while (Dsensor==l)
{
buzzer=O;
MSDelay(200) ;
buz~er=l;
MSDelay (200) ;
}
}

void MSDelay(unsigned int itime)

unsigned int i, j;
for(i=O;i<itime;i++)
for(j=O;jd27S;j++) ;

19\
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-15 .. .

Solution:

#include <regsl.h>
#define LCDData PI IILCDData declaration
A
sbit En=P2 O; lithe enable pin
void main (void!
(
unsigned char message [ ]= "The Earth is but One Country";
unsigned char Z;
for(z=O;Z<28;z++) Iisend all the 28 characters
(
LCDData=message[z] ;
En=l; Iia high-
En=O;
II-to-low pulse to latch the LCD data
)
}

Run the above program on your simulator to see how P I displays each character of
the message. Meanwhile, monitor bit P2.0 after each character is issued.

Accesssing SFR addresses 80 • FFH

Another way to access the SFR RAM space 80 - FFH is to use the sfr data
type. This is shown in Example 7-16. We can also access a single bit of any SFR
if wc specify the bit address as shown in Example 7-17. Both the bit and byte
addresses for the PO - P3 ports are given in Table 7-2. Notice in Examples 7-16
and 7-17, that there is no #include <reg51.h> statement. This allows us to access
any byte of the SFR RAM space 80 - FFH. This is a method widely used for thc
new generation of 8051 microcontrollers, and we will usc it in future chapters.

Table 7-2: Single Bit Addresses of Ports


PO Addr PI Addr P2 Addr
PO.O 80H PI,O P3 Addr Port's Bit
90H P2.0 AOH
PO.I 81H P 1.1 P3.0 BOH 00
91H P2.! A,IH
PO,2 82H P1.2 P3.1 BIH 01
92H P2.2 A2H
POJ 83H PI.3 P3.2 B2H 02
93H P2.3 A3H
PO,4 841-1 PI,4 P3J 83H 03
94H P2,4 A4H
PO.5 85H PI.5 P3,4 B4H 04
951-1 P2.5 A5H
PO,6 86H PI.6 P3.5 B5H 05
961-1 P2.6 A6H
PO.7 87H PI.7 P3.6 B6H 06
97H P2.7 A7H P3.7 B71-1 07

-
CI
Example 7-16

Write an 8051 C program to toggle all the bits of PO, PI, and P2 continuously with a
250 ms delay. Use the sfr keyword to declare the port addresses.
Solution:
II Accessing Ports as SFRs using the sfr data type
sfr PO = OX80; Iideclaring PO using sfr data type
sfr PI = OX90;
sfr P2 = OxAO;
void MSDelay(unsigned int);
void main (void)
{
while (1) lido it forever
{
PO=Ox55;
Pl=Ox55 ':
P2=Ox55';
MSDelay (250) ; 11250 ms delay
PO=OxAA;
PI=OxAA;
P2=OxAA;
MSDelay(250) ;
}
}

void MSDelay(unsigned int itime)


{
unsigned int i, j;
for(i=O;i<itime;i++)
for(j=0;jd275;j++) ;
}

Example 7-17
Write an 805 J C program to turn bit P 1.5 on and off 50,000 times.
Solution:

sbit MYBIT = Ox95; Ilanother way to declare b·It PI 5 A

void main (void)


{
unsigned int Z;
for(z=0;z<50000;Z++)
{
MYBIT=l;
MYBIT=O;
}
}

193
fAPTER 7: 8051 PROGRAMMING IN C
. ddressable RAM
.
bit data type for bit-a ble SFR registers only.
Using . d for bit-addressa . f the data
. d type IS use . dd essable section 0
The sbit ala tore some data in a bit-a r· as shown in Example
Sometimes we need to s d that we usc the bit data type,
RAM space 20 - 2FH. To 0 ,

7-18.

Example 7-18 f bit PI .,a save it, and send it to P2.? con-
. an 8051 C program to get the status 0 I
Write
tinuously.

Solution:

#include <regSI ~h>


sb't
1 inbit : PI A0;
sbit outbit : P2 7; ..
IIsb1t lS use d to declare SFR bits
bit membit; Iinotlce
. we u se bit to declare
Ilbit-addressable memory
void main (void)
(
while (I)
{
membit:inbit; Ilget a bit from Pl.O
outbit:membit; Iland send it to P2.7
}

Review Questions
I. The address of P I is -:-_
2. Write a short program that toggles all bits of P2.
3. Write a short program that toggles only bit PI.O. . I bit
4. True or false. The sbit data type is used for both SFR and RAM sing c- 1
addressable locations.
5. True or false. The bit data type is used only for RAM single-bit addressable
locations.

SECTION 7.3: LOGIC OPERATIONS IN 8051 C

One of the most important and powerful features of the C language is its
ability to perform bit manipulation. Because many books on C do not cover this
important topic, it is appropriate to discuss it in this section. This section describes
the action of bit-wise logic operators and provides some examples of how they are
used.

194
Bit-wise operators in C
While every C programmer is familiar with the logical operators AND
(&&), OR (II), and NOT (!), many C programmers are less familiar with the bit-
wise operators AND (&), OR (I), EX-OR ("), Inverter H, Shift Right (»), and
Shift Left «<). These bit-wise operators are widely used in software engineering
for embedded systems and control; consequently, understanding and mastery of
them are critical in microprocessor-based system design and interfacing. See
Table 7-3.
Table 7-3: Bit-wise Logic Operators for C
AND OR EX-OR Inverter
A B A&B AlB A"B Y~B
0 0 0 0 0 1
0 1 0 I 1 0
I 0 0 1 I
1 1 I I 0

The following shows some examples using the C logical operators.


I. Ox35 & OxOF = Ox05 f* ANDing *f
2. Ox04 I Ox68 = Ox6C f* ORing: *f
3. Ox54 " Ox78 = Ox2C f* XORing *f
4. -Ox55 = OxAA f* Inverting 55H *f

Examples 7-19 and 7-20 show the usage bit-wise operators.

Example 7-19
Run the following program on your simulator and examine the results.

Solution:

#include <reg5I.h>
void main (void)
{
PO= ox35 & OxOF; I lANDing
PI= Ox04 I Ox68; IIORing
P2= Ox54
A
Ox?8; IIXORing
PO= -Ox55; Ilinversing
3; Iishifting right 3 times
PI= Ox9A »
4; Iishifting right 4 times
P2= Ox?? »
4; Iishifting left 4 times
PO= Ox6 «
}

195
CHAPTER 7: 8051 PROGRAMMING IN C
Solution: . · h XTAL = 11 .0592 MHz.
d for the DS89C420 WIt
The program below IS teste

Uinclude <reg51.h>
void MSDelay(unsigned inti ;
void main(voidl
(
PO;Ox55;
P2=Ox55;
while (1)
(
PO;-PO;
P2;-P2;
MSDelay(250) ;

void MSDelay(unsigned int itime)


(
unsigned int i, j;
for(i;O;i<itime;i++1
for(j;O;j<1275;j++l;

Bit-wise shift operation in C

There are two bit-wise shift operators in C: (I) shift right ( »), and
(2) shift left (<<).

Their format in C is as follows:


data» number of bits to be shifted right
data « number of bits to be shifted left

The following shows some examples of shift operators in C.


I. Ox9A» 3= Ox13 f* shifting right 3 times */
2. Ox??» 4 = Ox07 f* shifting right 4 times *f
3. Ox6« 4 = Ox60 f* shifting left 4 times *f

Study Examples 7-21,7-22, and 7-23, showing how the bit-wise operators
are used in the 805 J C.

196
Example 7-21
Write
250 msandelay
8051 UsC program
th E to
0 togg I-eat 11 h e bits
. of PO, PI, and P2 continuously
. with a
. e e x- R operator.

Solution:

The program below is tested for the DS89C420 with XTAL = II 0592 MH
#lnclude <reg51.h> . z.
void MSDelay(unsigned int);
void main (void)
{
PO~Ox55;
Pl~Ox55;
P2~Ox55;
while(l)
{
PO=POAOxFF;
Pl=P1AOxFF;
P2=P2AOxFF;
MSDelay (250);
}
}

void MSDelay(unsigned int itime)


{
unsigned int i, j;
for(i=O;i<itime;i++)
for(j=0;j<1275;j++) ;
}

Example 7-22
Write an 8051 C program to get bit Pl.O and send it to P2.7 after inverting it.

Solution:

#include <reg5l.h>
sbit inbit=P1AO;
A //sbit is used declare port (SFR) bits
sbit outbit=P2 7;
//notice this is bit-addressable memory
bit membit;
void main(void)
{
while (1)
{ //get a bit from Pl.O
membit=inbit; //invert it and send it to P2.7
outbit=-membit;
}
}

197
CHAPTER 7: 8051 PROGRAMMING IN C
Example 7-23 d the P 1.0 and PI. J bits
. an d issue an ASCII character to
. 51 C program to rea
Write an 80 he following table.
PO accordmg to t
PI.I PI.O
o 0 sen d '0' to PO
o I send']'toPO
I 0 send '2' to PO
I I send '3' to PO
Solution:
#include <reg5l.h>
VOlid main (voi d)
{
unsigned char z;
z=Plj //read PI
z=z&Ox3; //mask the unused bits
switch(z) / /rnake decision
(
case (0):
(
po= ' 0 I ; / / issue ASCII 0
break;
)
case n ) .
{
po= II! i / / issue ASCII I
break;
}
case tz) :
(
PO=' 2' ; / / issue ASCII 2
break;
)
case (3) :
(
PO='3 1;
/ / issue ASCII 3
break;

Review Questions

I. Find the content of P I after the following C code in each ease.


(a) Pl=OX37&OxCA; (b) PI=OX371 OXCA; (e) PhOX37 OxCA; A

2. To mask certain bits we must AND them with _


J. To set high eertain bits we must OR them with __
4. EX-ORing a value with itself results in
5, FindP2=O;
the Contents of P2 after exeeution of the following code.
P2=P2!OX99;
P2=-P2;

198
SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C

Recall that BCD numbers were discussed in Chapter 6. As stated there,


many newer microcontrollers have a real-time clock (RTC) where the time and
date are kept even when the power is off. Very often the RTC provides the time
and date 10 packed. BCD. However, to display them they must be converted to
ASCII. In this section we show the application of logic and rotate instructions in
the co~verslOn of BCD and ASCII.

ASCII numbers
. On ASCII keyboards, when thc key "0" is activated, "0 II 0000" (30H)' is
provided to the computer. Similarly, 31H (01 I 0001) is provided for the kcy "I",
and so on, as shown in Table 7-4.

Table 7-4: ASCII Code for Digits 0 - 9


Key ASCII (hex) Binary BCD (unpacked)
o 30 011 0000 00000000
1 31 0110001 00000001
2 32 011 DOlO 00000010
3 33 0110011 00000011
4 34 0110100 00000100
5 35 0110101 00000101
6 36 011 0 II 0 00000110
7 37 0110111 00000111
8 38 011 1000 0000 1000
9 39 0111001 0000 1001

Packed BCD to ASCII conversion


The RTC provides the time of day (hour, minute, second) and the datc
(year, month, day) continuously, regardless of whether the power is on or off.
However, this data is provided in packed BCD. To convert packed BCD to ASCII,
it must first be converted to unpacked BCD. Then the unpacked BCD is tagged
with 011 0000 (30H). The following demonstrates converting from packed BCD
to ASCII. See also Example 7-24.

Unpacked BCD ASCII


Packed BCD
Ox02, Ox09 Ox32, Ox39
Ox29
00000010,00001001 00110010,00111001
00101001

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: 4 and
7 on the keyboard give 34H and 37H, respectively. The goal IS to produce 47H or
"0 I00 0111", which is packed BCD.

199
CHAPTER 7: 8051 PROGRAMMING IN C
unpacked BCD Packed BCD
Key ASCII
4 34 00000100
00000111 01000111 or 47H
7 37

After this conversion, the packed BCD numbers are processed and the
result will be in packed BCD format. Chapter 16 discusses the RTC ehip and uses
the BCD and ASCrr conversion programs shown in Examples 7-24 and 7-25.

Example 7-24
Writean 8051 C program to convert paeked BCD Ox29 to ASCII and display the b te
on PI and P2. y s

Solution:

#include <regSI.h>
void main (void)
{
unsigned char x, y, Z;
unsigned char mybyte ; OX29;
x ; mybyte & OxOF' //mask lower 4 bits
PI; x I OX30; r //make it ASCII
Y ; mybyte & OxFO', //mask upper 4 bits
y;y»4; //shift it to lower 4 bits
P2 ; Y I OX30; //make it ASCII

Example 7-25
Write an 8051 C program to convert ASC rr di .
play them on PI. igits of'4' and '7' to packed BCD and dis-

Solution:

#i~clude <regSI.h>
vord main (void)
{
unsigned char bcdbyte;
unsigned char w:;: 141 j
unsigned char z:::: 7 j I I

w ; W & OXOF.
II W ::: W < 4.

Z = Z & OX;F.
I
//mask 3
//shift left
I/mask 3
to make upper BCD d'19lt
.
bCdbyte = W I' z .
PI ; bCdbyte., ' I/combine to make packed BCD

200

c1
Checksum byte in ROM
To ensure the integrity of 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 check-
sum 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 7-26.

Example 7-26
Assume that we have 4 bytes of hexadecimal data: 25H, 62H, 3FH, and 52H.
(a) Find the checksum byte, (b) perform the checksum operation to ensure data
integrity, and (c) if the second byte 62H has been changed to 22H, show how check-
sum detects the error.

Solution:

(a) Find the checksum byte.


25H
+ ·62H
+ 3FH
+ 52H
lIBH (Dropping carry of 1 and taking the 2's complement, we get E8H.)

(b) Perform the checksum operation to ensure data integrity.


25H
+ 62H
+ 3FH
+ 52H
+ EBH
200H (Dropping the carries we gel 00, which means data is not corrupted.)

(c) If the second byte 62H has been changed to 22H, show how checksum detects
the error.
25H
+ 22H
+ 3FH
+ 52H
+ EBH d)
1COH (Dropping the carry, we gel COH, which means data is corrupte .

201
CHAPTER 7: 8051 PROGRAMMING IN C
&

Example 7-27
Write an 8051 C program to ca Icu Iate the checksum byte for the data given in Example
7-26.

Solution:

#include <reg51.h>
void main (void)

unsigned char mydata[] ~ (OX25,OX62,Ox3F,OX52);


unsigned char sum~O;
unsigned char X;
unsigned char chksumbyte;
for(x~o;x<4;x++)
(
P2~mydata[x] ;
//issue each byte to P2
sum~sum+mydata[xJ ; //add them together
Pl=suffi;
} //issue the sum to PI
chksUmbyte~-sum+l;
PI~chksumbyte; //make 2's complement
//show the checksum byte

Single-step the above program on the 8051 simulator and examine the contents of P I
and P2. Notice that each byte is put on P j as they are added together.

Example 7-28

Write an 8051 C program to perform step (b) of Example 7-26. If data is good, send
ASCII character 'G' to PO. Otherwise send 'B' to PO.

Solution:

#include <reg51.h>
void main (void)
(

unsigned char mYdata[]~(OX25,OX62,OX3F,OX52,OXE8};


unsigned char chksum~o;
unsigned char x;
for(x~O;X<5;x++)
chksum~chksum+mYdata[x];
if(chksum~~o) //add them together
pO= '8' ;
else
PO:::: 'B' i
}
Binary (hex) to decimal and ASCII conversion in 8051 C

The printf function is part of the standard I/O library in C and can do many
things, including converting data from binary (hex) to decimal, or vice versa. But
printf takes a lot of memory space and increases your hex file substantially .. For
this reason, in systems based on the 8051 microcontroller, it is better to write your
own conversion function instead of using printf.
One of the most widely used conversions is the binary to decimal conver-
sion. Tn devices such as AOC (Analog-to-Digital Conversion) chips, the data is
provided to the microcontroller in binary. In some RTCs, data such as time and
dates are also provided in binary. In order to display binary data we need to con-
vert it to decimal and then to ASCII, Since the hexadecimal format is a conven-
ient way of representing binary data we refer to the binary data as hex. The bina-
ry data 00 - FFH converted to decimal will give us 000 to 255. One way to do that
is to divide it by 10 and keep the remainder, as was shown in Chapter 6. For exam-
ple, 1111110 I or FOH is 253 in decimal. The following is one version of an algo-
rithm for conversion of hex (binary) to decimal:

Quotient Remainder
FD/OA 19 3 (low digit) LSD
19/0A 2 5 (middle digit)
2 (high digit) (MSO)

Example 7-29 shows the C program for that algorithm.

Example 7-29
Write an 8051 C program to convert 11111101(FD hex) to decimal and display the dig-
its on PO, PI, and P2.

SOlution:

#include <reg51.h>
void main (void)
{
unsigned char x, binbyte, d1, d2, d3;
binbyte ; OXFD; Ilbinary(hex} byte
x ; binbyte I 10; Iidivide by~O
d1 ; binbyte % 10; I Ifind remal~der (LSD)
d2 ; x % 10' Ilmiddle d i.q
i t; .'
' Ilmost significant di q i t (MSD)
d3 ; X I 10; .
PO = d1;
PI = d2;
P2 ; d3;
}

203
CHAPTER 7: 8051 PROGRAMMING IN C
Review Questions
.
I. For the following decimal numbers,. give
. the Packcd BCD and unpacked BCD
representations.
(a) 15 (b) 99 f t for "76" and its BCD version.
2. Show the binary and hex orma ~SC" . Hand H
3 67H in BCD when converted to IS -- . --.. to ASCII?
4.. Does the following convert unpacked BCD In register A
mydata ~ Ox09 + Ox30; ?
Why is the use of packed BCD preferable to ASCII.
5. Which one takes more memory space: packed BCD or ASCII?
~: In Question 6, which is more universal? I 22H 76"H 5FH 8CH 99H
Find the checksum byte for the following va ues; . ' , , , .
8. To test data integrity, we add them together, includmg the checksum byte. Then
9. dro the carries. The result must be equal to __ If the data IS not corrupted.
10. An ~DC provides an input of 0010 0110. What happens if we output that to
the screen?

SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C

Using the code (program) space for predefined data is the widely used
option in the 8051, as we saw in Chapter 5. In that chapter we saw how to use the
Assembly language instruction MOVe to access the data stored In the 8051 code
space. In this chapter, we explore the same concept for 8051 C.
RAM data space v. code data space

In the 8051 we have three spaces in which to store data. They arc as fol-
lows:
I. The 128 bytes of RAM space with address range 00 - 7FH. (In the 8052, it is
256 bytcs.) We can read (from) or write (into) this RAM space directly or indi- .
rectly using the RO and R I registers as we saw in Chapter 5.
2. The 64K bytes of code (program) space with addresses of 0000 _ FFFFH. This
64K bytes of on-chip ROM space is used for storing programs (opcodes) and
therefore is directly under the control of the program counter (PC). We can use
the "MOve A, @A+DPTR" Assembly language instruction to access it for
data (see Chapter 5). There are two problems with using this code space for
data. First, since it is ROM memory, we can bum Our predefined data and
tables into it. But we cannot write into it during the execution of the program.
The second problem is that the more of this code space we use for data, the less
is left for our program code. For example, if we have an 8051 chip such as
DS89C420 with only 16K bytes of on-chip ROM, and we usc 4K bytes of it to
store some look-up table, only 12K bytes is left for the code program. For
some applications this can be a problem. For this reason Intel created another
memory space called external memory especially for data. This is discussed
next very briefly and we postpone the full discussion to Chaptcr 14.

204

CHAP
3. The 64K bytes of external memory, which can be used for both RAM and
ROM. This 64K bytes is called external since we must use the MOVX
Assembly language instruction to access it. At the time the 8051 was designed,
the cost of on-chip ROM was very high; therefore, Intel used all the on-chip
ROM for code but allowed connection to external RAM and ROM. In other
words, we have a total of 128K bytes of memory space since the off-chip or
external memory space of 64K bytes plus the 64K bytes of on-chip space pro-
vides you a total of 128K bytes of memory space. We will discuss the exter-
nal memory expansion and how to access it for both Assembly and C in
Chapter 14.
Next, we discuss on-chip RAM and ROM space usage by the 8051 C com-
piler. We have used the Proview32 C compiler ro verify the concepts discussed
next. Use the compiler of your choice to verify these concepts.
RAM data space usage by the 8051 C compiler
In Assembly language programming, as shown in Chapters 2 and 5, the J 28
bytes of RAM space is used mainly by register banks and the stack. Whatever
remains is used for scratch pad RAM. The 8051 C compiler first allocates the first
8 bytes of the RAM to bank 0 and then some RAM to the stack. Then it starts to
allocate the rest to the variables declared by the C program. While in Assembly
the default starting address for the stack is 08, the C compiler moves the stack's
starting address to somewhere in the range of 50 - 7FH. This allows us to allocate
contiguous RAM locations to array elements.
In cases where the program has individual variables in addition to array
elements, the 8051 C compiler allocates RAM locations in the following order:
1. Bank 0 addresses 0 -,7
2. Individual variables addresses 08 and beyond
3. Array elements addresses right after variables
4. Stack addresses right after array elements
7F
You can verify the above order by
running Example 7-30 on your 8051 C Scratch Pad RA M
simulator and examining the contents of
the data RAM space. Remember that 30

array elements need contiguous RAM 2F


Bit-Addressable RAM
locations and that limits the size of the 20
array due to the fact that we have only . IF
Register Bank 3
128 bytes of RAM for everything. In the
18
case of Example 7-31 the array elements
17
are limited to around 100. Run Example Register Bank 2

7-31 on your 8051 C simulator and exam- 10

ine the RAM space allocation. Keep OF


Register Bank 1 (Stack)
changing the size of the array and monitor 08
the RAM space to see what happens. 07
Register Bank 0
00
Figure 7-1. RAM AllocatIOn 10 the 8051

205
CHAPTER,7: 8051 PROGRAMMING IN C
Example 7-30 8051 simulator. Examine the
. h fi llowing program on your
Compi Ie and single-step teo I te the ASCII values.
contents of the I28-byte RAM space to oca

Solution:
#include <regsl.h>
void main(void)

{ unsigned char mynum [] = "ABCDEF"; IIThis uses RAM space


IIto store data
unsigned char z;
for(z=0;z<=6;z++)
Pl=mynum [z];
}

Run the above program on your 8051' sirnu lator and ASCIIexamineI ttthe RAM space'C'to and
'A' '8' locate
so
va Iues
41 H., 42H , 43H , 44H , etc ., the hex values for e ers , , ,
on.

Example 7-31

Write, compile, and single-step the following program on your 805 J simulator.
Examine the contents of the code space to locate the values.

Solution:
#include <regsl.h>
void main(void)
{
unsigned char mydata(lOO]; 11100 byte space in RAM
unsigned char x,z=O;
for(x=O;x<lOO;x++)

z--;
Ilcount down
mydata[x]=z;
Iisave it in RAM
Pl=z;
} Ilgive a copy to PI too

Run the above program on your 8051 simulator and examine the data RAM space to
locate values FFH, FEH, FDH, and so on in RAM.

The 8052 RAM data space

Intel added some new features to the 8051 microcontroller and called it the
8052. One of the new features was an extra 128 bytes of RAM space. That means
that the 8052 has 256 bytes of RAM space instead of 128 bytes. Remember that
the 8052 is code-compatible with the 8051. This means that any program written
for the 8051 will run on the 8052, but not the other way around since some fea-

206
-
tures of the 8052 do not exist in the 8051. The extra 128 bytes of RAM helps the
8051/52 C compiler to manage its registers and resources much more effectively.
Since the vast majority of the new versions of the 8051 such as DS89C4xO arc
really based on 8052 architecture, you should compile your C programs for the
8052 microcontroller. We do that by (I) using the reg52.h header file, and (2)
choosing the 8052 option when compiling the program.

Accessing code data space in 8051 C


In all our 8051 C examples so far, byte-size variables were stored in the
128 bytes of RAM. To make the C compiler use the code space instead of the
RAM space, we need to put the keyword code in front of the variable declaration.
The following are some examples:

code unsigned char mynuml)» "012345ABCD"; I luse code space


code unsigned char weekdays;?, month;Ox12; Iluse code space

Example 7-32 shows how to use code space for data in 8051 C.

Example 7-32
Compile and single-step the following program on your 8051 simulator. Examine the
contents of the code space to locate the ASCII values.

Solution:

#include <reg51.h>
void main (void)
{
code uns igned char mynum[]; "ABCDEF"; Iluses code space
Ilfor data
unsigned char z;
for(z;O;z<;6;z++)
Pl;mynum [z] ;
}
51 simulator and examine the code space to locate
Run the above program on your 80 f 'A' 'B' 'C'
43H 44H etc the hex values for ASCII characters a , , ,
va 1ues 41H , 42H , , , 0'
and so on.

Compiler variations
shows three different versions of a program that
Look at Examp Ie 7 -33 . It . '. h h 8051 C
." LO" to the PI port. Compile each program WIt t e
sends the stnng HEL the hex file size Then compile each pro-
compiler of your choice and co~pare d examine tile hex file size to see the effec- .
gram on a different 8051 C com;~ e~: MicroDigilalEd.com for 8051 C compil-
tiveness of your C compder. e .
ers.

207
CHAPTER 7: 8051 PROGRAMMING IN C
Example
Compare 7-33 . programs an d discuss the advantages and disad-
and contrast the following
vantages of each one.

(a)
#include <regSl.h>
void main(void)
{
PI:::: I H' i
PI:::: E
I r ;

Pl='Lr i
Pl='L'j
PI= '0' i

(b)
#include <regSl.h>
void main (void)
{
unsigned char mydata []= "HELLO" ;
unsigned char z;
for(z=O;z<=S;z++)
P1=mydata Izl ;

(c)
#include <regSl.h>
void main (void)
{
//Notice Keyword code
code unsigned char mydata [J = "HELLO";
unsigned char Z;
for(z=o;z<=s;z++)
Pl=mydata[z] ;
}

Solution:

All the programs send out "HELLO" to P I, one character at a time, but they do it in dif-
ferent ways. The first one is short and simple, but the individual characters are embed-
dcd into the program. ]f we change the characters, the whole program changes. It also
mixes the code and data together. The second one uses the RAM data space to store
array elements, therefore the size of the array is limited. The third one uses a separate
area of the code space for data. This allows the size of the array to be as long as you
want if you have the on-chip ROM. However, the more code space you use for data, the
less space is left for your program code. Both programs (b) and (c) are easily upgrad-
gramif(a).
able we want to change the string itself or make it longer. That is not the case for pro-
See the following Web sit~sfor 8051 C compilers:

www.MicroDigitaIEd.com

www.8052.com.

Review Questions
1. The 8051 has __ bytes of data RAM, while the 8052 has bytes.
2. The 8051 has __ K bytes of code space and __ K bytes of external data
space.
3. True or false. The code space can be used for data but the external data space
cannot be used for code.
4. Which space would you use to declare the following values for 8051 C?
(a) the number of days in the week .
(b) the number of months in a year
(c) a counter for a delay
5. In 8051 C, we should not use more than 100 bytes of the RAM dataspace for
variables. Why?

SECTION 7.6: DATA SERIALIZATION USING 8051 C

Serializing data is a way of sending a byte of data one bit at a time through
a single pin of mir.rocontroller. There are two ways to transfer a byte of data
serially:

I. Using the serial port. When using the serial port, the programmer has very
limited control over the sequence of data transfer. The detail of serial port data
transfer is discussed in Chapter 10.
2. The second method of serializing data is to transfer data one bit a time and con-
trol the sequence of data and spaces in between them. In many new generations
of devices such as LCD, ADC, and ROM the serial versions are becoming pop-
ular since they take less space on a printed circuit board.

Examine the next four examples to see how data serialization is done in
8051 C.

209
CHAPTER 7: 80S1 PROGRAMMING IN C
Example 7-34
Write a C program to send out the value 44H serially one bit at a time via P 1.0. The
LSB should go out first.

Solution:
((SERIALIZING DATA VIA Pl.0 (SHIFTING RIGHT)
#include <regsl.h>
sbit PlbO = PIAO;
sbit regALSB = ACCAO;
void main (void)

unsigned char conbyte OX44;


unsigned char X;
ACC = conbyte;
for(x=O; x<8; x++)
{
PlbO = regALSB;
ACC = ACC » 1;

PIN

DL-__
D7
R_E_G_A Df---~.1
DO
P1.O'

Example 7-35

Write a C program to send out the value 44H serially one bit at a time . PI 0 The
MSB should go out first. via ..

Solution:
((SERIALIZING DATA VIA Pl.0 (SHIFTING L
#1nclude <regSl.h> EFT)
sbit PlbO = PI O'A
sbit regAMSB = AC~A7'
void main (void) ,

unsigned char conbyte _-0x44;


unsigned char x.
ACC = conbyte; ,
for(x=o; x<8; x++)
{
PIbO = regAMSB;
ACC = ACC « 1.
} ,
Example 7-36
Write a C program
. to bring inay b t e 0 f data seri
ata senally one bit..' at a nrne via P 1.0. The LSB
should come ill first.

Solution:
//BRINGING IN DATA VIA PI.O (SHIFTING RIGHT)
#include <reg51.h~
sbit PIbO = PIAO;
A
sbit ACCMSB = ACC ?;
void main (void)

unsigned char conbyte = OX44;


unsigned char x;
for(x=O; x<8; x++)
{
ACCMSB = PIbO;
ACC = ACC » I;
}
P2=ACC;

PIN

Ipl.Ol"'-··O D7 L-- REGA 0 DO

Example 7-37
Write a C program to bring in a byte of data serially one bit at a time via PI.O. The MSB
should come in first.

Solution:
//BRINGING DATA IN VIA PI.O (SHIFTING LEFT)
#include <reg51.h~
sbit PIbO = PIAO;
sbit regALSB = ACCAO;
void main (void)

unsigned char x;
for(x=O; x<8; x++)
{
regALSB = PIbO;
ACC = ACC « 1;
}
P2=ACC;
}

211
CHAPTER 7: 8051 PROGRAMMING IN C
SUMMARY

This chapter dealt with 8051 C programming, especially lA/ON6ro~~Il~~~g


. C W Iso showed the logic operators , , ,
and time delays In 8051 :. e a a Iieations for these operators were dis-
and complement.
cussed. This chapter also escn e
.~0~~cf6
In addldtlOn, and ASCII formats and conversions in
d RAM data
I C We also compared and contrasted the use of code spaee an .
~~~ce i~ 8051 C. The widely used teehnique of data serialization was also dis-
eussed.

PROBLEMS

SECTION 7.1: DATA TYPES AND TIME DELAY IN 8051 C

I. Indicate what data type you would use for each of the following variables:
(a) the temperature
(b) thc number of days in a week
(e) the number of days in a year
(d) the number of months in a year
(e) the counter to keep the number of people getting on a bus
(I) the eounter to keep the number of people going to a class
(g) an address of 64K bytes RAM space
(h) the voltage
(i) a string for a message to welcome people to a building
2. Give the hex value that is sent to the port for each of the following C state-
ments:
(a) PI=14; (b) PI=OxI8; (e) PI:' A' ; (d) PI=?;
(e) PI=32; (f) PI=Ox45; (g) Pl=255; (h) PI=OxOF;
3. Give three factors that can affect time delay code size in the 8051 rrucrocon-
troller.
4. Of the three factors in Problem 3, which one can be set by the system design-
er?
5. Can the programmer set the number of clock cycles used to execute an instruc-
tion? Explain your answer.
6. Explain why various 8051 C compilers produce different hex file sizes.

SECTION 7.2: 110 PROGRAMMING IN 8051 C

7. What is the difference between the sbit and bit data types?
8. Write an 8051 C program to toggle all bits of PI every 200 ms.
9. Use your 8051 C compiler to see the Shortest time delay that you can produce.
10. Write a lime delay funetion for 100 ms,
II. Write an 8051 C program to toggle only bit P 1.3 every 200 ms.
12. Write an 8051 C program to Count up PI from 0 _ 99 eontinuously.

212
SECTION 73: LOGIC OPERATIONS IN 8051 C
I

\ 3. Indicate the data on the ports for each of th "11 ..


M The onerati e 10 owing. .
ole: e operations are independent of each other.
; (a) P1~OxFO&Ox45; (b) P1~oxFO&Ox56'
(c) P1~OxFOAOx76; (d) P2~OXFO&OX90:
(e) P2~OxFOAOx90; (t) P2~OxFO I OX90;
(g) P2~OXFO:OXFF; (h) P2~oxFO I Ox99;
. (1) P2~OxFO OXEE; U) P2~OxFOAOxAA;
14. Find the contents of the port after each of the following operations.
(a) P1~Ox65&Ox76; (b) Pl~Ox70 I ox6B;
(c) P2~Ox95AOxAA; (d) P2~Ox5D&ox78;
(e) P2~OxC51 OX12; (f) PO~Ox6A Ox6E;
A

(g) P1~Ox371 Ox26;


15. Find the port value after each of the following is executed.
(a) P1~Ox65»2; (b) P2~ox39«2;
(c) P1~OxD4»3; (d) P1~OxA7«2;
16. Show the C code to swap Ox95 to make it Ox59.
17. Write a C program that finds the number of zeros in an 8-bit data item.
18. A stepper motor uses the following sequence of binary numbers to move the
motor. How would you generate them in 8051 C?
1100,0110,0011,1001

SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C

19. Write a program to convert the following series of packed BCD numbers to
ASCIl. Assume that the packed BCD is located in data RAM. :
76H,87H,98H,43H
20. Write a program to convert the following series of ASCII numbers to packed
BCD. Assume that the ASCII data is located in data RAM. ' I
"8767"
21. Write a program to
gct an 8·bit binary number from PI, convert it to ASCII,
and save the result if the input is .packed BCD of 00 . Ox99. Assume P I has
1000 100 I binary as input.

SECTION 7.5: ACCESSING CODE ROM SPA'CE IN 8051 C

22. Indicate what memory (embedded, data RAM, or code ROM space) you would
use for the following variables:
(a) the temperature
(b) the number of days in week
(c) the number of days in a year
(d) the number of months in a year
(e) the counter to keep the number of people getting on a bus
(f) the counter to keep the number of people gomg to a class
(g) an address of 64K bytes RAM space
(h) the voltage· . .
(i) a string for a message to welcome people to building
213
CHAPTER 7: 8051 PROGRAMMING IN C
23. Discuss why the total size of your 8051 C variables should not exceed 100
bytes.
24. Why do we usc the ROM code space 'for video game characters and shapes?
25. What is the drawback of using RAM data space for 8051 C variables?
26. What is the drawback of using ROM code space for 805 J C data?
27. Write an 8051 C program to send your first and last names to P2. Use ROM
code space.

ANSWERS TO REVIEW QUESTIONS

SECTION 7.1: DATA TYPES AND TIME DELAY IN 8051 C

I. 0 to 255 for unsigned char and -128 to +127 for signed char
2. 0 to 65,535 for unsigned int and -32,768 to +32.767 for signed int
3. Unsigned char
4. True
5. (a) Crystal frequency of8051 system, (b) 8051 machine eycle timing and (c) compiler use for
8051 C '

SECTION 7.2: I/O PROGRAMMING IN 8051 C

I. 90H
2. #include <reg51.h>
void rnainj)
1
P2 = Ox55;
P2 = OxAA
}
3. #include <reg51.h>
sbit PIObit = PIAO;
void mainO
{
PIObit = 0;
PIObit = I;
}
4. False, only to SFR bit
5. True

SECTION 7.3: LOGIC OPERATIONS IN 8051 C

I. (a) 02 (b) FFH (c) FDH


2. Zeros
3. One
4. All zeros
5. 66H

SECTION 7.4: DATA CONVERSION PROGRAMS IN 8051 C

I. (a) 15H = 00010101 packed BCD 00


(b) 99H = 10011001 packed BCD' 0 000001,00000101 unpacked BCD
2. 3736H=00110111001l01l0B ,0001001,00001001 uopackedBCD
and in BCD we have 76H = 011101 lOB

214
3. 36H,37H
4. Yes, since A = 39H
5. Space savings
6. ASCII 7. ASCII
8. 21CH
9. 00
10. First convert from binary to decimal, then to ASCII, then send to screen.

SECTION 7.5: ACCESSING CODE ROM SPACE IN 8051 C

I. 128,256
2. 64K,64K
3. True
4. (a) data space, (b) data space, (c) RAM space
5. The compiler starts storing variables in code space.

215
CHAPTER 7: 8051 PROGRAMMING IN C
CHAPTER 8

8051 HARDWARE
CONNECTION AND
INTEL HEX FILE

OBJECTIVES

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

» Explain the purpose of each pin of the 8051 microcontroller


» Show the hardware connection of the 8051 chip
» Explain how to design an 8051-based system
» Show the design of the DS89C4xO Trainer
» Code the test program in Assembly and C for testing the DS89C4xO
» Show how to delete programs from DS89C4xO flash ROM using
PC Hyper'Ierminal
» Show how to download programs into a DS89C4xO system using
PC HyperTerminal
» Explain the Intel hex file

217
This chapter describes the process of physically connecting and testing
805 l-based systems. In the first section we describe the function of the pins of
8051 chip. The second section shows the hardware connection for an 8051 Trainer
using the DS89C4xO (DS89C420/30/40/50) chip. It also shows how to download
programs into a DS89C4xO-based system using PC HyperTerminal. In Section 8.3
wc explain thc characteristics of the Intel hex file.

SECTION 8.1: PIN DESCRIPTION OF THE 8051

Although 8051 family members (c.g., 8751, 89C51, 89C52, DS89C4xO)


come in different packages, such as DIP (dual in-line package), QFP (quad flat
package), and LLC (Ieadless chip carrier), they all have 40 pins that are dedicated
to various functions such as I/O, RD, WR, address, data, and interrupts. It must bc
noted that some companies provide a 20-pin version of the 8051 with a reduced
number of I/O ports for less demanding applications. However, since the vast
majority of developers use the 40-pin chip, we will concentrate on that. Figure 8-1
shows the pins for thc 8051/52. For the 8052 chip some of the pins have extra
functions and thcy will bc discussed as we study them.

PDIP/Cerdip

P1.0 1 40 Vee
P1.1 2 39 PO.O(ADO)
P1.2 3 38 P01 (AD1)
P1.3 4 37
P1.4
8051/52 PO.2 (AD2)
5 36 PO.3 (AD3)
P1.5 6
(DS89C4xO
35 POA (AD4)
P1.6 7 AT89C51 34 PO.5 (ADS)
P1.7 8 8031) 33 P06 (AD6)
RST 9 32 PO.7 (AD7)
(RXD) P3.0 10 31 EANPP
(TXD) P3.1 11 30 ALE/PROG
(INTO) P3.2 12 29 PSEN
(INT1) P3.3 13 28 P2.7 (A15)
(TO) P3A 14 27 P2.6 (A14)
(T1) P35 15 26 P25(A13)
(WR) P36 16
25 P2A(A12)
(RD) P3.7 17
24 P2.3 (A11)
XTAL2 18
23 P2.2 (A10)
XTAL1 19
22 P21 (A9)
GND 20
21 P2.0 (A8)

Figure 8-1. 8051 Pin Diagram

218
Examining Figure 8-1 note h' -
aside for the four ports PO P l P2 t at of the 40 pins, a total of 32 pins are set
of the pins are designat d V ' and P3, where each port takes 8 pins. The rest
Of the . . e as co GND, XTALl, XTAL2, RST, EA PSEN and
ALE . esc pins SIX (V GND ' ,
all members of the 805 lee, d ' XTAL 1, XTAL2, RST, and EA) are used by
.. - an 803t
families, In other words, they must be i--C--2------------,
connected In order for the system to I-----....j XTAL2
work, regardless of whether the micro-
controller is of the 8051 or 8031 fami-
ly. The other two pins, PSEN and
o
ALE, are used mainly in 8031-based
...--;11---.-...---1 XTAL 1
systems. We first describe the function
30 pF
of each pin. Ports are discussed sepa-
rately.
+------.....j GND
Vee
Pin 40 provides supply voltage
to the chip. The voltage source is +5Y. ","=:-o-::;-;:::-;-~;;;-;--;::;---,----,-,-J
Figure 8-2 (a). XTAL Connection to 8051
GND
Pin 20 is the ground.
XTAL 1 and XTAL2 NC ------I XTAL2

The 8051 has an on-chip oscil-


lator but requires an external clock to
run it. Most often a quartz crystal EXTERNAL
oscillator is connected to inputs OSCILLATOR ..,.-----1 XTAL 1
XTALI (pin 19) and XTAL2 (pin 18). SIGNAL
The quartz crystal oscillator connected
to XTALI and XTAL2 also needs two
capacitors of 30 pF value. One side of
J.------1 GND

each capacitor is connected to the


ground as shown in Figure 8-2 (a).
It must be noted that there arc Figure 8-2 (b). XTAL Connection to an
various speeds of the 8051 family. External Clock Source
Speed refers to the maximum oscillator
frequency connected to XTAL. For
example, a l2-MHz chip must be connected to a crystal with 12 MHz frequency
or less. Likewise, a 20-MHz microcontroller requires a crystal frequency of no
more than 20 MHz. When the 8051 is connected to a crystal oscillator and is pow-
ered up, we can observe the frequency on the XTAL2 pin using the oscilloscope.
If you decide to use a frequency source other than a crystal oscillator, such
as a TTL oscillator, it will be connected to XTALJ; XTAL2 is left unconnected, as
, shown in Figure 8-2 (b).
RST
Pin 9 is the RESET pin. It is an input and is active high (normally low).
Upon applying a high pulse to this pin, the microcontroller will reset and terminate

CHAPTER 8: 8051 HARWARE CONNECTION AND rNTEL HEX FILE 219


all activities. This is often referred to
as a power-on reset. Activating. a
power-on reset will cause all values In
the registers to be lost. It will set pro-
+
gram counter to all Os.
Figures 8-3 (a) and (b) show 10 ~F 31 ==--_-,
two ways of connecting the RST pm EANPP
30prFI--L-1-l9 X1
to the power-on reset circuitry. 011.0592 MHz
Figure 8-3 (b) uses a momentary
+-8_.2_K~ f---....L---~18,. X2
switch for reset circuitry. 30pF
In order for the RESET input RST
9
to be effective, it must have a mini-
mum duration of two machine cycles.
In other words, the high pulse must be
high for a minimum of two machine
cycles before it is allowed to go low.
Here is what the Intel manual says
about the Reset circuitry; "When . .
power is turned on, the circuit holds Figure 8-3 (a). Power-On RESET Circuit
thc RST pin high for an amount of r-t- ,

time that depends on the capacitor Vee


value and the rate at which it charges.
To ensure a valid reset the RST pin
must be held high long enough to .---+------, 31 EANPP
19
allow the oscillator to start up plus
two machine cycles." Although, an • 10 ~~30 pt-F-O-r--, X 1
8.2K-ohm resistor and a I0-IlF capac-
itor will take care of the vast majority 18
o Jt---~X2
of the cases, you sti II need to check 30pF
the data sheet for the 8051 you arc '----1--------, 9 RST
using.
EA 8.2K

The 8051 family members,


such as the 875 1/52, 89C5 I/52, or '::;-_-;:-;:-:;-;-;;;_--:::--::::;-;=:--:-::- _
OS 8 9C4 x,0 a II come WIith on-e hiip Figure 8-3 (b). MS'
Power-On RESET h with
ROM to store programs, In such omentary wttc
cases, the EA pin is connected to Vcc For family mcmbers such as the 8031 and
8032 in which there is no on-chip ROM, code is stored on an external ROM and
is fetchcd by the 8031/32. Thcreforc, for the 803 I the EA pin must be connected
to GND to indicate that the code is stored externally. EA, which stands for "exter-
nal access," is pin number 3 j in the DIP packages. It is an input pin and must be
conncctcd to either Vee or GND. In other words, it cannot be left unconnccted.
In Chapter 14, we will show how the 8031 uses this pin along with PSEN
to access programs stored in ROM memory located outside the 8031. In 8051
chips with on-chip ROM, such as the 8751/52, 89C51/52, or DS89C4xO, EA is
connccted to Vcr, as we will see in the next section.
.The pins discussed so far must be connected no matter which family mem-
ber IS used. The next two pins are used mainly in 803 J -based systems and are dis-
cussed In more detail in Chapter 14. The following is a brief description of each.
PSEN

This isan output pin. PSEN stands for "program store enable." In an 8031-
based system In which an external ROM holds the program code, this pin is con-
nected to the OE pin of the ROM. See Chapter 14 to see how this is used.
ALE
. ALE (address latch enable) is an output pin and is active high. When con-
necting an 8031 to external memory, port 0 provides both address and data. In
other words, the 8031 multiplexes address and data through port 0 to save pins.
The ALE pin is used for demultiplexing the address and data by connecting to the
G pin of the 74LS373 chip. This is discussed in detail in Chapter 14.
Ports 0, 1,2 and 3
As shown in Figure 8-1 (and discussed in Chapter 4), the four ports PO, PI,
P2, and P3 each use 8 pins, making them 8-bit ports. All the ports upon RESET
are configured as input, since PO- P3 have value FFH on them. The following is
a summary of features of PO - P3 based on the materials in Chapter 4.

PO
As sbown in Figure 8-1, port 0 is also designated as ADO - AD7, allowing
it to be used for botb address and data. When connecting an 80S I/31 to an exter-
nal memory, port 0 provides both address and data. The 80S I multiplexes address
and data through port a to save pins. ALE indicates if PO has address or data.
When ALE = 0, it provides data DO - D7, but when ALE = I it bas address AO -
A 7. Therefore, ALE is used for demuliplexing address and data with the help of a
74LS373 'latch, as we will see in Chapter 14. In the 80Sl-based systems where
there is no external memory connection, tbe pins of POmust be connected exter-
nally to a J OK-ohm pull-up resistor. This is due to the fact that POis an open drain,
unlike PI, P2, and P3. Open drain is a term used for MOS chips in the same way
that open collector is ..----------~---------,
used for TTL chips. In Vce
10 K
many systems using the
8751, 89C51,
DS89C4xO chips, we nor-
or £ ~~~~ ~~~ ~ 3E
mally connect PO to pull-
up resistors. See Figure
PO.Or-:=±=t=t==t==t=~==~
PO.11-
8051/52 M2
"J1
8-4. With cxternal pull- PO.3 ~
0

up resistors connected to PO.4t========::==t=~=~f=


PO.5~
PO.6~ ........--+---t_
PO, it can be used as a
simple I/O port, just like
PO.?
P I and P2. In contrast to
port 0, ports PI, P2, and L_--::--;:--~~;-;;-::-;;=::::::------'
P3 do not need any pull- Figure 8-4. Port 0 with Pull-Up Resistors

CHAPTER 8: 8051 HARWARE CONNECTION AND INTEL HEX FILE 221


up resistors since they already have pull-up resistors internally. Upon reset, ports
PI, P2, and P3 are configured as input ports.

P1 and P2
ln 805 I-based systems with no external memory connection, both P I and
P2 are used as simple I/O. However, in 8031/51-based systems with external
memory connections, port 2 must be used along with PO to provide the l6-bit
address for the external memory. As shown in Figure 8-1, port 2 is also designat-
cd as A8 - A 15, indicating its dual function. Since an 8031/51 is capable of access-
ing 64K bytes of external memory, it needs a path for the 16 bits of the address.
While PO provides the lower 8 bits via AO - A7, it is the job ofP2 to provide bits
A8 - A IS of the address. In other words, when the 803 l/51 is connected to exter-
nal mcmory, P2 is used for the upper 8 bits of the 16-bit address, and it cannot be
used for 110. This is discussed in detail in Chapter 14.
From thc discussion so far, we conclude that in systems based on 8051
microcontrollers, we have three ports, PO, PI, and P2, for I/O operations. This
should be enough for most microeontroller applications. That leaves port 3 for
interrupts as well as other signals, as we will sec next.

Port 3

Port 3 occupies a total of 8 pins, pins 10 through 17. It can be used as input
or output. P3 does not need any pull-up resistors, the same as P J and P2 did not.
Although port 3 is configured as an input POl1 upon reset, this is not the way it is
most commonly used. Port 3 has the additional function of providing some
extremely important signals such as interrupts. Table 8-1 provides these alternate
functions ofP3. This information applies to both 805] and 8031 chips.
P3.0 and P3.! are used for the RxD and TxD serial communications sig-
nals. Sec Chapter 10 to see how they are connected. Bits P3.2 and P3.3 are set
aside for external interrupts, and arc discussed in Chapter II. Bits P3.4 and P3.5
arc used for Timers 0 and ~nd are discussed in Chapter 9. Finally, P3.6 and P3.7
are uscd to provide the WR and RD signals of external memory connections.
Chapter 14 discusses how they are used in 803 I-based systems. In systems based
on the 8051, pms 3.6 and 3.7 are used for I/O while the rest of the pins in port 3
are normally used 111 the alternate function rolc.

Table 8-1: Port 3 Alternate Functions


P3 Bit Function Pin

P3.0 RxD 10
P3.! TxD II
P3.2 INTO 12
P3.3 INTI 13
P3.4 TO 14
P3.5 TI 15
P3.6 WR 16
P3.7 RD 17

222

Program counter value upon reset


Activating a power-on reset will Table 8-2: RESET Value of Some
.cause all values in the registers to be lost. 8051 Registers
Table 8-2 provides a partial list of 8051 reg-
isters and their values after power-on reset. Register Reset Value (hex)
From Table 8-2 wc note that the value of the PC 0000
PC (program counter) is 0 upon reset, forc- DPTR 0000
ing the CPU to fetch the first opcode from ACC 00
ROM memory location 0000. This means PSW 00
that we must place the first byte of opcode SP 07
in ROM location 0 because that is where the B 00
CPU expects to find the first instruction. PO-P3 FF

Machine cycle and crystal frequency


As we discussed in Chapter 3, the 805 I uses one or more machine cycles
to execute an instruction. The period of machine cycle varies among the different
versions of 8051 from 12 clocks in the AT89C51 to 1 clock in the DS89C4xO chip.
See Table 8-3. The frequency of the crystal oscillator connected to the X - X2 pins
dictates the speed of the clock used in the machine cycle. From Table 8-3, we can
conclude that using the same crystal frequency of 12 MHz for both the AT89C5l
and DS89C4xO chips gives performance almost 12 limes better from the
DS89C4xO chip. The
reason wc say "almost" is Table 8-3: Clocks per Machine Cycle (MC) for
that the number of ..::.V::ar:.::io::,:u~·s~8:.::0~5.:.1.:.V.::.er:.::s::;io~n~s~
_
machine cycles it takes to Chip (Maker) Clocks per Machine Cycle
execute an instruction is AT89C51/52 (Atmel) 12
not the same for the P89C54X2 (Phillips) 6
AT89C5l and DS89C4xO DS5000 (Dallas Semiconductor) 4
chips as we discussed in DS89C4xO (Dallas Semiconductor) 1
Chapter 3.

Example 8-1
Find the machine cycle (MC) for the following chips if XTAL = 1J .0592 MHz.
(a) AT89C51 (b) DS89C4xO (c) DS5000

Solution:

1111.0592 MHz = 90.42 nanoseconds (ns)


(a) MC = 12 x 90.42 ns = 1.085 us
(b) MC = J x 90.42 ns = 90.42 us
(c) MC = 4 x 90.42 us = 361.68 ns

CHAPTER 8: 8051 HARWARE CONNECTION AND INTEL HEX FILE 223


Review Questions
I. A given AT89C51 chip has a speed of 16 MHz. What is the range of frequen-
cy that can be applied to the XTALI and XTAL2 pins? .
2. Which pin is used to inform the 8051 that the on-chip ROM contains the pro-
gram?
3. Upon power-up, the program counter (PC) has a value of I'
4. Upon power-up, the 8051 fetches the first opcode from ROM address ocation

5. Which 8051 port needs pull-up resistors to function as an I/O port?

SECTION 8.2: DESIGN AND TEST OF DS89C4xO TRAINER

In this section we show connections for 805 l-based systems using chips
such as the AT89C51 and DS89C4xO. If you decide to wire-wrap one of these,
make sure that you read Appendix B on wire wrapping.
AT89C51/52·based trainer connection
In systems based on an AT89C51/52-type mieroeontroller, you need a
ROM burner to bum your program into the microcontroller. For the AT89C51, the
ROM burner can erase the flash ROM in addition to burning a program into it. In
the case of the 8751, you also need an EPROM erasure tool since it uses UV-
EPROM. To burn the 8751, you need to erase its contents first, which takes
approximately 20 minutes for UV-EPROM. For the AT89C51, this is not required
since it has flash ROM.
Figure 8.5 shows the minimum connection for the 8751 or 89C51-based
system. Notice that "EA=V cc" indicates that an 8751 or 89C51 has on-chip ROM
for the program. Also notice the PO connection to pull-up resistors to ensure the
availability of PO for I/O operations. If you need to use a momentary switch for
RESET, refer to Figure 8-3 (b).
DS89C4xO family

. The DS89C4xO chip from Maxim/Dallas Semiconductor is an 8051 type


IlJIeroeontrolier with on-chip flash ROM. It also has a built-in loader allowing it
to download programs mto the chip via the serial port, therefore eliminating any
need for an external ROM burner. This important feature makes the DS89C4xO
chip an ideal candidate for 805 l-based home development systems ..
DS89C4xO flash ROM
size
Table 8-4: Qn-Chip Flash ROM Size for the
Whi Ie all OS89C4xO DS89C4xO Family from Maxim-Dallas
chips share the same features, Semiconductor. See www.maxim-ic.com
they come with different Chip
amounts of on-chip ROM. On-Chip ROM size (Flash)
OS89C420/30
Table 8-4 shows the on-chip 16K bytes
OS89C440
ROM size for various 32K bytes
OS89C450
OS89C4xo chips. Refer to 64K bytes

224

I
Vee

Vee
:b 10 K

~ 10uF 8751/89C51 . ~ ~ ~ ~ {~~ ~ ~

>
~;:
r-1:
30 pF
1 l ~
I
EANPP
X1
-+-+-+-+--+---1---1_
PO ..........
.0,
'~2 K \ 9110592MHz 19 ~g~I----4~I--+-+-+----+~1- J
P---+--J!----L------JX2 PO.3 ;:l.
30 ~F 18 PO.4 0
PO.5r-------L-+-+_
PO.6r----------..-1-
PO.7r---------~L
P3.0/RXD
P3.1ITXD P2.0
P3.2/lillQ P2.1
P3.3/INT1 P2.2
P3.41T0 P2.3
P3.51T1 P2.4
P25 '
P1.0 P2.6
P1.1 P2.7
P1.2
P1.3
P1.4
P1.5
ALElt~6~
P1.6 P 3,61i'\it{
P1.7 P3.7/RD

Figure 8-5. Minimum Connection for 89CSlIS2-Based Systems

the web site www.maxim-ic.com for further information, Notice that while the
AT89C51 comes with 4K bytes of on-chip ROM, and theAT89C52 comes with 8K
bytes, the DS89C4xO has 16K bytes of on-chip ROM, Also notice that the
DS89C430 is a replacement for the OS89C420 with the bugs fixed.

Example 8-2
Find the address space for the on-chip ROM of the following chips,
(a) AT89C51, (b) AT89C52, and (c) OS89C420/30

Solution:

(a) AT89C51 has 4K bytes of on-chip ROM, That gives us 4 x 1024 = 4,096 bytes,
Converting the 4096 to hex, we get 1000H. Therefore, the address space is 0000 -
OFFFH.
(b) AT89C52 has 8K bytes of on-chip ROM. That gives us 8 x 1024 = 8,192 bytes,
Converting the 8,192 to hex, we get 2000H. Therefore, the address space is 0000 -
IFFFH.
(c) DS89C420/30 has 16K bytes of on-chip ROM, That gives us 16 x 1024 = 16,384
bytes, Converting the 16,384 to hex, we get 4000H. Therefore, the address space is
0000 - 3FFFH.

CHAPTER 8: 8051 HARWARE CONNECTION AND INTEL HEX FILE 225


Key features of the DS89C4xO f the DS89C4xO chip taken
. f the key features 0
The following are some 0 web site (http;//www.maxim-ic.com.) We
from the Maxim-Dallas Semiconductor h to use them in future chapters.
will look at many of these features and show ow

1. 80C52 compatible . t mpatible


(a) 8051 pin- and instruction-se co
(b) Four bidirectional I/O ports
(c) Three 16-bit timer counters
(d) 256 bytes scratch pad RAM
2. On-chip flash memory
(a) 16KB for DS89C420/30
(b) 32KB for DS89C440
(c) 64KB for DS89C450 .
3. In-system programmable through the serial port
1KB SRAM for MOVX
4. ROMSIZE Feature . f 0 t 64K
(a) Selects internal program memory size rom 0
(b) Allows access to entire external memory map
(c) Dynamically adjustable by software
5. High-speed architecture
(a) 1 clock per machine cycle
(b) DC to 33MHz operation
(c) Single-cycle instruction in 30 ns .
(d) Optional variable length MOVX to access fast/slow penpherals
6. Two full-duplex serial ports
7. Programmable watchdog timer
8. 13 interrupt sources (six external)
9. Five levels of interrupt priority
10. Power-fail reset
11. Early warning power-fail interrupt

DS89C4xO trainer connection

We selected the DS89C4xO for an 8051 Trainer because it is inexpensive


but powerful, and one can easily wire-wrap it to be used at work and home. The
connection for the DS89C4xO Trainer is shown in Figure 8-6.
If you decide not to wire-wrap the trainer yourself, you can buy this
DS89C4xO-based Trainer from the www.MicroDigitalEd.com web site.
Using the DS89C4xO for development is more advantageous than using the
8751 or 89C51 system for the following two major reasons.
I. Using the DS89C4xO for an 8051 microcontroller allows us to program the
chip without any need for a ROM burner. Because not everyone has access to
a ROM burner, the DS89C4xO is an ideal home-development systcm. The
advantage of the DS89C4xO is that it can be programmed via the COM port of
a PC (x86 IBM or compatible PC) while it is in the system. Contrast this with
the 89C51 system in which you must remove the chip, program it, and install
it back in the system every time you want to change the program contents of
226
the on-chip ROM. This
89C51 syste resu I'Is In a much longer development time for the
Th m compared with the DS89C4xO system
2, e two senal ports on the DS89C4 0 ' '
with the chi d h. x allow us to use one for PC interfacing
p, an t e other for data acquisition,

+5V

rJ
+5V

0:
<'"
~~4
>- 0 +
10uF vee
2 5
OB·9F

~'" ...,N
" 8.2k

+5V
RST TxD

RxD
a
..
~ 4 ,0 }
1k
I,
1k DS89C4xD
....
10k EA
2N3904
P2.6 ) DPENDR
.5V
PULLED UP
P2.7

:I: l;UN

"'~
1
>-0
~!= 10k PsEN 30pF

2N3904 XTAL1

.~
(J) 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 pro-
gram into the DS89C4xO by setting the switch to V cc. and run the program by set-
ting 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 termi-
nal 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 pro-
gram position.
3. In Windows Accessories, click on HyperTerminaJ. (If you get a modem instal-
lation 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>
_101 xl
---=r..-r~;;;,~"'-----_. . .__

DS89C420 LOADER VERSION 1.0


COPYRIGHT (Ci 2000 DALLAS SEMICONDUCTOR
>

FIgure 8-7. Screen Capture from HyperTerminal for DS89C4xO Trainer "

228
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" com-
mand.
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. At the ">" prompt, enter L (L is for Load). Example: ">L" an~ pr~s~ En~ri
2. In HyperTerminal, click on the Transfer m~,nu option. ,~IIck on en ext I e.
3. Select your file from your disk. Example: C:test.hex h "GGGG " t
4. 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 dump WI gIve you the opcodes and operands
. . of all. the mstrucnons
. m
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 nON AND INTEL HEX FILE 229


CHAPTER 8: 8051 HARWARE CONNEC .
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 in-
between 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 peri-
od instead of the 12 clock periods used by the AT89C51/52 chip.
Trainer Test Program in Assembly
ORG OH
MAIN: 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
Trainer Test Program in C
#include <reg51.h>
void MSDelay(unsigned int);
void main (void)
{
while (I)
{ !/repeat forever
PO:OX55;
PhOX55 r. //send value to port
P2:0x55'r
MSDelay(250) ; Ilcall 250 ms function
PO : OxAA', Iiset value to port
Pl : OxAA',
P2 : OxAA',
MSDelay(250) ; Ilcall 250 ms function

void MSDelay(unsigned int itime)


(
unsigned int i , J'.,
for(i:O;i<itime;i++)
for(j:0;j<1275;j++);
}

DS89C4xO commands
. There are many commands embedded into the DS89C4xO loader. The most
widely used among them are L, K, and D. Here is the summary of their opera-
nons.
L Load standard ASCII Intel hex formatted data into flash memory.
K Erases the entire contents of flash memory. .
D <begin> <end> Dumps the Intel hex file.

We have shown the use of the L (load), K (klean), and D (dump) com-
mands earlier. A complete list of commands and error messages can be obtained
from www.MicroDigitalEd.com.

Some troubleshooting tips


Running the test program on your DS89CxO-based trainer (or 8051 sys-
tem) should toggle all the 1/0 bits with some delay. If your system does not work,
follow these steps to find the problem.
1. With the power off, check your connectionfor all pins, especiaJlyVee and GND.
2. Check RST (pin #9) using an oscilloscope. When the system is powered up,
pin #9 is low. Upon pressing the momentary switch it goes high. Make sure the
momentary switch is connected properly.
3. Observe the XTAL2 pin on the oscilloscope while the power is on. You should
see a crude square wave. This indicates that the crystal oscillator is good.
4. If all the above steps pass inspection, check the contents of the on-chip ROM
starting at memory location 0000. It must be the same as the opcodes provid-
ed by the list file of Figure 8-8. Your assembler produces the list file, which
lists the opcodes and operands on the left side of the assembly instructions.
This must match exactly the contents of your on-chip ROM if the proper steps
were taken in burning and loading the program into the on-chip ROM.

CHAPTER 8: 8051 HARWARE CONNECTION AND INTEL HEX FILE 231


Review Questions
I. True or false. The DS89C4xO is an 8052 chip,
2. Which pin is used for reset?
3. What is the status of the reset pin when it is not activated?
4. What kind of ROM is used in the DS89C4xO chip?
5. The loader for the DS89C4xO works with the (serial, parallel) port.
6. Give two reasons that the DS89C4xO is preferable over 89C51 chips.
7. In the DS89C4xO Trainer, what is the role of the Prog/Run switch?
8, What is the highest frequency that we can connect to the DS89C420/30?
9. True or false. The DS89C4xO can download the file into its ROM only if it is
in Inlei hex file format.
10. Which command is used to erase the contents of ROM in the DS89C4xO chip?
II. Which command is used to load the ROM in the DS89C4xO chip?
12, Which command is used to dump the contents of ROM in the DS89C4xO chip?

SECTION 8.3: EXPLAINING THE INTEL HEX FILE

. Intel hex file is a widely used file format designed to standardize the load-
mg of executable machine codes into a ROM chip. Therefore, loaders that come

LOC OBJ LINE


0000 1 ORG OH
0000 758055 2 MAIN: MOV PO, #55H
0003 759055 3 MOV PI, #55H
0006 75A055 4 MOV P2, #55H
0009 7DFA 5 MOV R5, #250
OOOB lllC 6 ACALL MSDELAY
DODD 7580AA 7 MOV PO, #OAAH
0010 7590AA 8 MOV PI, #OAAH
0013 75AOAA 9 MOV P2, #OAAH
0016 7DFA 10 MOV R5, #250
0018 lllC II
ACALL MSDELAY
OOIA 80E4 12
SJMP MAIN
13 ;--- THE 250 MILLISECOND
DELAY.
14 MSDELAY:
ODIC 7C23 15 HERE3: MOV R4, #35
ODIE 7B4F 16 HERE2: MOV R3,#79
0020 DB FE 17 HERE1: DJNZ R3, HEREI
0022 DCFA 18
0024 DDF6 DJNZ R4 , HERE2
19
0026 22 DJNZ R5 , HERE3
20
RET
21
END
with every ROM burner (programmer) support the Intel hex file format. While in
many newer Wmdows-based assemblers the Intel hex file is produced automati-
cally (by selecting the right setting), in a DOS-based PC you need a utility called
OH (object-to-hex) to produce that. In the DOS environment, the object file is fed
into the linker program to produce the abs file' then the abs file is fed into the OH
utility to create the Intel hex file. While the abs file is used by systems that have a
mont tor program, the hex file is used only by the loader of an EPROM program-
mer to load it into the ROM chip. .

Program list file for test program


The list file for the test program is given in Figure 8-8. The LOC and OBJ
fields in Figure 8-8 must be noted. The location is the address where the opcodes
(object codes) are placed. The LOC and OBJ information is used to create the hex
file. Next, we will analyze the hex file belonging to the list file of Figure 8-8.

Analyzing Intel hex file


Figure 8-9 shows the Intel hex file for the test program whose list file is
given in Figure 8-8. Since the ROM burner (loader) uses the hex file to download
the opcode into ROM, the hex file must provide the following: (I) the number of
bytes of information to be loaded, (2) the information itself, and (3) the, starting
address where the information must be placed. Each line of the hex file consists
of six parts. In Figure 8-9, we have separated the parts to make it easier to ana-
lyze. The following describes each part.
1. ":" Each line starts with a colon.
2. CC, the count byte. This tells the loader how many bytes are in the line. CC
can range from 00 to 16 (10 in hex).
3. AAAA is for the address. This is a 16-bit address. The loader places the first
byte of data into this memory address.
4. TT is for type. This field is either 00 or 0 I. If itis 00, it means that there are
more lines to come after this line. If it is 0 I, it means that this is the last line
and the loading should stop after this line.

: 1000000075805575905575A0557DFA III C7580AA9F


:100010007590AA 75AOAA7DFAI1IC80E47C237B4FO I
:07002000DBFEDCFADDF62235
:OOOOOOOIFF

Seperating the fields we get the following

OOOOOOOOOOODOOOOOOOOOOOOOOOOOOOO 55
:CC AAAA TT 9F
75805575905575A0557DFA111C7580AA
:10 0000 00 01
7590AA75AOAA7DFA111C80E47C237B4F
:10 0010 00 35
DBFEDCFADDF622
:07 0020 00
:00 0000 01 FF

File Test Program as Provided by the Assembler


Figure 8-9. Inte I Hex I

CHAPTER 8: 8051 HARWARE CONNECTION AND INTEL HEX FILE 233


S. 00 ......0 is the real information (data or code). There is a maximum of 16
bytes in this part. The loader places this information into successive memory
locations of ROM.
6. S5 is a single byte. This last bytc is the checksum byte of everything in that
line. The checksum byte is used for error chccking. Checksum bytes are dis-
cusscd in detail in Chapters 6 and 7. Notice that the checksum byte at the end
of each line represents everything in that line and not just the data portion.

ow, compare the data portion of the Intel hex tile in Figure 8-9 with the
informationunder the OBl field of the list file in Figure 8-8. Notice that they are
identical, as they should be. The extra information is added by the Intel hex file
fonnalter. You can run the C language version of the test program and verify its
operation. YourC compiler will provide you both the list tile and the Intel hex file
if you want explore the Intel hex file concept.

Examine the next three examplcs to gain an insight into the Imel hex fil1 e.

Example 8-3
From Figure 8-9, analyze the six parts of line 3.

Solution:

After the colon (') we have 07 hi h


0020H is the address at which ;e t~at:e:~ th% seven bytes of data are in this line.
line of the record. Then the data whi h s a s. ext, 00 means that this is not the last
F622. Finally, the last byte 3S' I'StthCIShsekvenbytes, ISas follows: DB FE DC FA DD
" e c ec sum byte.

Example 8-4
Verifythe
corrupted.checksum byte for line 3 of Fiigure 8-9. Verify also that the information is not

Solution:

07 + 00 + 20 + 00 + OB +
ries (S)gives CB . FE + DC + FA + DD + F6 + 2 -
If we add H, and ItS2's complement is 3 . 2.- 5CBH. Dropping the car-
ries . hall the mfonnation in line 3 incl di SH, which IS the last byte of line 3.
07 +~~ s+ould get 00. ' u mg the checksum byte, and drop the car-
20 + 00 + DB + FE + DC+FA+ DD + F6 + 22 + 35 = 600H

234 -
Example 8-5

Compare the data p,ortion of the Intel hex file of Figure 8-9 with the opcodes in the list
file of the test program given in Figure 8-8. Do they match?

Solution:

In the first line of Figure 8-9, the data portion starts with 75H, the opcode for the instruc-
tion "MOV", as shown in the list file of Figure 8-8. The last byte of the data in line 3 of
Figure 8-9 is 22, which is the opcode for the "RET" instruction in the list file of Figure
8-8.

Review Questions
I. True or false. The Intel hex file uses the checksum byte method to ensure data
integrity.
2. The first byte of a line in the Intel hex file represents __ .
3. The last byte of a line in the Intel hex file represents __ .
4. In the TT field of the Intel hex file, we have 00. What does it indicate?
5. Find the checksum byte for the following values: 22H, 76H, 5FH, 8CH, 99I-1.
6. In Question 5, add all the values and the checksum byte. What do you get?

SUMMARY

. This chapter began by describing the function of each pin of the 8051, The
four ports of the 8051, PO, PI, P2, and P3, each use 8 pins, making them 8-bit
ports. These ports can be used for input or output. Port 0 canbe used for. either
address or data. Port 3 can be used to provide interrupt and serial communication
signals. Then the design of the DS89C4xO-based trainer was shown. We also
explained the Intel hex format.

PROBLEMS

SECTION 8.1: PIN DESCRIPTION OF THE 8051

l. The 8051 DIP package is a __ -pin package.


2. Which pins are assigned to Vee and GND?
the 8051 how many pins are designated as I/O port pins?
3., In 'd
4 The crystal oscillator is connected to pins __ an --'
. . d 25 MHz what is the maximum frequency that can be
5, If an 8051 IS rate as ,
connected to it? . k
6. Indicate the pin number assigned to RST III the DIP pac agc.
7 RST is an '(input, output) pill. . (low, high)
. (low high) and needs a _
8, The RST pin is nonnally ,
signal to be activated.
f h PC (program counter) upon RESET of the 805 I?
9. What are the contents
t e 0

nON AND INTEL HEX FILE 235


CHAPTER 8: 8051 HARWARE CONNEC
re ister upon RESET of the 80S I?
I0 What are the contents of the SP g pon RESET of the 80S I 'I
· fthe A register u d X
II What are the contents 0 . tal frequencies connecte to I
· f
12. Find the machine cycle or eth followmg erys

and X2. (c) 25 MHz (d) 30 MHz


(a) 12 MHz (b) 20 MHz d. (input output) pin.
- an IS an , 89
13. EA stands for . h· ROM such as the 875 I and the C5 I,
14 For 8051 family members WIth on-e ip
· pin -EA is connecte d t 0 __ (Vee '. GND).
15 PSEN is an (input, output) pin.
16: ALE is an (input, output) pm. (80S I 8031)
. . I· In terns based on the ,.
17. ALE ISused main Yd sys t d as PO and what are those in the DIP package?
8 H any pms are esrgna e
I19 . H ow m . are d.esigna te d as PI and what are those .in the DIP package?
w many prns
20 · How0 many pms . are d eSIignated
. as 1'2 and what are those .In the DIP package? k ?
· .
2/. How many pins are eSI d ignated as 1'3 and what arc those In the
. DI I' pac age.
22 U RESET all the bits of ports arc configured as __ (Input, output).
· pon , . d I/O?
23. In the 8051, which port needs a pull-up resistor to be usc. as .
24. Which port of the 8051 does not have any alternate function and can be used
solely for 1/0'1

SECTION 8.2: DESIGN AND TEST OF DS89C4XO TRAINER

25. Write a program to get 8-bit data from PI and send it to ports PO, P2, and P3.
26. Write a program to get 8-bit data from 1'2 and send it to ports PO and PI.
27. In 1'3, which pins are for RxD and TxD?
28. At what memory location does the 8051 wake up upon RESET? What is the
implication of that?
29. Write a program to toggle all the bits of P I and P2 continuously
(a) using AAH and 55H (b) using the CPL instruction.
30. What is the address of the last location of on-chip ROM for the AT89C5 I 'I
31. What is the address of the last location of on-Chip ROM for the DS89C420?
32. What is the address of the last location of on-chip ROM for the D889C440?
33. What is the address of the last location of on-chip ROM for the DS89C450?
34. What is the fastest frequency that DS89C4xO can run on?
35. What is the slowest frequency that DS89C4xO can run on?
36. Calculate the machine cycle time for the OS89C430 ifXTAL = 33 MHz.
37. Before we reprogram the DS89C4xO we must (dump era c) the flash
ROM. . ,

38. True or false. In order to download the hex file into the OS89C4xO, it must be
111 the Intel hex file formal.

39. have.
Give two features of the DS89C4xO that earlier 8051 and 8052 chips do not

40·WAfihterdownloading a program, the OS89C4xO gives the message ">GGGG".


at docs It mean?

236
SECTION 8.3: EXPLAINING THE INTEL HEX FILE

4J. Analyze the six parts of line I of Figure 8-9.


42. Analyze the six parts of line 2 of Figure 8-9.
43. Verify the checksum byte for line I of Figure 8-9 and also verify that the infor-
mation is not corrupted.
44. Verify the checksum byte for line 2 of Figure 8-9 and also verify that the infor-
mation is not corrupted.
45. Reassemble the test program with ORG address of IOOHand analyze the Intel
hex file.
46. Reassemble the test program with ORG address of 300H and compare the Intel
hex file with the results of Problem 45.
47. Write a program to toggle all the bits of P 1 and P2 continuously with no delay
and analyze the Intel hex file.

ANSWERS TO REVIEW QUESTIONS


SECTION 8.1: PlN DESCRIPTION OF THE 8051

I. From 0 to 16 MHz, but no more than 16 MHz


2. EA
3. PC = 0000
4. 0000
5. Port 0

SECTfON 8.2: DESIGN AND TEST OF DS89C4XO TRAINER

I. True
2. Pin 9
3. Low
4. Flash
5. Serial .
6. a) It comes with a loader inside the chip and b) it has t~o serial ports
7. ,. The SWallows to load the program or to run It.
8. 33 MHz
9. True
10. >K
II. >L
f2. >D

SECTION 8.2: EXPLAINING INTEL THE HEX FILE

l. True .
2. The number of bytes of data in the line
3. Checksum byte . d there are more lines or data to be followed.
4. 00 means this IS not the last line ""21CH D pping the carries we have ICH and its 2's cam-
S. 22H + 76H + 5FH + 8CH + 99H - . ro
plement is E4H. E4 = 300H. Dropping the carries we have 00, which means
6. 22H + 76H + 5FH + 8CH + 99H +
data is not corrupted.

. eTlON AND INTEL HEX FILE 237


CHAPTER 8: 8051 HARWARE CONNE
-
CHAPTER 9

8051 TIMER
PROGRAMMING
IN ASSEMBLY AND C

OBJECTIVES

UpOD completion of this chapter; you will be able to:

» List the timers of the 8051 and their associated registers


» Describe the various modes of the 8051 timers
» Program the 8051 timers in Assembly and C to generate time delays
» Program the 8051 counters in Assembly and C as event counters

239
, / t s They can be used either as timers to
The 8051 has two timers eoun e~u'ntevents happening outside the micro.
, delay or as counters to c ,
generate a time h these timers arc used to generate time delays,
Scetion 9 I we see ow ,
contro IIer, In ' h used as event counters. In Section 9.3 we
In Section 9.2 we show how t eyare
usc C language to program the 8051 timers.

SECTION 9.1: PROGRAMMING 8051 TIMERS

The 8051 has two timers: Timer 0 and Timer I. They can be ,used either as
.umcrs or as event cu.
a nters In this section we first discuss
. the timers registers and
then show how to program the timers to generate time delays.

Basic registers of the timer


Both Timer 0 and Timer I are 16 bits wide. Since the 8051 has an 8-bit
architecture, cach 16-bit timer is accessed as two separate registers of low byte and
high byte. Each timer is discussed separately.

Timer 0 registers
The 16-bit register ofTimer 0 is accessed as low byte and high byte. The
low byte register is called TLO (Timer 0 low byte) and the high byte register is
referred to as THO (Timer 0 high byte). These registers can be accessed like any
other register, such as A, B, RO, RI, R2, etc. For example, the instruction "MOV
TLO, #4FH" moves the value 4FH into TLO, the low byte ofTimer O. These reg-
isters can also be read like any other register. For example, "MOV R5, THO" saves
THO(high byte ofTimer 0) in R5.

r----- THO TLO

Figure 9-1. Timer 0 Registers

Timer 1 registers
Timer I is also 16 bits a d it 16 bi . ,
to as TLI (1' . I I b ,n IS - It register IS split into two bytes referred
imer ow ytc) and THI (1' I hi h b '
accessible in the same he reci imcr Ig yte). These registers are
way as t e registers of Timer O.

THI

Figure 9-2. Timer I Registers

240
TMOD (timer mode) register
Both timers 0 and I use the ' '
timer operation mode TMOD te same register, called TMOD, to set the various
set aside for Timer 0 s. d h IS an 8-bll register in which the lower 4 bits are
bits are used to set thant' t e upper 4 bits for Timer I, In each case, the lower 2
, elmer mode and th 2 b' ,
These options are disc d e upper Its to spec] fy the operation,
usse next.

(MSB)
(L S B)
GATE I CIT I MI I MO GATE I CIT I MI T MO
Timer 1 Timer 0

GATE Gating control when s t Th 'I ' enabled only while the \NTx pin
, hi he, e timer count,er IS
ISh ig and the TRx can t to I PI~
' ISset
. When cleared, Ihe timer is enabled
w enever the TRx control bit is set
CIT Timer or counter selected cleared for timer operation (input from internal
system clock), Set for counter operation (input from Tx input pin)
Ml Mode bit I '
MO Mode bit 0

MI MO Mode ~Q~p,;:er~a~tin~g;.lM=odlJ;e~ _
o 0 0 l3-bit timer mode
8-bit timer/counter THx with TLx as 5-bil prescaler
o 16-bit timer mode
16-bit timerlcounters THx and TLx are cascaded; there is
no prescaler
o 2 8-bit auto reload
8-bit auto reload timer/counter; THx holds a value that is
to be reloaded into TLx each time it overflows.
3 Split timer mode '
Figure 9-3. TMOD Register

M1, MO
MO and Ml select the timer mode, As shown in Figure 9-3, there arc three
modes: 0, I, and 2, Mode 0 is a 13-bit timer, mode I is a 16-bit timer, and mode 2
is an 8-bit timer. We will concentrate on modes I and 2 since they arc the ones
used most widely, We will soon describe the characteristics of these modes, after
describing the rest ofthe TMOD register.

CIT (clock/timer)
This bit in the TMOD register is used to decide whether the timer is used
as a delay generator or an event counter, If CIT = 0, it is used as a timer for time
delay generation, The clock source for the time delay is the crystal frequency of
the 805 L This section is concerned with this choice, The timer's use as an event
counter is discussed in the next section,

CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C 241


Example 9-1
Indicate which mode and which timer are selected for each of the following.
(a) MOV TMOD,#OlH (b)MOV TMOD,#20H (c) MOV TMOD,#12H

Solution:

We convert the values from hex to binary. from Figure 9-3 we have:

0 is selected.
(a) TMOD = 00000001, mode 1 of Timer
(b) TMOD = 00100000, mode 2 of Timer
1 is selected.
(c) TMOD = 00010010, mode 2 of Timer
0, and mode 1 of
Timer 1 are selected.

Clock source for timer


As you know, every timer needs a clock pulse to tick. What is the source
of the clock pulse for the 8051 timers? If CIT = 0, the crystal frequency attached
to the 8051 is the source of the clock for the timer. This means that the size of the
crystal frequency attached to the 8051 also decides the speed at whieh the 8051
timer ticks. The frequency for the timer is always 1/12th the frequency of the crys-
tal attached to the 8051. See Example 9-2.
Example 9-2
Find the timer's clock frequency and its period for various 805 I-based systems, with the
following crystal frequencies.
(a) 12 MHz
(b) 16 MHz
(c) 11.0592 MHz

Solution:

XTAL -i- 12
oscillator

(a)1/12 X 12 MHz = 1 MHz and T = 1/1 MHz = 1 ~s


(b)1/12 X 16 MHz =
1.333 MHz and T = 1/1.333 MHz = .75 ~s
(c) 1/12 X 11 05
T _ . 92 MHz = 921.6 kHz·
- 1/921.6 kHz = 1.085 ~s

NOTE THAT 8051 TIMERS SE


REGARDLESS OF MACHINUE 1112 OF XTAL FREQUENCY,
CYCLE TIME.
242

d
Although various 8051-based systems have an XTAL frequency of 10
MHz to 40 MHz, we will concentrate on the XTAL frequency of 11.0592 MHz.
The reason behind such an odd number has to do with the baud rate for serial com-
munication of the 8051. XTAL = 11.0592 MHz allows the 8051 system to com-
municate with the IBM PC with no errors, as we will see in Chapter 10.
GATE

The other bit of the TMOD register is the GATE bit. Notice in the TMOD
register of Figure 9-3 that both Timers 0 and 1 have the GATE bit. What is its pur-
pose? Every timer has a means of starting and stopping. Some timers do this by
software, some by hardware, and some have both software and hardware controls.
The timers in the 8051 have both. The start and stop of the timer are controlled by
way of software by the TR (timer start) bits TRO and TR1. This is achieved by the
instructions "SETS TRl" and "CLR TRl" for Timer I, and "SETS TRO" and
"CLR TRO" for Timer O. The SETB instruction starts it, and it is stopped by the
CLR instruction. These instructions start and stop the timers as long as GATE =
o in the TMOD register. The hardware way of starting and stopping the timer by
an external source is achieved by making GATE = 1 in the TMOD register.
However, to avoid further confusion for now, we will make GATE = 0, meaning
that no external hardware is needed to start and stop the timers. In using software
to start and stop the timer where GATE = 0, all we need are the instructions "SETS
TRx" and "CLR TRx". The use of external hardware to stop or start the timer is
discussed in Chapter 1I when interrupts are discussed.

Example 9-3
Find the value for TMOD if we want to program Timer 0 in mode 2, use 8051 XTAL
for the clock source, and use instructions to start and stop the timer.

Solution:

TMOD= 0000 0010 Timer 0, mode 2,


CIT = 0 to use XTAL clock source, and
gate = 0 to use internal (software)
start and stop method.
Now that we have this basic understanding of the role of the TMOD regis-
ter we will look at the timer's modes and how they are programmed tO crfeahtca
. ' dId 2 are so widely used, we descnbe eac h0 t em
time delay. Because mo es an
in detail.
Mode 1 programming
.' h haracteristics and operations of mode I:
The following are t e c . I f 0000 to FFFFH to be loaded
1. It is a 16-bit timer; therefore, It allows va ues 0
. h t' r's registers TL and TH.
into t e ime laded with a 16-bit initial value, the timer must be start-
2. After TH and TL are 0 "T' 0 d "SETB TRl" for Timer I.
. . d b "SETS TRO for imer an .
ed. This IS one Y . t t count up. It counts up until it reaches Its
3. After the timer ISstarted, It star s 0
243
MING IN ASSEMBLY AND C
CHAPTER 9: 8051 TIMER PROGRAM
FFFFH to 0000, it sets high a flag bit
I· it of FFFFH. When it rolls overfrom b onitored. When this timer flag
1m1 Thi t' er flag can em. .
ea lied TF (timer flag).
. IS un
Id be to stop the timer with the mstructions
. .
I'S raised one option wou . 0 and Timer I respectively. Again, It
' 1" for Timer ,
"CLR TRO"or "CLRh tiTR has '. Its own tuner
'flag' . TFOfor Timer 0, and TF I for
must be notedthat eae timer
Timer J.

. . limit
hes Us ., and ro lis. over , in order to repeat the process
d TF
4. After the timer reae L t be reloaded with the original value, an must
the registers TH and T mus
be reset to O.

.JL.JL

L-
XTAL
oscillator
_
1--/ +12
I I
~

TF goes high overflow


el'f =0 TR when FFFF--O flag

Steps to program in mode 1


To generate a time delay, using the timer's mode I, the following steps are
taken. To clarify these steps, see Example 9-4. '.
°
I. Load the TMOD value register indicating which timer (Timer or Tuner I) IS
to be used and which timer mode (0 or I) is selected.
2. Load registers TL and TH with initial count values.
3. Start the timer.
4. Keep monitoring the timer flag (TF) with the "JNB TFx, target" instruc-
tion to sec ifit is raised. Get out of the loop when TF becomes high.
5. Stop the timer.
6. Clear the TF flag for the next round.
7. Go back to Step 2 to load TH and TL again.
To calculate the exact time delay and the square wave frequency generat-
ed on pin P1.5, we need to know the XTAL frequency. Sec Example 9-5.
From Example 9-6 we can develop a formula for delay calculations using
mode I (I6-bit) of the timer for a crystal frequency of XTAL = 11.0592 MHz.
This is given in Figure 9-4. The scientific calculator in the Accessories directory
of Microsoft Windows can help you to find the HI, TL values. This calculator
supports decimal, hex, and binary calculations.
(a) in hex
(b) in decimal
(FFFF - YYXX + 1) x 1.085 MS
where YYXX are TH, TL initial Convert YYXX values of the
values respectively. Notice TH,TL register to decimal to
that values YYXX are in hex. get a NNNNN decimal number,
then (65536 - NNNNN) x 1. 085 MS
Figure 9-4. Timer Delay Calculation for XTAL _ 11.0592 MHz

244
Example 9-4

In the following program we .


. ., .we are creating a square wave of 50% duty cycle (with equal
portions high and low) on the Pl 5 bi T' .
. It. imer 0 IS used to generate the time delay
Analyze the program. .

MOV TMOD,#01 ;Timer 0, mode 1(16-bit mode)


HERE: MOV TLO,#OF2H ;TLO = F2H, the Low byte
MOV THO,#0 FFH ;THO = FFH, the High byte
CPL Pl. 5
; toggle Pl.5
ACALL DELAY
SJMP HERE ;load TH, TL again
--------,delay using Timer 0
DELAY:
SETB TRO ; start Timer 0
AGAIN: JNB TFO, AGAIN ;monitor Timer 0 flag until
i it rolls over
CLR TRO ;stop Timer 0
CLR TFO ;clear Timer 0 flag .
RET

Solution:

In the above program notice the following steps.

1. TMOD is loaded.
2. FFF2H is loaded into THO - TLO:
3. Pl.5 is toggled for the high and low portions of the pulse.
4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, Timer 0 is started by the "SETB TRO" instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal
oscillator. As the timer counts up, it goes through the states of FFF3, FFF4, FFF5,
FFF6, FFF7, FFF8, FFF9, FFFA, FFFB, and so on until it reaches FFFFH. One more
clock rolls it to 0, raising the timer flag (TFO = I). At that point, the JNB instruction
falls through.
7. Timer 0 is stopped by the instruction "CLR TRO". The DELAY subroutine ends,
and the process is repeated.

Notice that to repeat the process, we must reload the TLand TH registers and start the
timer again.

8--®-8······························~
TF = 0 TF = 0 TF = 0 TF = 0 TF = I

245
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C
Example 9-5
amount of time delay in the DELAY subroutine generat.
In Examp Ie 9-4 ,ca Icu Ia te the
cd by the timer. Assume that XTAL ~ 11.0592 MHz.

Solution:

The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we
have 11.0592 MHz / 12 ~ 921.6 kHz as the timer frequency. As a result, each clock has
a period ofT ~ 1/921.6 kHz ~ 1.085 I1S. In other words, Timer 0 counts up each 1.085
I1S resulting in delay ~ number of counts x 1.085 I1S.
The number of counts for the rollover is FFFFH - FFF2H ~ ODH (13 decimal).
However, we add one to 13 because of the extra clock needed when it rolls over from
FFFF to 0 and raises the TF flag. This gives 14 x 1.085 I1S ~ 15.19 I1S for half the pulse.
For the entire period T ~ 2 x 15.I 9 115 ~ 30.38 I1S gives us the time delay generated by
the timer.

Example 9-6
In Example 9-5, calculate the frequency of the square wave generated on pin P1.5.

Solution:

In the time delay calculation of Example 9-5, we did not include the overhead due to
instructions in the loop. To get a more accurate timing, we need to add clock cycles due
to the instrucnons In the loop. To do that, we use the machine cycles from Table A-I in
Appendix A, as shown below.

Cycles
HERE: TLO, #OF2H
MOV 2
MOV THO,#OFFH 2
CPL PI.5 1
ACALL DELAY
2
SJMP HERE 2
;--------~delay using Timer 0
DELAY:
SETB TRO
AGAIN: 1
JNB TFO ,AGAIN
14
CLR TRO
1
CLR TFO
1
RET
L
Total 28
T ~ 2 x 28 x 1.085 I1S = 60.76 us and
.. F = 16458.2 Hz.
NOTE THAT 8051 TIME
REGARDLESS OF MAC~SINUESE 1112 OF XTAL FREQUENCY,
CYCLE TIME.
246
Example 9-7
Find . the delay generated . b ot h 0f t he met ha d s
. by Timer 0 in the foil'owmg co d e, usmg
of Figure 9-4. Do not Include the overhead due to instructions.

CLR P2.3 ;clear P2.3


MOV TMOD,#Ol ;Timer 0, mode 1(16-bit mode)
HERE: MOV TLO,#3EH ;TLO = 3EH, Low byte ,

MOV THO,#OBBH ;THO = BBH, High byte


SETB P2.3 ;SET high P2.3

AGAIN:
SETB
JNB
TRO
TFO,AGAIN
!; start Timer
;monitor Timer 0 flag
°
CLR TRO ;stop Timer °
CLR TFO ;clear Timer
;next round
°
flag for

CLR P2.3

Solution:

(a) (FFFF - B83E + I) ~ 47C2H ~ 18370 in decimal and 18370 x 1.085 J.1S ~ 19.93145
ms.
(b) Since TH - TL ~ B83EH ~ 47166 (in decimal) we have 65536 - 47166 = 18370.
This means that the timer counts from B83EH to FFFFH. This plus rolling over to
o goes through a total of 18370 clock cycles, where each clock is 1.085 J.1S in dura-
tion. Therefore, we have 18370 x 1.085 J.1S ~ 19.93145 ms as the width ofthe pulse.

Example 9-8
Modify TL and TH in Example 9-7 to get the largest time delay possible. Find the delay
in ms. In your calculation, exclude the overhead due to the instructions in the loop.

Solution:
To get the largest delay we make TL and TH both O. This will count up [Tom 0000 to
FFFFH and then roll over to zero.

CLR P2.3 ;clear P2.3


MOV TMOD,#Ol ;Timer 0, mode 1(16-bit mode)
HERE: MOV TLO, #0 ;TLO = 0, Low byte
MOV THO,#O ;THO = 0, High byte
;SET P2. 3 high
SETB
SETB
P2.3
TRO ;start Timer °
;monitor Timer 0 flag
AGAIN: JNB TFO, AGAIN
;stop Timer 0
CLR
CLR
TRO
TFO ;clear Timer °
flag
CLR P2. 3
Making TH and TL both zero means that the timer will count from 0000 to FFFFH, and
. h TF fl g As a result it goes through a total of 65536 states.
th en roll over to raise tea. '~71 1065 ms.
Therefore, we have delay = (65536 - 0) x 1.085 J.1S .

247
CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C
Example 9-9 ave on pin P I 5 continuously using Timer 1
The following program generates a squ~r~: square wave if XTAL = 11.0592 MHz. In
for a lime delay. Find the frequ~ncy 0 h ad due to instructions in the loop.
your calculation do not include t e over e

TMOD,#10H ·Timer 1, mode 1(16-bit)


MOV
TL1,#34H :TLI
, ; 34H, Low byte
AGAIN: MOV
MOV TH1,#76H ,'THI ; 76H, High byte
; (7634H ; timer value)
SETB TRI ;start Timer I
BACK: JNB TFI,BACK ;stay until timer rolls over
CLR TRI ;stop Timer I
CPL PI. S ;comp. PI.S to get hi, 10
CLR TFI ;clear Timer I flag
SJMP AGAIN ;reload timer since Mode I
;is not auto-reload

Solution:

In the above program notice the target of SIMP. In mode I, the program must reload the
TH, TL register every time if we want to have a continuous wave. Now the calculation.
Since FFFFH - 7634H = 89CBH + I = 89CCH and 89CCH = 35276 clock count.
35276 x 1.085 us = 38.274 ms for half of the square wave. The entire square wave
length is 38.274 x 2 = 76.548 ms and has a frequency = 13,064 Hz.

Also notice that the high and low portions of the square wave pulse are equal. In the
above calculation, the overhead due to all the instructions in the loop is not included.

In Examples 9-7 and 9-8, we did not reload TH and TL since it was a sin-
gle pulse. Look at Example 9-9 to sec how the reloading works in mode I.
Finding values to be loaded into the timer
. Assuming that we know the amount of timer delay we need, the question
IS how to find the values needed for the TH, TL registers. To calculate the values
to be loaded into the TL and TH registers look at Example 9-10 where we usc crys-
tal frequency of 11.0592 MHz for the 8051 system.

, Assuming XTAL = 11.0592 MHz from Example 9-10 we can use the fol-
lowmg steps for findmg the TH, TL registers' values.

I, Divide the desired time delay by 1.085 us.


2. Perform 65536 - n, where n is the decimal value we got in Step I
3. Convert the result of Step 2 t h h " ,. .
loaded int the ti , . a ex, were yyxx IS the initial hex value to be
a e timer s registers.
4, Set TL = xx and TH = yy,

248
-
CI
Assume that XTAL - 11.0592 MHz, What value do we need to load into the timer's reg-
isters if we want to have a time delay of 5 ms (milliseconds)? Show the program for
Timer 0 to create a pulse width of 5 ms on P2,),

Solution:

Since XTAL = 11,0592 MHz, the counter counts up every I ,085 ~,S, This means that out
of many 1.085 us intervals we must make a 5 ms pulse, To get that, we divide one by
the other, We need 5 rns /1,085 ILS= 4608 clocks, To achieve that we need to load into
TL and TH the value 65536 - 4608 = 60928 = EEOOH,Therefore, we have TH = EE and
TL= 00,
CLR P2,3 ;clear P2,3
MOV TMOD,#Ol ;Timer 0, mode 1 116-bit mode)
HERE: MOV TLO,#O ,TLO = 0, Low byte
MOV THO,#OEEH ;THO = EE( hex), High byte
SETB P2,3 ,SET P2, 3 high
SETB TRO ,start Timer °
AGAIN: JNB TFO,AGAIN ,monitor Timer °
flag
;until it rolls over
CLR P2.3 ;clear P2,3
CLR TRO ;stop Timer °
CLR TFO ;clear Timer °
flag

Example 9-11
Assuming that XTAL = 11.0592 MHz, write a program to generate a square wave of 2
kHz frequency on pin P1.5.

Solution: ,
This is similar to Example 9-10, except that we must toggle the bit ,to generate the
square wave. Look at the following steps,
(a) T = 1 / f= 1/2 kHz = 500 us the period of the square wave,
(b) 112 of it for the high and low portions of the pulse IS250 ILS, ,
(c) 250 ILS/ 1,085 ILs= 230 and 65536 - ,230 = 65306, which in hex IS FF lAI-!,
(d) TL = IAH and TI-!= FFH, all in hex, The program ISas follows,

MOV TMOD,#lOH ;Timer 1, mode 1 (16-bit)


AGAIN: MOV TLl,#lAH ;TLl=lAH, Low byte
MOV THl,#OFFH ,THl=FFH, High byte
SETB TRI ;start Timer 1
BACK: JNB TFl,BACK ;stay until timer rolls over
CLR TRI ;stop Timer 1
CPL PI.5 ;complement PI.5 to get hi , 10
CLR TFI i clear Timer 1 flag
SJMP AGAIN ;reload timer since mode 1
jis not auto-reload

249
CHAPTER 9: 8051 TIMER PROGRAMMIN G IN ASSEMBLY AND C
Example 9-12 . m to generate a square wave of 50 Hz
. XTA1 ~ J 1.0592 MHz, wnte a progra
AssumIng
frequency on pin P2.3.

Solution:

Look at the following step\ . d of the square wave.


(a) T ~ I 150 Hz ~ 20 ms, t e pen:rtions of the pulse = 10 ms . . . .
(b) 1/2 of it for the high and low p65536 _ 9216 = 56320 in decimal, and In hex It IS
(c) 10 ms / 1.085 /IS ~ 9216 and
DCOOH.
(d) TL ~ 00 and TH ~ DC (hex)

The program follows.

MOV TMOD,#IOH ;Timer 1, mode 1 (IG-bit)


AGAIN: MOV TLl,#OO ;TLI = 00, Low byte
MOV THI,#ODCH ;THI = DCH, High byte
SETB TRI .start Timer 1
BACK: JNB TFl,BACK ;stay until timer rolls over
CLR TRI ;stop Timer 1
CPL P2.3 ;comp. P2.3 to get hi, 10
CLR TFI ,·clear Timer 1 flag
SJMP AGAIN ,·reload timer since mode 1
;is not auto-reload

Generating a large time delay


As we have seen in the examples so far, the size of the time delay depends
on two factors, (a) the crystal frequency, and (h) the timer's 16-bit register in mode
I. Both of these factors are beyond the control of the 8051 programmer. We saw
earlier that the largest time delay is achieved by making both TH and TL zero.
What if that is not enough? Example 9-13 shows how to achieve large time delays.
Using Windows calculator to find TH, TL
The scientific calculator in Microsoft Windows is a handy and easy-to-use
tool to find the TH, TL values. Assume that we would like to find the TH, TL val-
ues calculation.
the for a time delay that uses 35,000 clocks of 1.085 us. The following steps show

I. ~ring up the scientific calCUlatorin MS Windows and select decimal.


2. Enter 35,000.
3. Select hex. This converts 35,000 to hex, which is 88B8H.
4. Select +/- to give -35000 decimal (7748H).
5. The lowest two digit (48) f hi h
are c:lor TH. We igno·SotII h F. IS ex value are for TL and the next .two (77)
re ate s on the left SInce our number is l S-bit data.
250
Example 9-13
Examine the following
'. program and find th e tiline d e I'ay In secon ds. Exclude the over-
head due to the mstruclIons in the loop.

MOV TMOD,#lOH ;Timer 1, mode 1(16-bit)


MOV R3,#200 ;counter for multiple delay
AGAIN: MOV TLl,#08H ;TLI ~ 08, Low byte
MOV THl,#OlH ;THI ~ 01, High byte
SETB TRI ;start Timer 1
BACK: JNB TFl,BACK ;stay until timer rolls over
CLR TRI ;stop Timer 1
CLR TFI ;clear Timer 1 flag
DJNZ R3,AGAIN ;if R3 not zero then
;reload timer

Solution:

TH - TL = 0 108H = 264 in decimal and 65536 - 264 = 65272. Now 65272 x 1.085 us
=70.820 ms, and for 200 of them we have 200 x 70.820 ms = 14.164024 seconds.

Mode 0
Mode 0 is exactly like mode I except that it is a 13-bit timer instead of 16-
bit. The 13-bit counter can hold values between 0000 to I FFFH in TH - TL.
Therefore, when the timer reaches its maximum of IFFH, it rolls over to 0000 , and
.

TF is raised.

Mode 2 programming
The following are the characteristics and operations of mode 2.
J.It is an 8-bit timer; therefore, it allows only values of 00 to FFH to be loaded
into the timer's register TH.
2. After TH is loaded with the 8-bit value, the 8051 gives a copy of it to TL. Then
the timer must be started. This is done by the instruction "SETB TRO" for
Timer a and "SETB TRI" for Timer I. This isjust like mode I.
3. After the timer is started, it starts to count up by incrementing the TL register.
It counts up until it reaches its limit of FFH. When it rolls over from FFH to
00, it sets high the TF (timer flag). If we are using Timer 0, TFO goes high; if
we are using Timer I, TFI is raised.

.rt.rt
XTAL
~I T~.overnow
+ 12
oscillator
·1 I TR
I ru ]
reload TF ;:: high
when FF .....O
cif=o

CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C 251


4. When the TL register rolls from FFH to 0 and IF is set to I, TL is reloaded
automatically with the original value kept by the TH register. To repeat the
process, we must simply clear TF and let it go without any need by the pro-
grammer to reload the original value. This makes mode 2 an auto-reload, in
contrast with mode I in which the programmer has to reload TH and TL.
It must be emphasized that mode 2 is an 8-bit timer. However, it has an
auto-reloading capability. In auto-reload, TH is loaded with the initial count and
a copy of it is given to TL. This reloading leaves TH unchanged, still holding a
copy of the original value. This mode has many applications, including setting the
baud rate in serial communication, as we will sec in Chapter 10.

Steps to program in mode 2


To generate a time delay using the timer's mode 2, take the following steps.
I. Load rhe TMOD value register indicating which timer (Timer 0 or Timer I) is
to be used, and select the timer mode (mode 2).
2. Load the TH registers with the initial count value.
3. Start the timer.
4. Keep monitoring the timer flag (TF) with the "JNB TFx, target" instruc-
non to see whether it is raised. Get out of the loop when TF goes high.
5. Clear the TF flag.
6. Go back to Step 4, since mode 2 is auto-reload,
. Example 9-14 illustrates these points. To achieve a larger delay, we can usc
multiple registers as shown in Example 9-15.

Example 9-14
Assuming that XTAL = II 0592 MH f d
ated on pin PI 0 in the [,0110'
wi z, m (a) the frequency of the square wave gener-
. . mg program and (b) th II t: ..
this program, and the TH value to do that. e sma est rrequency achievable 111

MOV TMOD,#2DH
MOV THl,#5 ;Tl/mode 2/S-bit/auto-reload
SETB TRI ; THI = 5
BACK: JNB TFl,BACK ;start Timer 1
CPL Pl.D ;stay until timer rolls over
CLR TFl .comp . Pl.O to get hi, 10
SJMP BACK ;clear Timer 1 flag
Solution: rmcde 2 is auto-reload
(a) First notice the target address of SIMP In m
It IS auto~reload. Now (256.05)
0de
X'I 085 _2 we do not need to reload TH since
high portion of the pulse. Since it is a 500/, du - 251 x I .085 us = 272.33 us is the
twice that; as a result T = 2 x 272 33 s _0 uty cycle square wave, the period T is
(b) ~z. . u .. 544.67 us and the frequency = 1.83597
o get the smallest frequency
= 00 In th ' we need the lar t T
= I 8' kH at case, we have T = 2 x 256 I ges and that is achieved when TH
. z. x .085 us -- 555 .52 ~s and the frequency

252
-
Example 9-15
Find the frequency of a square wave generated on pin P j .0.

Solution:

MOV TMOD, #2H ,Timer 0, mode 2


; (8-bit, auto-reload)
MOV THO,#O ;THO=O
AGAIN: MOV R5,#250 ;count for multiple delay
ACALL DELAY
CPL PI. 0 ;toggle Pl. 0
SJMP AGAIN ,repeat
DELAY: SETB TRO ;start Timer 0
BACK: JNB TFO, BACK ;stay until timer rolls over
CLR TRO ;stop Timer 0
CLR TFO ;clear TF for next round
DJNZ R5, DELAY
RET

T = 2 (250 x 256 x 1.085 us) = 138.88 ms, and frequency = 72 Hz.

Example 9-16
Assuming that we are programming the timers for mode 2, find the value (in hex) loaded
into TH for each of the following cases.

(a) MOV TH1,#-200 (b) MOV THO,#-60


(c) MOV TH1,#-3 (d) MOV TH1,#-12
(e) MOV THO,#-48

Solution:

You can use the Windows scientific calculator to verify the results provided by the
assembler. In Windows calculator, select decimal and enter 200. Then select hex, then
+/- to get the TH value. Remember that we only use the-right two digits and ignore the
rest since our data is an 8-bit data. The following is what we get.

Decimal 2's complement (TH value)


-200 38H
-60 C4H
-3 FDH
-J2 F4H
-48 DOH

CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C 253


Assemblers and negative values
' " 8-b ,t 'n mode 2, we can let the assembler calculate
, the
SII1CCthe timer IS , inI "MOV
I THl,
# -,
100" the assembler will calculate
.
value for TH. For example, 9C' h This makes our job easier.
the -I 00 ~ 9C, and makes THI ~ In ex.

Find (a) the frequency 0 f thee squar wave generated In the following code, and (b) the
duty cycle of this wave,

MOV TMOD,#2H 'Timer 0, mode 2


; (a-bit, auto-reload)
MOV THO,#-150 ;THO = 6AH = 2's camp of -150
AGAIN: SETB PI.3 ; PI, 3 = 1
ACALL DELAY
ACALL DELAY
CLR PI. 3 ; PI. 3 0
ACALL DELAY
SJMP AGAIN
DELAY:
SETB TRO ; start Timer 0
BACK: JNB TFO,BACK ;stay until timer rolls over
CLR TRO ; stop Timer 0
CLR TFO ,'clear TF for next round
RET

Solution:

For the TH value in mode 2, the conversion is done by the assembler as long as we enter
a negative number. This also makes the calculation easy. Since we are using 150
clocks, we have time for the DELAY subroutine = 150 x 1.085 ~s = 162 us, The high
portion of the pulse is twice that of the low portion (66% duty cycle). Therefore, we
have: T ~ high portion + low portion = 325.5 us + 162.25 us = 488.25 us and frequen-
ey = 2.048 kHz.

Notice that in many of the time delay calculations we have ignored the
clocks caused by the overhead instructions in the loop. To get a more accurate
umc delay, and hence frequcncy, you need to include them, ] f you use a digital
scope and you don't get exactly the same frequency as the one we have calculat-
ed, It ISbecause of the overhead associated with rhos . t . .
I hi . e InS ructions.
n uns section, we used the 8051 timer for time delay generation.
However, a more powerful and c ti f h '
, . rea ivc use 0 t esc tlmcrs is to use them as event
counters. We diSCUSSthis use of the counter next.

254
-
Review Questions
I. How many timers do we have in the 8051?
2. Each timer has __ registers that are bits wide.
3. TMOD register is a(n) _-bit register. -
4. True or false. The TMOD register is a bit-addressable register.
5. Indicate the selection made in the instruction "MOV TMOD, #2 OH".
6. In mode J, the counter rolls over when it goes from to .
7. In mode 2, the counter rolls over when it goes from --to --.
8. In the instruction "MOV TH1, # - 2 00", find the hex value for the TH register.
9. To get a 2-ms delay, what number should be loaded into TH, TL using mode
I? Assume that XTAL = 11,0592 MHz. '
10. To get a IOO-~sdelay, what number should be loaded into the TH register using
mode 2? Assume XTAL = I J .0592 MHz.

SECTION 9.2: COUNTER PROGRAMMING

In the last section we used the timerlcounter of the 8051 to generate time
delays. These timers can also be used as counters counting events happening out-
side the 8051. The use of the timerlcounter as an event counter is covered in this
section. As far as the use of a timer as an event counter is concerned, everything
that we have talked about in programming the timer in the last section also applies
to programming it as a counter, except the source of the frequency. When the
timer/counter is used as a timer, the 8051 's crystal is used as the source of the fre-
quency. When it is used as a counter, however, it is a pulse outside the 8051 that
increments the TH, TL registers, In counter mode, notice that the TMOD and TH,
TL registers are the same as for the timer discussed in the last section; they even
have the same names. The timer's modes are the same as well.

CIT bit in TMOD register


Recall from the last section that the CIT bit in the TMOD register decides
the source of the clock for the timer. If CIT = 0, the timer gets pulses from the
crystal. In contrast, when CIT = I, the timer is used as a counter and gets its puls-
es from outside the 8051. Therefore, when CIT = I,the counter counts up as puis- ,
es are fed from pins 14 and 15. ' These pins are called TO (Timer 0 input) and T I
(Timer I input), Notice that these two pins belong to port 3. In the case ofTimer
0, when CIT = I, pin P3.4 provides the clock pulse and the counter counts up for
each clock pulse coming from that pin. Similarly, for Timer I, when CIT = I each
clock pulse coming in from pin P3.5 makes the counter count up.
Table 9- I: Port 3 Pins Used For Timers 0 and I

Pin Port Pin Function Description


14 P3.4 TO Timer/Counter 0 external input
15 P3.5 TI TimerlCounter I external input
(MSB) (LSB)

GATE I CIT I Ml I MO GATE I CIT I MI I MO


Timer I Timer 0

CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C 255


, mpl 9·18
fed into pin T I write a program for counter 1 in mode
umang Ihat e Ioc k pu I es arc .' . '
2 to count the pulses and di play the state of the TL I count on P2.

MOV TMOD, #01100000B ;counter 1, mode 2,C/T=1


;external pulses
MOV TH1,#0 ;clear TH1
SETB P3.5 ;make T1 input
AGAIN: SETB TR1 ;start the counter
BACK: MOV A,TL1 ;get copy of count TL1
MOV P2,A ;display it on port 2
JNB TFl, BACK ;keep doing it if TF=O
CLR TR1 ;stop the counter 1
CLR TFl ;make TF=O
SJMP AGAIN ;keep doing it

Notice in the above program the role of the instruction "SETB P3. 5". Since
pons are SCI up for output when the 805 J is powered up, we make P3.5 an input port by
making it high. In other words, we must configure (set high) the TI pin (pin P3.5) to
allow pul es to be fed into it.
8051

P2 is connected to 8 LEOs P2 to
and input TI to pulse. LEDs
~P3.5
Tl

In Example 9-18, we use Timer I as an event counter where it counts up as


clock pulses a~e fed into pin 3.5. These clock pulses could represent the number
of people pas mg through an entrance, or the number of wheel rotations or any
other event that can be convened to pulses. '
In ~xample 9-18, the TL data was displayed in binary. In Example 9-19
the TL rcgi tcr arc convened to ASCII to be displayed on an LCD. '

.ru-t. overtlow
fl
r-~,,~-=
~
,-,=------------,
overflow
Timer 0 L..J L
external ag Timer I flag
input
pin 3.4
[TFO I external
input
I TFII
TFO goes high pin 3.5
TRO TF I goes high
when FFFF -- 0 eif = I TRI
when FFFF ..... O
Figure '/..5. (I) Timer 0 wllh Ellernaiinpul
( lode i) (b) Timer 1 with External Input (Mode 1)
2 6
Example 9-19

Assume that a I-Hz frequency pulse is connected to input pin 3.4. Write a program to
display counter 0 on an LCD. Set the initial value of THO to -60.

Solution:

To display the TL count on an LCD, we must convert 8-bit binary data to ASCJJ. Sec
Chapter 6 for data conversion.

ACALL LCD_SET_UP ;initialize the LCD


.MOV TMOD,#00000I10B;counter O,mode 2,C/T=1
MOV THO,#-60 ;counting 60 pulses
SETB P3 .4 ;make TO as input
AGAIN: SETB TRO ;starts the counter
BACK: MOV A,TLO ;get copy of count TLO
ACALL 'CONV ;convert in R2, R3, R4
ACALL DISPLAY ;display on LCD
JNB TFO,BACK ;loop if TFO=O
CLR TRO ;stop the counter 0
CLR TFO .make TFO=O
SJMP AGAIN ;keep doing it

;converting 8-bit binary to ASCII


;upon return, R4, R3, R2 have ASCII data (R2 has LSD)

CONV: MOV B,#10 ;divide by 10


DIV AB
MOV R2,B ;save low digit
MOV B,#10 ;divide by 10 once more
DIV AB
ORL A,#30H jmake it ASCII
MOV R4,A jsave MSD
MOV A,B
ORL A,#30H jmake 2nd digit an ASCII
MOV R3,A isave it
MOV A,R2
ORL A,#30H jmake 3rd digit an ASCII
MOV R2,A isave the ASCII
RET

8051
..----f--- -,
f--- to
Plf---

~P3.4
I Hz clock TO
§ LCD

By using 60 Hz we can generate seconds, minutes, hours.


. f 0 since on RESET, TLO = O.
Note that on the first round, It starts rom, besi g of the program
To solve this problem, load TL O WIt . h -60 at the egll1nll1 .

SSEMBLY AND C 257


CHAPTER 9: 8051 TIMER PROGRAMMING IN A
overflow flag .f"LJL overflow nag
Timer J ----r-'LITTLLlil_ .......~
extemalr r~
input
reload pin 3.5 TRI reload
.-='--,

C/T= I TFOgoes high C/T= I TF I goes high


when FF .... O when FF--O

Figure 9-6. Ttmer 0 with Extemal Input (Mode 2) Figure 9-7. Timer I with External Input (Mode 2)

As another example of the application of the timer with crr = I, wc can


fced an external square wave of 60 Hz frequency into the timer. The program will
generate the second, the minute, and the hour out of this input frequency and dis-
play the result on an LCD. This will be a nice digital clock, but not a very accu-
rate one.

Before we finish this chapter, we necd to slate two important points.


I. You might think that the use of the instruction "JNB TFx, target" to mon-
itor the raising of the TFx flag is a waste of the microcon!rollcr's time. You
arc right. There is a solution to this: the use of interrupts. By using interrupts
we can go about doing other things with the microcontroller. When the TF flag
is raised it will inform us. This important and powerful feature of the 8051 is
discussed in Chapter II.
2. You might wonder to what registcr TRO and TR I belong. They belong to a
rcgistcr called TCON, which is discussed next

Table 9-2: E uivalent Instructions for the Timer Control Re


For Timer 0
SETB TRO
SETB TCONA
CLR TRO
CLR TCONA
SETB TFO
SETB TCON.S
CLR TFO
CLR TCON.5
For Timer I
SETB TRI
SETB TCON.6
CLR TRI
CLR TCON.6
SETB TFI
SETB TCON.7
CLR TFl
CLR TCON.7
TCON: Timer/CounterControl Register

[ TF! I TR! I TFQ I TRQ I IEl I ITI I lEO lr-~JT::-:-O-

258
TeON register
In the examples so far we have seen the use of the TRO and TR 1 flags to
tum on or off the timers. These bits are part of a register called TCON (timer con-
trol). This register is an 8-bit register. As shown in Table 9-2, the upper four bits
are used to store the TF and TR bits of both Timer 0 and Timer 1. The lower four
bits are set aside for controlling the interrupt bits, which will be discussed in
Chapter 11. We must notice that the TCON register is a bit-addressable register.
Instead of using instructions such as "SETB TR1" and "CLR TR1", we could use
"SETB TCON. 6" and "CLR TCON. 6", respectively. Table 9-2 shows replace-
ments of some of the instructions we have seen so far.

The case of GATE = 1 in TMOD


Before we finish this section we need to discuss another case of the GATE
bit in the TMOD register. All discussion so far has assumed that GATE = O. When
GATE = 0, the timer is started with instructions "SETB TRO" and "SETB TRl",
for Timers 0 and I, respectively. What happens if the GATE bit in TMOD is set
to 17 As can be seen in Figures 9-8 and 9-9, if GATE = 1, the start and stop of the
timer are done externally through pins P3.2 and P3.3 for Timers 0 and 1, respec-
tively. This is in spite of the fact that TRx is turned on by the "SETB TRx"
instruction. This allows us to start or stop the timer externally at any time via a
simple switch. This hardware way of controlling the stop imd start of the timer can
have many applications. For example, assume that an 8051 system is used in a
product to sound an alarm every second using Timer 0, perhaps in addition to
many other things. Timer 0 is turned on by the software method of using the
"SETB TRO" instruction and is beyond the control of the user of that product.
However, a switch connected to pin P3.2 can be used to tum on and off the timer,
thereby shutting down the alarm.

XTAL
OSCILLATOR
1- +12 r--
CIT =0
' ....... ~
-u '-J
., V

! CIT =1
TO IN ~
Pin 3.2

:
TRO
--LJ
r-,
Gate
....5>-
-
INTO Pin
-- ,
Pin 3.2

Figure 9-8. Timer/Counter 0

N ASSEMBLY AND C 259


CHAPTER 9: 8051 TIMER PROGRAMMING I
XTAL +12
OSCILLATOR cii = 0

T1IN~
t cii» 1

Pin3.5

TR1------j

Gale ----{>--~l~
INTI Pin ~
Pin 3.3

Figure 9-9. Timer/Counter I

Review Questions
I. Who provides the clock pulses to 8051 timers if CIT = O?
2. Who provides the clock pulses to 8051 timers if CIT = J?
3. Does the discussion in Section 9.1 apply to timers if CIT = I? ?
4. What must be done to allow P3.4 to be used as an input for TI, and why.
5. What is the equivalent of the following instruction? "SETB TCON. 6"

SECTION 9.3: PROGRAMMING TIMERS 0 AND 1 IN 8051 C

In Chapter 7 we showed some examples of C programming for the 8051.


In this section we study C programming for the 8051 timers. As we saw in the
cxamples in Chapter 7, the general-purpose registcrs of the 8051, such as RO _ R7,
A, and B, are under the control ofthc C compiler and are not accessed directly by
C statemcnts. In the case of SFRs, thc entire RAM space of 80 _ FFH is accessi-
ble directly using 8051 C statements. As an example of accessing the SFRs direct-
ly, we saw how to access ports PO - P3 in Chapter 7. Next, we discuss how to
access the 8051 timers directly using C statements.

Accessing timer registers in C

. In 8051 C we can access the timer registers TH, TL, and TMOD directly
usingthe reg51.h header file. This is Shown in Example 9-20. Example 9-20 also
shows how to access the TR and TF bits.

-
Example 9-20

Write a 8051 C program to toggle all the bits of port P I continuously with some delay
in between. Use Timer 0, 16-bit mode to generate the delay.

Solution:

#include <reg5I.h>
void TODelay(void);
void main (void)
{
while(l) //repeat forever
{
Pl=Ox55: //toggle all bits of PI
TODelay (); //delay size unknown
Pl=OxAA; //toggle all bits of PI
TODelay ();
}
}

void TODelay ()
{
TMOD=OxOI: //Timer 0, Mode 1
TLO=OxOO: //load TLO
THO=Ox35: //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O;
TFO=O;
//turn off TO
//clear TFO I
FFFFH - 3500H = CAFFH = 51967 + I = 51968

51968 x 1.085 /..IS = 56.384 ms is the approximate delay.

8051

PO LEOs

-CHAPTER 9: 805] TIMER PROGRAMMING IN ASSEMBLY AND C 26]


Calculating delay length using timers

A s we men tiionc d iIn, Chapter 7 the delay length depends


. on three factors:
(a) the crystal frequency, (b) the number of clocks pcr machme cycle, and (c) the
C compiler, The original 8051 used 1/12 of the crystal oscillator frequency asone
machine cycle. In other words, each machine cycle is equal to 12 clocks pen ods
of the crystal frequency connected to the X I - X2 pins .. The nrne It takes for the
8051 to execute an instruction is one or marc machme cycles, as shown III
Appendix A. To speed up the 8051, many recent versions of the 8051 have
reduced the number of clocks per machine cycle from 12 to four, or even one, For
example, the AT89C51/52 uses 12, while the OS5000 uses 4 clocks, and the
OS89C4xO uses only one clock per mach inc cycle. As we mentioned earlier in this
chapter, the 8051 timers also usc the crystal frequency as the clock source. Thc
frequency for the timer is always 1I12th the frequency of the crystal attached to
the 8051, regardless of the 8051 version. In other words, for the AT89C51/52,
OS5000, or OS89C4xO the duration of the time to execute an instruction varies,
but they all use 1/12th of the crystal's oscillator frequency for the clock source to
the timers. This is done in order to maintain compatibility with the original 8051
since many designers use timers to create time delay. This is an important point
and needs to be emphasized. The C compiler is a factor in the delay size since var-:
ious 8051 C compilers generate different hex code sizes. This explains why the
timer delay duration is unknown for Example 9-20 since none of the other factors
mentioned is specified.

Delay duration for the AT89C51/52 and DS89C4xO chips

As we stated before, there is a major difference between the AT89C51 and


DS89C4xO chips in term of the time it takes to execute a single instruction.
A !though the OS89C4xO executes instructions 12 times faster than the AT89C51
chip, thcy
.
both . still use
.
Osc/12 clock for their timers ' . Thc faste
Ii r execu tiIon tiIme
for the mstrucuons WIll have an impact on your delay Ic tl T ify I'
'. ng 1. 'a ven t liS very
Important pomt, compare parts (a) and (b) of Example 9-21 since they have been
tested on these two chips with the same speed and C compiler.

Timers 0 and 1 delay using mode 1 (16-bit non auto-reload)


Examplcs 9-21 and 9-22 show 8051 C . .
in mode I (16-b" t _ . programmmg of the tuners 0 and I
I non auto reload). Examme them to get familiar with the syntax.

Timers 0 and 1 delay using mode 2 (8 bOt


• I auto-reload)
. Examples 9-23 through 9-25 shows 8051 '.
I rn mode 2 (8-bit auto-reload) St d h C programmmg of umers 0 and
tax. . u y t esc cxamples to get familiar with the syn-

262
Example 9-21

Write an 8051 C program to toggle only bit P 1.5 continuously every 50 ms. Use
Timer 0, mode I (l6-bit) to create the delay. Test the program (a) on the AT89C51 and
(b) on the DS89C420.

Solution:

#include <regsl.h>
void TOMIDelay(void);
sbit mybit=PIAS;
void main (void)
{
while(l)
{
mybit=-mybit; //toggle Pl.S
TOMIDelay (); //Timer 0, mode 1(16-bit)
}
}

(a) Tested for AT89C51, XTAL=II.0592 MHz, using the Proview32 compiler

void TOMIDelay(void)
{
TMOD=OxOl; //Timer 0, mode 1(16-bit)
TLO=OxFD; //load TLO
THO=Ox4B; //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O; //turn off TO
TFO=O; //clear TFO
}

(b) Tested for D589C420, XTAL=II.0592 MHz, using the Pioview32 compiler
I
void TOMIDelay(void)
{ I
TMOD=OxOl; //Timer 0, mode 1(16-~it)
TLO=OxFD; //load TLO
THO=Ox4B; //load THO
TRO=l; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O; //turn off TO
TFO=O; //clear TFO
}

FFFFH - 4BFDH = B402H = 46082 + 1 ;, 46083

Timer delay = 46083 x 1.085 lls = 50 DlS

- G IN ASSEMBLY AND C 263


CHAPTER 9: 8051 TIMER PROGRAM MIN
Example 9-22 500 Use
Write an 8051 C program to toggIe a11bits of P2 continuously every ms.
Timer I, mode I to create the delay.

Solution:

//tcsted for 0889C420, XTAL = II .0592 MHz, using the Proview32 compiler

#include <regsl.h>
void TIMIDelay(void);
void main (void)

unsigned char X;
P2=OxSS;
wh i Le I I )
(
P2=-P2; //toggle all hi ts of P2
for(x=O;x<20;x++)
TIMlDelay ();

void TIMIDelay(void)

TMOD=OxlO;
//Timer 1, mode 1(16-bit)
TLl=OxFE; //load TLI
THl=OxAS; //load THI
TRl=l; //turn on Tl
while (TFl==O);
//wait for TFI to rollover
TRl=O;
//turn off Tl
TFl=O; //clear TFI

A5FEH = 42494 in decimal

65536 - 42494 = 23042

23042 x 1.085 J1S = 25 ms and 20 x 25 rns = 500 rns

NOTE THAT 8051 TIMERS USE 1112 OF XTAL FREQUENCY,


REGARDLESS OF MACHINE CYCLE TIME.

264
Example 9-23

Write an 8051 C program to toggle only pin P 1.5 continuously every 250 ms. Use
Timer 0, mode 2 (8-bit auto-reload) to create the delay.

Solution:

Iitested for DS89C420, XTAL = 11.0592 MHz, using the Proview32 compiler
#include <reg51.h>
void TOM2Delay(void) ,
A
sbit mybit=PI 5;
void main (void)
{
unsigned char x, y,
while (1)
{
mybit=-mybit; //toggle Pl. 5
for(x=O,x<250;x++) //due to for loop overhead
for(y=O;y<36;y++) //we put 36 and not 40
TOM2Delay() ,

void TOM2Delay(void)
{
TMOD=Ox02; //Timer 0, mode 2(B-bit auto-reload)
THO=-23; //load THO (auto-reload value)
TRO=I; //turn on TO
while (TFO==O) ; //wait for TFO to rollover
TRO=O, / / turn off. TO
TFO=O; //clear TFO
}

256 - 23 = 233

23 x 1.085 us = 25 lls

25 us x 250 x 40 = 250 ms by calculation.

However the scope output does not give us this result. This is due to overhead of the
, C. To correct this problem, we put 36' mstea df40
for loop in 0 .

G IN ASSEMBLY AND C 265


CHAPTER 9: 8051 TIMER PROGRAMMIN
Example 9-24
Write an 8051 C program to create a frequency of 2500 Hz on pin P2. 7. Use Timer I,
mode 2 to create the delay.

Solution:

//tested for D589C420, XTAL ~ 11.0592 MHz, using the Proview32 compiler

#include <regS1.h>
void T1M2Delay(void);
sbit mybit=P2A7;
void main (void)
(
unsigned char X;
while (1)
(
mybit=-mybit; Iitoggle P2. 7
TlM2Delay ();

void T1M2Delay(void)

TMOD=Ox20; IITimer 1, mode 2(8-bit auto-reload)


TH1=-184; Ilload TH1(auto-reload value)
TR1=1; Iiturn on T1
while (TF1==O); Ilwait for TF1 to rollover
TR1=O; Iiturn off T1
TF1=O; Ilclear TF1

I / 2500 Hz ~ 400 us

400 us / 2 ~ 200 us

200 us / 1.085 us ~ 184

8051

2500 Hz
P2.7~

266
Example 9-25

A switch is connected to pin P 1.2. Write an 8051 C program to monitor SW and create
the following frequencies on pin PI.7:
SW=O: 500 Hz
SW=l: 750Hz
Use Timer 0, mode I for both of them.

Solution:

!!tested for AT89C51!52, XTAL = 11.0592 MHz, using the Proview32 compiler
#include <reg51.h> '
sbit mybit=PIA5;
A
sbit SW=PI 7;
void TOMIDelay(unsiged char);
void main (void)
{
SW=l, //make PI.7 an input
while (I)
{
mybit=-mybit; //toggle P1.5
if (SW==O) //check switch
TOMlDelay (0);
else
TOMlDelay (I);

}
void TOMIDelay(unsigned char c)
{
TMOD=OXOI;
if (c==O)
{
TLO=Ox67; //FC67
THO=OxFC;
}
else
(
TLO=Ox9A; //FD9A
THO=OxFD;
)
TRO=l;
while (TFO==O) ;
TRO=O;
TFO=O,

FC67H = 64615
65536 - 64615 = 921
921 X 1.085 us = 999.285 IlS
1 ! (999.285 Ils X 2) = 500 Hz

- ~ G IN ASSEMBLY AND C 267


CHAPTER 9: 8051 TIMER PROGRAMMIN
----ldIlII

C Programming of timers 0 and 1 as counters


In Section 9.2 we showed how to use timers 0 and I as event counters. A
timer can be used as a counter if we provide pulses from outside the chip instead
of using the frequency of the crystal oscillator as the clock source. By feeding
pulses to the TO(P3.4) and TI (P3.5) pins, wc tum Timer 0 and Timer I into count-
er 0 and counter I, respectively. Study the next few examples to see how timers 0
and I arc programmed as counters using the C language.

Example 9-26

Assume that a l-Hz external clock is being fed into pin TJ (P3.5). Write a C program
for counter I III mode 2 (8-blt auto reload) to count up and display the state of the TLI
count on P I. Start the count at OH.

Solution:

#include <regSI.h>
sbit Tl = P3'S;
void main (void)
{
T1=1;
Ilmake T1 an input
TMOD=OX60;
II
TH1=O;
Iiset count to 0
while (1)
{ Ilrepeat forever
do
{
TR1=1;
Iistart timer
PhTL1;
} Ilplace value on pins
While (TF1==O) .
TRl:;;O i I
Ilwait here
TFl=O;
Iistop timer
I I clear flag

8051
P I is connected to 8 LEDs.
T1 (P3.5) is connected to a PI to
I-Hz external clock. LEDs

I Hz TI
Example 9-27
Assume that a I-Hz external clock is being fed into pin TO (P3.4). Write a C program
for counter 0 in mode 1 (I 6-bit) to count the pulses and display the THO and TLO reg-
isters on P2 and PI, respectively.

Solution: '1
I
#include <reg51.h>

void main (void)


{
TO;l; Ilmake TO an input
TMOD;ox05; II
TLO;O; Iiset count to 0
THO;O; Iiset count to 0

while (1) Ilrepeat forever


{ I

do
{
TRO;l; Iistart timer
Pl;TLO; Ilplace value on pins
P2;THO; II
}
while (TFO;;O) ; Ilwait here
TRO;O; Iistop timer
TFO;O;
}
}

8051 "
~-....,~
f-- PI and
P!f--
P2 to
LEDs
5LJL- ~
I Hz clock TO P3.4

- IN ASSEMBLY AND C 269


CHAPTER 9: 8051 TIMER PROGRAMMING
Example 9-28
Assume that a 2-Hz external clock is being fed into pin TI (P3.5). Write a C program
for counter 0 in mode 2 (8-bit auto reload) to display the count in ASCII. The 8-bit
binary count must be converted to ASCII. Display the ASCII digits (in binary) on PO,
PI, and P2 where PO has the least significant digit. Set the initial value of THO to O.

Solution:
To display the TL I count we must convert 8-bit binary data to ASCII. See Chapter 7
for data conversion. The ASCII values will be shown in binary. For example, '9' will
show as 00 I J J 001 on ports.
#include <reg51.h>
void BinToASCII(unsigned char);
void main ()
(
unsigned char value;
T1;1;
TMOD;OX06;
THO;O;

while!l)
(
do
(
TRO;l;
value;TLO;
BinTOASCII!value);
)
while (TFO;;O) ;
TRO;O;
TFO;O;
}
)

void BinToASCII(unsigned char


value)
//see Chapter 7
unsigned char X,d1,d2 d3.
x ; value / 10. r

dl ; value % 1~
d2 ; x % 10.
d3 x / 10'
PO ; 30 I dl;
PI 30 I d2;
P2 ; 30 I d3
Example 9-29

Assume that a 60-Hz external clock is being fed into pin TO (P3.4). Write a C program
for counter 0 in mode 2 (8-bit auto-reload) to display the seconds and minutes on P I and
P2, respectively.

Solution:

#include <reg51.h>
void ToTime(unsigned char);
void main ()
{
unsigned char val;
TO=I;
TMOD=Ox06;
THO=-60;
liTO, mode 2, counter
while (I)
Iisec = 60 pUlses

{
do
{
TRO=I;
sec=TLO;
ToTime (val);
)
while (TFO==O) ;
TRO=O;
TFO=O;
)
},
void ToTime(unsigned char val)
{
unsigned char sec, min;
min = value I 60;
sec = value % 60;
PI = sec;
P2 = min;

8051
'--'1-- <,
I-- PI and
PI-
P2 to
~
-fL......JL-. P3.4 P2~ LEDs
f--
60 Hz clock TO

By using 60 Hz, we can generate secon ds , minutes ' hours.

-CHAPTER 9: 8051 TIMER PROGRAMMING IN ASSEMBLY AND C 271


For Examples of Timer 2, see t~e
www.MicroDigitaIEd.com Web site.

Review Questions

I. Who provides the clock pulses to 8051 time~~ ifC/T = O? 20"


2, Indicate the selection made in the statement TMOD = Ox .
3, In mode I, the counter rolls over when it goes from __ to __ '
4, In mode 2, the counter rolls over when it goes from __ to __ ' ,
5, In the statement "THI = -200", find the hex value for the TH register.
6, TFO and TF I are part of register __ '
7, In Question 6, is the register bit-addressable?
8, Show how to monitor the TF I flag for high in 8051 C,

SUMMARY

The 8051 has two timers/counters, When used as timers they can generate
time delays, When used as counters they can serve as event counters, This chap-
ter showed how to program the timers/counters for various modes,
The two timers are aceesscd as two 8-bit registers: TLO and THO for
Timer 0, and TL I and TH I for Timer I, Both timers usc the TMOD register to set
timer operation modes, The lower 4 bits of TMOD arc used for Timer 0 and the
upper 4 bits are used for Timer I,
There are different modcs that can be used for each timer. Mode 0 sets the
timer as a 13-bit timer, mode I sets it as a 16-bit timer, and mode 2 sets it as an 8-
bit timer,

When the timer/counter is used as a timer, the 8051 's crystal is used as the
source of the frequency; when it is used as a counter, however, it is a pulse outside
the 8051 that increments the TH, TL registers,

PROBLEMS

SECTION 9, I: PROGRAMMING 8051 TIMERS

I, How many timers do we have in the 805 I?


2, The timers of the 8051 are _-bit and arc designated as and

3, The registers of Timer 0 arc accessed as d


_an
272
CHAPTEF
4. The registers of Timer 1 are accessed as and
5. In Questions 3 and 4, are the registers bit-addressable?---
6. The TMOD register is a(n) _-bit register.
7. What is the job of the TMOD register?
8. True or false. TMQD is a bit-addressable register.
9, Find the TMOD value for both Timer 0 and Timer I , mode 2 , software start /
stop (gate = 0), with the clock coming from the 8051 's crystal.
10. Find the frequency and period used by the timer if the crystal attached to the
8051 has the following values.
(a) XTAL = 11.0592 MHz (b) XTAL = 20 MHz
(c) XTAL = 24 MHz (d) XTAL = 30 MHz
II. Indicate the size of the timer for each of the following modes.
(a) mode 0 (b) mode I (e) mode 2 I
12. Indicate the rollover value (in hex and decimal) of the timer for each of the fol-
lowing modes.
(a) mode 0 (b) mode I (c) mode 2
I
j 3. Indicate when the TF I flag is raised for each of the following modes.
(a) mode 0 (b) mode I (c) mode 2
14. True or false. Both Timer 0 and Timer 1 have their own TF.
15. True or false. Both Timer 0 and Timer 1 have their own timer start (TR).
16. Assuming XTAL = 11,0592 MHz, indicate when the TFO flag is raised for the
following program.
MOV TMOD, #01
MOV TLO,#12H
MOV THO,#lCH
SETB TRO
17. Assuming that XTAL = 16 MHz, indicate when the TFO flag is raised for the
following program.
MOV TMOD,#Ol
MOV TLO,#12H
MOV THO, #lCH
SETB TRO ,
18. Assuming that XTAL = 11.0592 MHz, indicate when the TFOflag is raised for
the following program.
MOV TMOD,#Ol
MOV TLO,#lOH
MOV THO,#OF2H
SETB TRO . isedf h
19. Assuming that XTAL = 20 MHz, indicate when the TFO flag IS raise or t e
following program.
MOV TMOD,#Ol
MOV TLO,#12H
MOV THO,#lCH

SETB TRO H F' d the TH I TLl value to generate a


20. Assume that XTAL = 11.0592 M z. m, d 'I
. I' ogrammed
time delay of 2 ms. TImer ISpI' m mo e .

G IN ASSEMBLY AND C 273


CHAPTER 9: 8051 TIMER PROGRAMMlN
21. Assume that XTAL = 16 MHz. Find the TH I,TL I value to generate a time
delay of 5 ms. Timer I is programmed in mode I. .
22. Assuming . that XTAL --. II 0592 MHz. , program Timer 0 to generate a time
delay of 2.5 ms.
23. Assuming that XTAL = 11.0592 MHz, program Timer I to generate a time
delay of 0.2 ms. .
24. A suming that XTAL = 20 MHz, program Timer I to generate a time delay of
100 ms.
25. Assuming that XTAL = 11.0592 MHz, and we are generating a square wave on
pin P 1.2, find the lowest square wave frequency that we can generate using
mode I.
26. Assuming that XTAL = 11.0592 MHz, and we are generating a square wave on
pin P 1.2, find the highest square wave frequency that we can generate using
mode I.
27. Assuming that XTAL = J 6 MHz, and we are generating a square wave on pin
P 1.2, find the lowest square wave frequency that we can generate using
mode I.
28. Assuming that XTAL = 16 MHz, and we are generating a square wave on pin
P 1.2, find the highest square wave frequency that we can generate using
mode I.
29. In mode 2 assuming that TH I = F IH, indicate which states timer 2 goes
through until TFI is raised. How many states is that?
30. Program Timer I to generate a square wave of I kHz. Assume that XTAL =
IJ .0592 MHz.
3 I. Program Timer 0 to generate a square wa.ve of 3 kHz. Assume that XTAL =
I) .0592 MHz.
32. Program Timer 0 to generate a square wave of 0.5 kHz. Assume that XTAL =
20 MHz.
33. Program Timer I to generate a square wave of 10kHz. Assume that XTA L =
20 MHz.
34. Assuming that XTAL = 11.0592 MHz, show a program to generate a l-second
time delay. Use any timer you want,
35. Assuming that XTAL = 16 MHz, show a program to generate a 0.25-second
time delay. Use any timer you want.
36. Assuming that XTAL = 11.0592 MHz and that we arc· generating a square
wave on pm P 1.3, find the lowest square wave frequency that we can generate
usmg mode 2.
37. Assuming that XTAL = 1J 0592 MH d h .
. . . z an t at we are generatmg a square
wave on pin P 1.3, find the highest square wave frequency that we can gener-
ate using mode 2.
38. Assuming that XTAL = 16 MH d h .
. zan t at we are generatmg a square wave on
pin P 1.3, find the lowest square wave frequeney that we e .
mode 2. an generate usmg
39. Assuming that XTAL = 16 MHz and that we .
. PI 3 fi d h . arc generatmg a square wave on
pm ., 111 t e highest square wave frequency that .
mode 2. we can generate usmg
40. Find the value (in hex) loaded into TH in .a h fl.
e Cot ic followmg.
274
-
CHAPTEl
(a) MOY THO,#-12 (b) MOY THO,#-22
(c) MOY THO,#-34 (d) MOY THO,#-92
(e) MOY THI,#-120 (I) MOY THl,#-104
(g) MOY TH I,#-222 (h) MOY TH 1,#-67
41. In Problem 40, indicate by what number the machine'cycJe frequency of921.6
kHz (XTAL = 11.0592 MHz) is divided,
42. In Problem 41, find the time delay for each case from the time the timer starts
to the time the TF flag is raised.

SECTION 9.2: COUNTER PROGRAMMTNG

43. To use the timer as an event counter we must set the CIT bit in the TMOD reg-
ister to (low, high).
44. Can we use both of the timers as event counters?
45. For counter 0, which pin is used to input clocks?
46. For Counter I, which pin is used to input clocks?
47. Program Timer I to be an event Counter. Use mode I and display the binary
count on PI and P2 continuously. Ser the initial count to 20,000.
48. Program Timer 0 to be an event counter. Use mode 2 and display the binary
count on P2 continuously, Set the initial count to 20.
49. Program Timer I to be an event counter. Use mode 2 and display thc decimal
I
I
count on P2, PI, and PO continuously. Set the initial count to 99.
50. The TCON register is a(n) __ -bit register.
5l. True or false. The TCON register is not a bit-addressable register.
52. Give another instruction to perform the action of "SETB TRO". I

SECTION 9.3: PROGRAMMTNG TIMERS ° AND I IN 8051 C

°
53. Program Timer in C to generate a square wave of 3 kHz. Assume that XTAL
= 11.0592 MHz.
54. Program Timer I in C to generate a square wave Of 3 kHz. Assume that XTAL
= 11.0592 MHz. ,
°
55. Program Timer in C to generate a' square wave of 0.5 kHz. Assume that
XTAL = 11,0592 MHz.
56. Program Timer I in C to generate a square wave of 0.5 kHz. Assume that
XTAL = 11.0592 MHz. , ,
57 Program Timer I in C to be an event counter. Use mode I and display the bina-
. ry count on P I and P2 continuously. Set the initial count to 2 O,0010,
th bi
58. Program Timer 0 in C to be an event counter. Use mode 2 and dISP ay e ina-
ry count on P2 continuously. Set the initial count to 20.

m 9: 8051 TIMER PROGRAMMING, TN ASSEMBLY AND C


275
ANSWERS TO REVIEW QUESTIONS

ECTION 9,1: PROGRAMMING 8051 TIMERS

I. Two
2, 2.8
3, 8
4,
False , L r t;
5,
00100000 indicates Timer I. mode 2, software start and stop, and usmg XTA lor ircqucncy.
6, FFFFH 10 0000
7, FFH 1000
8, -200 is 38H; therefore, TH I = 38H
9, 2 msll ,085 ms = 1843 = 0733H where TH = 0711 and TL = 33H
10, 100 ms/1.085 ms = 92 or 5CH; therefore, TH = 5CH

SECTION 9,2: COUNTER PROGRAMMING

I. The crystal attached 10 the 805 I


2, The clock source for the timers comes from pins TO aod T I,
3, Yes
4, We must usc (he instruction "SETB P3.4" 10 configure the T I pio as input, which allows the
clocks to come from an external source. This is because all ports are configured as output
upon reset.
5, SETB TRI

SECTION 9,3: PROGRAMMING TIMERS OAND I IN 8051 C

I. The crystal attached to the 8051


2, Timer 2, mode 2, 8-bil auto reload
3, FFFFH 100
4, FHI 100
5. 38H
6, TMOD
7, Yes
8, whilc(TFI=O);
CHAPTER 10

8051 SERIAL PORT


PROGRAMMING IN
ASSEMBLY AND C
OBJECTIVES

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

» Contrast and compare serial versus parallel communication


» List the advantages of serial communication over parallel
» Explain serial communication protocol
» Contrast synchronous versus asynchronous communication
» Contrast half- versus full-duplex transmission
» Explain the process of data framing
» Desribe data transfer rate and bps rate
» Define the RS232 standard
» Explain the use of the MAX232 and MAX233 chips
» Interface the 8051 with an RS232 connector
» Discuss the baud rate of the 8051
» Describe serial communication features of the 8051
» Program the 8051 serial port in Assembly and C
» Program the second serial port of DS89C4xO in Assembly and C

277
Computers transfer data in two ways: parallel and serial, In parallel data
transfers, often 8 or more lines (wire conductors) are used to transfer data to a
device that is only a few feet away. Examples of parallel transfers arc pnnters and
hard disks: each uses cables with many wire strips. Although III such cases a lot of
data can be transferred in a short amount of time by using many wires in parallel,
the distance cannot be great. To transfer to a device located many meters away, the
serial method is used. In serial communication, the data is sent one bit at a time,
in contrast to parallel communication, in which the data is sent a byte or more at a
time, Serial communication of the 8051 is the topic of this chapter. The 8051 has
serial communication capability built into it, thereby making possible fast data
transfer using only a few wires.
In this chapter we first discuss the basics of serial communication. In
Section 10.2, 8051 interfacing to RS232 connectors via MAX232 line drivers is
discussed. Scrial port programming of the 8051 is discussed in Section I D.3. The
second serial port of DS89C4xO is programmed in Section I D.4. Section 1D.5 cov-
crs 8051 C programming for serial ports #0 and # I.

SECTION 10.1: BASICS OF SERIAL COMMUNICATION

Whcn a microprocessor communicates with the outside world, it provides


the data in byte-sized chunks. In somc cases, such as printcrs, the information is
simply grabbed from the 8-bit data bus and presented to the 8-bit data bus of the
printer. This can work only if the cable is not too long, since long cables diminish
and even distort Signals. Furthermore, an 8-bit data path is expensive. For these
reasons, serial communication is used for transferring data between two systems
located at distances of hundreds of feet to mi lIions of miles apart. Figure I D- J dia-
grams serial versus parallel data transfers.

Serial Transfer
Parallel Transfer

l~s~e~n~d~e~rJI-_---j~~1
Receiver' DO
Sender Receiver

D7

Figure 10-1. Serial versus Parallel Data Transfer

. The fact that serial communication Uses. ..


8-blt data line of parallel communicatl·o I a slllgic data line mstcad of the
n not on y makcs it h
enables two computers located in two diff . .. I muc cheaper but also
i
te Iep hone, rerent cities t .
0 commullIcate over the
For serial data communication to work th b
, e ytc of data must be converted
278
to serial bits using a paralIel-in-serial_out shift register; then it can be transmitted
over a single data line. This also means that at the receiving end there must be a
serial-in-parallel-out shift register to receive the serial data and pack them into a
byte. Of course, if data is to be transfened on the telephone line, it must be con-
verted from as and I s to audio tones, which are sinusoidal-shaped signals. This
conversion is performed by a periphcral device called a modem, which stands for
"modulator/demodulator. "
When the distance is shOI1,the digital signal can be transfened as it is on
a simple wire and requires no modulation. This is how IBM PC keyboards trans-
fer data to the motherboard. However, for long-distance data transfers using com-
munication lines such as a telephone, serial data communication requires a modem
to modulate (convert from as and Is to audio tones) and demodulate (converting
from audio tones to as and Is).
Serial data communication uses two methods, asynchronous and synchro-
nous. The synchronous method transfers a block of data (characters) at a time,
while the asynchronous method transfers a single byte at a time. It is possible to
write software to use either of these methods, but the programs can be tedious and
long. For this reason, there are speciallC chips made by many manufacturers for
serial data communications. These chips are commonly referred to as VART (uni-
versal asynchronous receiver-tran~mitter) and USART (universal synchronous-
asynchronous receiver-transmitter).' The 8051 chip has a built-in UART, which is
discussed in detail in Section 10J.

Figure 10-2. Simplex, Half-, and Full-Duplex Transfers'

Half- and full-duplex transmission . .,


., . the data can be transmitted and received, It IS. a
If
In data transrmssion . lex transmissions such as with
.. This is in contrast to SImp, .
duplex transrmssion. IS IS I ds d t Duplex transmissions can be half
. . . h h uter only sen s a a. . I
pnnters ' m whic t e comp
. hether or not the data transfer can be sirnu taneous.
or full duplex, depending on w . ., eferred to as half duplex. If the data
.
If data is transmitted one way at a time, It ISr

- MMING IN ASSEMBLY AND C 279


CHAPTER 10: 8051 SERIAL PORT PROGRA .
can go both ways at the same time, it is/ull duplex, Of course, full duplex requires
two wire, con d uc tors fior the data lines (in addition to the Signal ,ground), one
, for
"
transrnrssron an d one for reception
. , in order to transfer and receive data sirnulta-
neously. Sec Figure 10-2,
Asynchronous serial communication and data framing
The data coming in at the receiving end of the data line in a serial data
transfer is aliOs and Is; it is difficult to make sense of the data unless the sender
and receiver agree on a set of rules, a protocol, on how the data is packed, how
many bits constitute a character, and when thc data begins and ends,

Start and stop bits


Asynchronous serial data communication is widely used for
character-oriented transmissions, while block-oriented data transfers usc the syn-
chronous method, In the asynchronous method, each character is placed between
start and stop bits, This is ealiedFaming, In data framing for asynchronous com-
munications, the data, such as ASCII characters, arc packed between a start bit and
a stop bit. The start bit is always one bit, but the stop bit can be one or two bits,
The start bit is always a 0 (low) and the stop bit(s) is I (high), For example, look
at Figure 10-3 in which the ASCII character "A" (8-bit binary 0100 0001) is
framed bctwecn the start bit and a single stop bit, Notice that the LSB is sent out
tirst.

• •
space
stop
bit
0 1 o o o o o 1 start mark:
;t~:--'
. .
bit ;
goes out last 07 t:
DO goes out first
Figure 10-3. Framing ASCII "A" (4IH)
Notice in Figure 10-3 th t he h '
hi h ' a w en t ere IS no transfer, the signal is I (high)
w IC IS referred to as mark The 0 (I )' ,
t " , , ,e ow IS referred to as space, Notice that the
ransmrssion begins With a start bit followed b DO ' ,
of the bits until thc MSB (D7) d f y uu, which ISthe LSB, then the rest
the character "A", ,an mally, the one stop bit indicating the end of
In asynchronous serial eommunicati ' h '
be programmed for data that' 7 8 bi ons, penp eral chips and modems can
IS or Its Wide Thi " ddi
of stop bits I or 2 Whl'le in Id ' IS IS III a dition to the number
" 0 er systems ASClI h
years, due to the extended ASCII h c araeters were 7-bit, in recent
c araeters 8-bit d t h b
some older systems due to the sl f ' a a as eeome common, In
, ' owness 0 the rec ' , , ,
stop bits were used to give the d '. ffici ,elvlllg mechanical device, two
, , cvice su IClent time t "
miSSion of the next byte In mod PC h . 0 organize Itselfbefore trans-
d ar d ,Assuming that we are'em s oweve th
tran r ' r, e usc of one stop bit is stan-
bi sJerrlllg a text til f ASC J
It, we have a total of 10 bils fi each ea I characters using I stop
b' or eac character' 8 b' f
It each for the start and stop b't Th ,Its or the ASCII code and I
' I s, erefore for e h 8 bi ,
ex tfa 2 b ItS, which gives 200//0 over h cad, ' ae - It character there are an

-
CHAPTE
In some systems, the parity bit of the character byte is included in the data
frame in order to maintain data integrity. This means that for each character (7- or
8-bit, depending on the system) we havc a single parity bit in addition to start and
stop bits. The parity bit is odd or even. In the case of an odd-parity bit the number
of data bits, including the parity bit, has an odd number of 1s. Similarly, in an
even-parity bit system the total number of bits, including the parity bit, is even. For
example, the ASCII character "A", binary 0 I 00 000 I, has 0 for the even-parity bit.
UART chips allow programming of the parity bit for odd-, even-, and no-parity
options.

Data transfer rate

The rate of data transfer in serial data communication is stated in bps (bits
per second). Another widely used terminology for bps is baud rate. However, the
baud and bps rates are not necessarily equal. This is due to the fact that baud rate
is the modem terminology and is defined as the number of signal changes per sec-
ond. In modems a single change of signal, sometimes transfers several bits of data.
As far as the conductor wire is concerned, the baud rate and bps are the same, and
for this reason in this book we use the terms bps and baud interchangeably.
The data transfer rate of a given computer system depends on communica-
tion ports incorporated into that system. For example, the early IBM PC!XT could
transfer data at the rate of 100 to 9600 bps. In recent years, however, Pentium-
based PCs transfer data at rates as high as 56K bps. It must be noted that in asyn-
chronous serial data communication, the baud rate is generally limited to
100,000 bps.

R5232 standards
To allow compatibility among data communication equipment made by
various manufacturers, an interfacing standard called RS232 was set by the
Electronics Industries Association (EIA) in 1960. In J 963 it was modified and
called RS232A. RS232B and RS232C were issued in 1965 and 1969, respective-
Iy. In this book we refer to it simply as .RS232. Today, RS232 IS th~ most Widely
used serial I/O interfacing standard. This standard IS used 111PCs and numerous
types of equipment. However, sinee the standard was set long before the advent of
the TTL logic family, its input and output voltage levels are not TTL compatible,
In RS232, a I IS . represente db y -, 3 to -25 V while a 0 bit IS +3 .to +25 Y, making
-3 to +3 undefined.For this reason, to connect any RS232 to a mlcroc:n~~~~ sys-
I converters such as MAX232 to convert t e ogre
tern we must use vo tage . MAX232 Ie chips are com-
levels to the RS232 voltage levels, and vice versa. t MAX232 is discussed in
monly referred to as line drivers. RS232 connecnon 0
Section 10.2.

RS232 pins .
. d their labels for the RS232 cable, com-
Table 10-1 provides the p111San I b I' DB-25P refers to the plug
DB 25 onnector In a e mg,
monly referred to as the - c h' ket connector (female). See Figure
connector (male) and DB - 25S I's for t e soc
10-4.

- MING IN ASSEMBLY AND C 281


CHAPTER 10: 8051 SERIAL PORT PROGRAM
13

o •••••••••••••
•••••••••••• o
14 25

Figure 10-4. RS232 Connector D8-25


Since not all the pins are used in PC cables, IBM introduced the 08-9 ver-
sion of the serial I/O standard, which uses 9 pins only, as shown in Table 10-2. The
08-9 pins are shown in Figure 10-5.

Data communication classification


Current terminology classifies data communication equipment as DTE
(data terminal equipment) or OCE (data communication equipment). DTE refers
to terminals and computers that send and receive data, while DCE refers to com-
munication equipment, such as
modems, that are responsible for trans- Table 10-1: RS232 Pins (08-25)
ferring the data. Notice that all the
RS23 2 pi n fu nction deli n iti ons 0 f 7Pn~~O.;;e;;;sc:;;,rdi
,;,;i pc;;t;;;io;;,n=-~c=-=__ ~
Tables 10-1 and 10-2 arc from the DTE =I__ -=P:..:ro::.:t::::ec::.:t:.,:jv..::e
....g.:.ro~u~n~d~ _
point of view. :;-2
__ -=T:.::ra~n::;sn~1~i
tt~e~d~d~a~ta~(LT~x~D~)L __
The simplest connection 73__ ~R::::ec::.:e::.iv:..:e:::d:..:d::.:a:.::ta~(R~x=D=)~
_
between a PC and microcontrollcr -;4__ .;:R;.;::e::l.gu::.:e~s~t
~to:.:s~e~n~d~(1ITS)~~ _
requires a minimum of three pins, TxD, -;5__ -=C.:.:le::a::.r.:.:to::....:::.:se:::n:.::dc.l(..::TIS)~~
_
RxO, and ground, as shown in Figure ::;6
__ ;;D.::;a~ta:..:s;.::.e~t
:..:re~a~d.z..y..l.(~D:.':S~R~)~ _
10-6. Notice in that figure that the RxD ~7_--;S~i.l>gn~a~l..Qg:..:ro~u~n~d..l.(G~N~D~)=;--_
and TxD pins are interchanged. ~8;;-;;_-;=;D:.:a~ta:.:c::.:a:::rr::.ie~r....:d~e~te~c~t..l.(OCD~~L)
__
9/10 Reserved for data testing
Examining RS232 hand-
II Unassigned
shaking signals
12 Secondary data carrier detect
To ensure fast and reliable data 13 Secondary clear to send
transmission between two devices, the 14 Secondary transmitted data
data transfer must be coordinated. Just 15 Transmit signal clement timing
as In the case ofthe printer, because the 16 Secondary received data
receiving device in serial data commu- 17 Receive signal element timing
nication may have no room for the data 18 Unassigned
there must be a way to inform the 19 Secondary regucst to send
sender. to stop sending data . Many 0 f 20 Data terminal ready (UTR)
t he pins of the RS-232 co 21 Signal guality detector
d f< nneetor are
use . or handshaking signals. Their 22 Ring indicator
deseflptlOns are provided below onl as 23 Data signal rate select
a reference and they can be b y
since th ypassed 24 Transmit signal element timing
ey are not supported by th 25 Unassigned
8051 UART chip. c

CHAPTE
l. OTR (data terminal ready). When a
term mal (or a PC COM par t)' IS 5
turned on, after going through a
<-.,
self-test, It sends out signal OTR to
indicate that it is ready for commu-
o •••• o
mcation .. If there is something ••••
wrong with the COM port, this sig-
nal will not be activated. This is an 6
9
active-low signal and can be used
to inform the modem that the com- Figure 10-5. DIJ..9 9-Pin Connector
puter is alive and kicking. This is
an output pin from OTE (PC COM Table 10-2: IBM PC DB-9 Signals
port) and an input to the modem.
Pin Description
2. OSR (data set ready). When OCE
I Data carrier detect (DCD)
(modem) is turned on and has gone
2 Received data (RxD)
through the self-test, it asserts OSR
3 Transmitted data (TxO)
to indicate that it is ready to com-
4 Data terminal ready (OTR)
municate. Thus, it is an output
from the modem (DCE) and input
s Signal ground (GND)
6 Data set ready (psR)
to the PC (DTE). This is an active-
low signal. If for any reason the 7 Reguest to send (RTS)
modem cannot make a connection 8 Clear to send (CIS)
to the telephone, this signal 9 Ring indicator (RI)
remains inactive, indicating to the
PC (or terminal) that it' cannot 1------------
accept or send data, OTE OTE
3. RTS (request to send). When the TxD TxD
OTE device (such as a PC) has a
byte to transmit, it asserts RTS to RxD RxD
signal the modem that it has a byte
of data to transmit. RTS is an ground
acti ve-low output from the DTE
and an input to the modem. Figure 10-6. Null Modem Connection
4. CTS (clear to send). In response to
RTS, when the modem has room for storing the data it is to receive, it sends
out signal CTS to the DTE (PC) to indicate that it can receive the data now.
This input signal to the DTE is used by the OTE to start transmission.
S. OCO (carrier detect, or DCD, data carrier detect). The modem asserts signal
OCO to inform the DTE (PC) that a valid carrier has been detected and that
contact between it and the other modem is established. Therefore, OCO is an
output from the modem and an input to the PC (DTE).
6. Rl (ring indicator). An output from the modem (DCE) and an input to a PC
(OTE) indicates that the telephone is ringing. lt goes on and off in synchro-
nization with the ringing sound. Of the six handshake signals, this is the least
often used , due to the fact that modems take care of answering the phone.
However, if the PC is in charge of answering the phone, this signal can be used.

PTER 10: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 283


a

From the above description, PC and modem communication can be sum-


marized as follows: While signals OTR and OSR are used by the PC and modem,
respectively, to indicate that they arc alive and well, it is RTS and CTS that actu-
ally control the flow of data. When the PC wants to send data It asserts RTS, and
in response, if the modem is ready (has room) to accept the data, It sends back
CTS. If, for lack of room, the modem does not activate CTS, the PC will deassert
OTR and try again. RTS and CTS are also referred to as hardware control flow sig-
nals.
This concludes the description of the most important pins of the RS232
handshake signals plus TxO, RxO, and ground. Ground is also referred to as SG
(signal ground).

IBM PC/compatible COM ports


IBM PC/compatible computers based on x86 (8086, 286, 386, 486, and
Pentium) microprocessors normally have two COM ports. Both COM ports have
RS232-type connectors. Many PCs usc one each of the OB-25 and OB-9 RS232
connectors. The COM ports arc designated as COM I and COM 2. At the present
time COM I is used for the mouse and COM 2 is available for devices such as a
modem. We can connect the 8051 serial port to the COM 2 port of a PC for serial
communication experiments.
With this background in serial communication, we arc ready to look at the
8051. In the next section we discuss the physical connection of the 805 J and
RS232 connector, and in Section 10J we show how to program the 8051 serial
communication port.

Review Questions
I. The transfer of data using parallel lines is (faster, slower) but
---- . (more expensive, less expensive).
2. True or false. Sending data to a printer is duplex.
3. True or false. In full duplex we must have two data lines one for transfer and
one for receive. '
4. The start and stop bits are used in the (svnch
nous) method. sync ronous, asynchro-
5. Assuming that we are transmitting the ASClI letter "E" (0 I00 0101' b' )
With no panty bit and one stop bit h h m mary
ally. ' s ow t e sequence of bits transferred seri-
6. In Question 5, find the overhead due t f .
7 ti
. Ca Ieu Iate the
e time 0 rammg
it takes to transfer 10 O· .
usc 9600 bps Wh I . ,00 characters as 111 Question 5 if we
. a percentage of lime is wast d d
8. True or false. RS232 is not TTL : e uc to overhead?
9 -compatible
10 What voltage levels arc used for binary 0 in' RS232?
. True or false. The 8051 has a built-in UART .
II. On the back of x86 PCs, we normally have . .
12. The PC COM ports arc designated b '0 - COM port connectors,
___ ' y as and Windows as and
SECTION 10.2: 8051 'CONNECTION TO RS232

In this section, the details of the physical connections of the 8051 to RS232
connectors are given, As stated in Section 10,2, the RS232 standard is not TTL
compatible; therefore, it requires a line driver such as the MAX232 chip to con-
vert RS232 voltage levels to TTL levels, and vice versa. The interfacing of 8051
with RS232 connectors via the MAX232 chip is the main topic of this section.
RxD and TxD pins in the 8051
The 8051 has two pins that are used specifically for transferring and receiv-
ing data serially. These two pins arc called TxD and RxD and are part of the port
3 group (P3.0 and P3.1). Pin I j of the 8051 (P3d) is assigned to TxD and pin 10
(P3.0) is designated as RxD. These pins are TTL compatible; therefore, they
require a line driver to make them RS232 compatible. One such line driver is the
MAX232 chip. This is discussed next.
MAX232

Since the RS232 is not compatible with today's microprocessors and


rnicrocontrollers, we need a line driver (voltage converter) to convert the RS232's
signals to TTL voltage levels that will be acceptable to the 805 J 's TxD and RxD
pins. One example of such a converter is MAX232 from Maxim Corp.
(www.maxim-ie.eom). The MAX232 converts from RS232 voltage levels to TTL
voltage levels, and vice versa. One advantage of the MAX232 chip is that it uses
a +5 V power source which, is the same as the source voltage for the 805 I. In other
words, with a single +5 V power supply we can power both the 8051 and
MAX232, with no need for the dual power supplies that arc common in many
older systems, . I.. .
The MAX232 has two sets of line drivers for transfernng and rccerving
data, as shown in Figure 10-7. The line drivers used for TxD are called T J and T2,

Vee

16
1C3 +
+ 2
8051 MAX232
C1 1
3 MAX232 6 11 11 14 2
TxDO (P3.1)
+
C2
4
5 T+
C4
13 3 '0 5

T11N T10UT 10 12
11 14 RxDO (P3.0) 08-9
R10UT R11N .
12 13
T21N T20UT
10 7
R20UT R21N
9 8

TTL side 15 RS232 side


-

Figure 10-7. (a) Inside MAX232 and I S

- MMING IN ASSEMBLY AND C 285


CHAPTER 10: 8051 SERIAL PORT PROGM.
while the line drivers for RxD are designated as RJ and R2. In many applications
only one of each is used. For example, TI and R I arc used together for TxD and
RxD of the 8051, and the second set is left unused. Notice m MAX232 that the T I
line driver has a designation ofTI in and TI out on pin numbers II and 14, respec-
tively. The TJin pin is the TTL side and is connected to TxD of the microcon-
troller, while Tlout is the RS232 side that is connected to the RxD pin of the
RS232 DB connector. The Rl Iinc driver has a designation of R I in and R lout on
pin numbers 13 and 12, respectively. The Rlin (pin 13) is the RS232 side that is
connected to the TxD pin of the RS232 DB connector, and Rlout (pin 12) is the
TTL side that is connected to the RxD pin of the microcontroller. See Figure 10-7.
Notice the nuJl modem connection where RxD for one is TxD for the other.
MAX232requires four capacitors ranging from 1 to 22 ~F. The most wide-
ly used value for these capacitors is 22 ~F.
MAX233

To save board space, some designers usc the MAX233 chip from Maxim.
The MAX233 performs the same job as the MAX232 but eliminates the need for
capacitors. However, the MAX233 chip is much more expensive than the
MAX232. Notice that MAX233 and MAX232 are not pin compatible. You cannot
take a MAX232 out of a board and replace it with a MAX233. See Figure 10-8
for MAX233 with no capacitor used.

Vee
13
14 7
11
12 MAX233 15
17 16 8051
MAX233
10 11
TxDO (P3.1) 2 5 2,-
T11N T10UT
2
5 4
R10UT R11N 31Jh
3
4 RxDO (P3.0) 10 3
T21N T20UT DB·9
18
R20UT R21N
20
19
6 9
TIL side
RS233 side

Figure 10-8. (a) Inside MAX233


. and (b) Its Connection to the 8051 (Null Modem)
ReView Questions
/.
True or false Thc PC COM
2. Which' .f h port connector is the RS232 type
. PillS a t c 805/ are set aside forsr-: . .'
their functions? r senal COmmunication, and what are
3. What arc line drivers such as MAX 232 d C
4. MAX232 can usc .or?
5 Whar . support _ lines for TxD and li
. at IS the advantage of the MAX233 __ . Illes for RxD.
over the MAX232 chip?

286
-
CH
SECTION 10.3: 8051 SERIAL PORT PROGRAMMING IN
ASSEMBLY .
Table 10-3: PC
Baud Rates . In this section we discuss the serial communication regis-
110 ters of the 8051 and show how to program them to transfer and
150 receive data serially. Since IBM PC/compatible computers are so
300 widely used to communicate with 805] -based systems, we will
600 emphasize serial communications of the 8051 with the COM port
1200 of the Pc. To allow data transfer between the PC and an 8051 sys-
2400 tem without any error, we must make sure that the baud rate of thc
8051 system matches the baud rate of the PC's COM port. Some of
4800
the baud rates supported by PC BIOS are listed in Table 10-3. You
9600
can examine these baud rates by going to the Windows
19200
Note: Some of the
HyperTcrminal program and clicking on the Communication
Baud rates sup- Settings option. The HyperTerminal program comes with
ported by 486/ Windows. HyperTerminal supports baud rates much higher than
Pentium IBM
PC BIOS. the ones listed in Table 10-3.

Baud rate in the 8051


The 8051 transfers and receives data serially at many different baud rates.
The baud rate in the 8051 is programmable. This is done with the help ofTimcr I.
Before we discuss how to do that, we will look at the relationship between the
crystal frequency and the baud rate in the 8051. .
As discussed in previous chapters, the 8051 divides the crystal frequency
by 12 to get the machine cycle frequency. In the case of XTAL = 11.0592 MHz,
the machine cycle frequency is 921.6 kHz (l1.0592 MHz / 12 = 921.6 kllz). The
8051 's serial communication UART circuitry divides the machine cycle frequcn-
cy of921.6 kHz by 32 once more before it is used by Timer 1 to set the baud rate.
Therefore, 921.6 kHz divided by 32 gives 28,800 Hz. This is the number we will
use throughout this section to find the Timer 1 value to set the baud rate. When
Timer I is used to set the baud rate it must be programmed in mode 2, that is 8-bit,
auto-reload. To get baud rates compatible with the PC, we must load TH I with the
values shown in Table 10-4. Example 10-1 shows how to verify the data in Table
10-4.

Table 10-4: Timer t TUt Register Values for Various Baud Rates

Baud Rate TUt (Decimal) TUt (Hex)


9~ 3 ro
4~ 6 AA
2400 12 F4
1200 24 E8
Note: XTAL = 11.0592 MHz.

CHAPTER to: 805t SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 287


Example 10-1 THl value needed to have the following baud
With XTAL = 11.0592 MHz, find the
rates (a) 9600 (b) 2400 (c) 1200

Solution:

With XTAL = I J .0592 MHz, we have:

. of the 8051 = 11.0592 MHz /12 = 921.6 kHz, and


The machme
92.1.6kHz / 32cycle Hz is the frequency proviided by UART to Timer I to set baud
frequency
= 28,800
rate.

(a) 28,80013 = 9600 where -3 = FD (hex) is loaded into TH I


(b) 28,800 I 12 = 2400 where -12 = F4 (hex) is loaded into THI
(c) 28,800 124 = 1200 where -24 = E8 (hex) is loaded into TH 1

Notice that II 12th of the crystal frequency divided by 32 is the default value up~n acti-
vation of the 8051 RESET pin. We can change this default settmg. This IS explained at
the end of this chapter.

11.0592 MHz

Machine cycle freq.


XTAL
oscillator
-i- 12
921.6 kHz
.. +32
28,800 Hz

by UART To Timer I to
L -J ratethe baud
set
SBUF register

SBUF is an 8-bit register used solely for serial communication in the 8051.
For a byte of data to be transferred via the TxO line, it must be placed in the SBUF
register. Similarly, SBUF holds the byte of data when it is received by the 8051 's
RxD line. SBUF can be accessed like any other register in the 8051. Look at the
following examples of how this register is accessed:

MOV SBUF,#'D'
MOV SBUF,A ;load SBUF=44H, ASCII for 'D'
MOV A,SBUF ;copy accumulator into SBUF
;copy SBUF into accumulator

The moment a byte is written into SBUF, it is framed with the start and stop
bits and transferred serially via the TxD pin. Similarly, When the bits are received
serially via RxD, the 8051 deframes it by eliminating the stop and start bits, mak-
ing a byte out of the data received, and then placing it in the SBUF.
SCON (serial control) register

. The SCON register is an 8-bit register used to program the start bit, stop
bit, and data bits of data framing, among other things.
The fOllowing describes various bits of the SCON register.

CHAPT
SMO I SMI I SM2 I REN I TB8 I RB8 I TJ R1

SMO seON.7 Serial port mode specifier


SMl seON.6 Serial port mode specifier
SM2 seON.S Used for multiprocessorcommunication. (Make it 0.)
REN seONA Set/cleared by software to enable/disable reception.
rB8 SeONJ Not widely used.
RB8 seON.2 Not widely used.
Tl seON.1 Transmit interruptflag. Set by hardware at the beginning of
the stop bit in mode I. Must be cleared by software
RI seON.O Receive interrupt flag. Set by hardware halfway through the
stop bit time in mode I. Must be cleared by software.

Note: Make SM2, TB8, and RE8 = O.


Figure 10-9. SCON Serial Port Control Register (Bit-Addressable)

SMO, SM1
. SMO and SM I are 07 and D6 of the SCON register, respectively. These
two bits determme the framing of data by specifying the number of bits per char-
acter, and the start and stop bits. They take the following combinations.

SMO SMI
o o Serial Mode 0
o I Serial Mode I, 8-bit data, I stop bit, I start bit
I o Serial Mode 2 '
I I Serial Mode 3

Of the 4 serial modes, only mode 1 is of interest to us. Further explanation


for the other three modes is in Appendix A.2. They are rarely used today. In the
SCaN register, when serial mode I is chosen, the data framing is 8 bits, 1 stop bit,
and 1 start bit, which makes it compatible with the COM port of IBM/compatible
,PCs. More importantly, serial mode I allows the baud rate to be variable and is
set by Timer I of the 8051. In serial mode 1, for each character a total of 10 bits
are transferred, where the first bit is the start bit, followed by 8 bits of data, and
finally I stop bit.
5M2
SM2 is the 05 bit of the seON register. This bit enables the multiprocess-
ing capability of the 8051 and is beyond the discussion of this chapter. For our
applications, we will make SM2 = 0 since we are not using the 8051 in a multi-
processor environment.
REN
The REN (receive enable) bit is 04 of the SeON register. The REN bit is
also referred to as SeONA sinee seON ISa bIt-addressable register. When the
REN bit is high it allows the 8051 to receive data on the RxO pin of the 8051. As
a result if we want the 8051 to both transfer and receive data, REN must be set to
I. By making REN = 0, the receiver is disabled. Making REN = I or REN = 0 can

CHAPTER 10: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 289


· . . ." ETB SCON. 4" and "CLR SCON. 4 ", rcspec-
be achieved by the instructions S the bit-addressable features of register
tively. Notice that these mstructions use . I data reception and is an extreme-
SCON. This bit can be used to block any sen a
Iy important bit in the SCON register.
TBB
f biIt 8)' IS bitI 03 ofSCON . It .is used
TB8 (transer . for serial modes 2 and 3.
We make TB8 = 0 since it is not used in our applications.
RBB

RB8 (receive bit 8) is bit D2 of the SCON register. In serial mode I, this
bit gets a copy of the stop bit when an 8-bit data is received. This bit (as ISthe ~ase
for TB8) is rarely used anymore. In all our applications we will make RB8 - O.
Like TB8, the RB8 bit is also used in serial modes 2 and 3.
TI

TI (transmit interrupt) is bit 0 I of the SCON register. This is an extreme-


ly important flag bit in the SCON register. When the 8051 finishes the transfer of
the 8-bit character, it raises the TJ flag to indicate that it is ready to transfer anoth-
er byte. The TJ bit is raised at the beginning of the stop bit. We will discuss its role
further when programming examples of data transmission are given.
RI

RI (receive interrupt) is the DO bit of the SCON register. This is another


extremely important flag bit in the SCON register. When the 8051 receives data
serially via RxD, it gets rid of the start and stop bits and places the byte in the
SBUF register. Then it raises thc RI flag bit to indicate that a byte has been
received and should be picked up before it is lost. RI is raised halfway through the
stop bit, and we will soon see how this bit is used in programs for receiving data
serially.

Programming the 8051 to transfer data serially


In programming the 8051 to transfer character bytes serially, the following
steps must be taken.
I. The TMOO register is loaded with the value 20H, indicating the use of Timer
I in mode 2 (8-bit auto-reload) to set the baud rate.
2. The THI is loaded with one of the values in Table 10-4 to set the baud rate for
serial data transfer (assuming XTAL = 11.0592 MHz).
3. The SCON register is loaded with the value 50H, indicating serial mode I,
where an 8-blt data IS framed with start and stop bits.
4. TR I is set to 1 to start Timer I.
5. TI is cleared by the "CLR TI" instl1lction.
6. The character byte to be transferred serially is written into the SBUF register.
7. TheTI flag bit IS mOl1ltoredWith the use of the instruction "JNB TI, xx" to
see If the character has been transferrcd completely.
8. To transfer the next character, go to Stcp 5.
Example 10-2 shows a program to transfer data serially at 4800 baud.
Example 10-3 shows how to transfer "YES" conn I
inuous y.

290
Example 10-2
Write a program for the 8051 to tr ansfer letter "An serially at 4800 ba ud , continuously.
.

Solution:
MOV TMOD,#20H ;Timer 1 , mod
0 e 2(auto-reload}
MOV TH1,#-6 ;4800 baud rate
MOV SCON,#50H ;8-bit, 1 stop, REN enabled
SETB TRl ;start Timer 1·
AGAIN: MOV SBUF,,#IIA" ;le~ter "A" to be transferred
HERE: JNB TI,HERE ;walt for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A

Example 10-3
Write
bit. Doa this
program to transfer the messa ge "YES" serially
continuously. . at 9600 baud, 8-bit data, I stop

Solution:
MOV TMOD,#20H ;Timer 1,'mode 2
MOV TH1,#-3 ;9600 baud
MOV SCON, #50H ;8-bit, 1 stop bit, REN enabled
SETB TRl ;start Timer 1
AGAIN: MOV A,#"yll ;transfer "yu
ACALL TRANS
MOV A, #11£11 ;transfer liE"
ACALL TRANS
;transfer IISIl
MOV A, #ltSH
ACALL TRANS
SJMP AGAIN ;keep doing it
;-----serial data transfer subroutine
TRANS: MOV SBUF ,A ;load SBUF
HERE: JNB TI ,HERE ;wait for last bit to transfer
CLR TI ;get ready for next byte
RET

Importance of the TI flag


To understand the importance of the role of Tl, look at the following
sequence of steps that the 8051 goes through in transmitting a character via TxD.
I. The byte character to be transmitted is written into the SBUF register.
2. The start bit is transferred.
3. The 8-bit character is transferred one bit at a time.
4. The stop bit is transferred. It is during the transfer of the stop bit that the 8051
raises the TI flag (TI = 1), indicating that the last character was transmitted
and it is ready to transfer the next character.
5. By monitoring the II flag, we make sure that we are not overloading the SBUF
register. If we write another byte into the SBUF register before TI is raised, the
untransmitted portion of the previous byte will be lost. In other words, when

CHAPTER JO: 8051 SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 291


the 8051 finishes transferring a byte, it raises the II flag to indicate it is ready
for the next character.
6. After SBUF is loaded with a new byte, the TI flag bit must be forced to 0 by
the "CLR TI" instruction in order for this new byte to be transferred.
From the above discussion we conclude that by checking the TI flag bit, we
know whether or not the 8051 is ready to transfer another byte. More importantly,
it must be noted that the TI flag bit is raised by the 8051 itself when it finishes the
transfer of data, whereas it must be cleared by the programmer with an instruction
such as "CLR TI". It also must be noted that if we write a byte into SBUF before
the TI flag bit is raised, we risk the loss of a portion of the byte being transferred.
The TI flag bit can be checked by the instruction "JNB TI, ... " or we can use
an interrupt, as we will see in Chapter II. In Chapter II we will show how to use
interrupts to transfer data serially, and avoid tying down the microeontroller with
instructions such as "JNB TI, xx".

Programming the 8051 to receive data serially


ln the programming of the 8051 to receive character bytes serially, the fol-
lowing steps must be taken.
I. The TMOD register is loaded with the value 20H, indicating the usc of Timer
I In mode 2 (8-bit auto-reload) to set the baud rate.
2. TH I is loaded with one of the values in Table 10-4 to set the baud rate (assum-
ing XTAL = 11.0592 MHz).
3. The SCON register is loaded with the value SOH, indicating serial modc I,
where 8-blt data IS framed with start and stop bits and receive enable is turned
on.
4. TR I is set to I to start Timer I.
5. RI is cleared with the "CLR RI" instruction.
6. The RI flag bit is monitored with the usc of the instruction "JNB RI, xx" to
see If an entire character has been received yet.
7. When Rl is raIsed, SBUF has the byte. Its contents arc moved into a safe place.
8. To receive the next character, go to Step 5.
Examples 10-4 and 10-5 shows the COding of the above steps.
Example 10-4

Program the 8051 to receive bytes of data . II


at 4800, 8-bit data, and I stop bit. sen a y, and put them in P I. Set the baud rate

Solution:
MOV TMOD,#20H T'
MOV TH1,#-6 ; ~mer 1, mode 2(auto-reload)
;4800 baud
MOV SCON,#50H
SETB TR1 ;8-bit, 1 stop, REN enabl~d
HERE: JNB ;start Timer 1
RI,HERE
MOV A,SBUF ;wait for char to come in
MOV P1,A ;save incoming byte in A
CLR RI ;send to port 1
SJMP HERE ;get ready to rece've
• next byte
;keep getting data
292
Example 10-5
Assume that the 8051 serial port is connected to the COM port of the IBM PC, and on
the PC we are using the HyperTerminal program to send and receive data serially. PI
and P2 of the 8051 are connected to LEDs and switches, respectively. Write an 8051
program to (a) send to the PC the message "We Are Ready", (b) receive any data sent
by the PC and put it on LEDs connected to Pl, and (c) get data on switches connected
to P2 and send it to the PC serially. The program should perform part (a) once, but parts
(b) and (c) continuously. Use the 4800 baud rate.

Solution:

ORG 0
MOV P2 , #OFFH ;make P2 an input port
MOV TMOD,#20H ;Timer 1, mode 2 (auto-reload)
MOV TH1, #OFAH ;4800 baud rate
MOV scon. #50H ;s-bit,l stop, REN enabled
SETB TR1 ;start Timer 1
MOV DPTR,#MYDATA ;load pointer for message
H 1: CLR A
MOVC A,@A+DPTR ;get the character
JZ B 1 ;if last character get out
ACALL SEND ;otherwise call transfer
INC DPTR jnext one
SJMP H 1 ; stay in loop
B 1: MOV A, P2 ; read data on P2
ACALL SEND ;transfer it serially
ACALL RECV ;get the serial data
MOV P1,A ;display it on LEDs
SJMP B_1 ;stay in loop indefinitly
t
·--------------serial data transfer. ACC has the data
SEND: MOV SBUF,A ·load the data
H2: JNB TI,H_2 ;stay here until last bit gone
- CLR TI ;get ready for next char
RET ;return to caller
,.----------------receive data serially in Ace
RECV: JNB RI ,RECV ,.wait here for char
MOV A, SBUF ,. save it in ACC
;get ready for next char
CLR RI
RET ,'return to caller
. The message
,
MYDATA: DB "We Are Ready", 0
END
8051
-,
) LED
PI
To TxO 7
PC
COM /
SW
port RxO P2 "\

"
MMING IN ASSEMBLY AND C 293
CHAPTER 10: 8051 SERIAL PORT PROGRA
Importance of the RI flag bit
In receiving bits via its RxO pin, the 805 I goes through the following
steps.

I. It receives the start bit indicating that the next bit is the first bit of the charac-
ter byte it is about to receive. .. '"
2. The -bit character is received one bit at lime. When the last bit IS received, a
byte is formed and placed in SBUF. . _
J. The stop bit is received. When receiving the stop bit the 8051 makes RI -k J ,
indicating that an entire character byte has been received and must be pIC e d
up before it gets overwritten by an incoming character.
4. By checking the Rl flag bit when it is raised, we know that a character has been
received and is sitting in the SBUF register. We copy the SBUF contents to a
safe place in some other register or memory before it is lost.
5. Aller the SBUF contents are copied into a safe place, the RI flag bit must be
forced to 0 by the "CLR RI" instruction in order to allow the next received
character byte to be placed in SBUF. Failure to do this causes loss of the
received character.

From the above discussion we conclude that by checking the RI flag bit we
know whether or not the 8051 has received a character byte. If we fail to copy
BUF into a safe place, we risk the loss of the received byte. More importantly, it
must be noted that the RI flag bit is raised by the 805 I, but it must be cleared by
the programmer with an instruction such as "CLR RI". It also must be noted that
if we copy SBUF into a safe place before the RI flag bit is raised, we risk copying
garbage. The RI flag bit can be checked by the instruction "JNB RI, xx" or by
u ing an interrupt, as we will sec in Chapter I I.

Doubling the baud rate in the 8051

There arc two ways to increase the baud rate of data transfer in the 8051.

I. Usc a higher-frequency crystal.


2. hange a bit in the PCON register, shown below.
D7
00
[SMOD I. I I OFI I OFO I PD I IDL I
. OptIOn I IS ~ot feasible in many situations since the system crystal is fixed.
More .Importantly, It IS not feasible because the new crystal may not be compati-
ble with the IBM PC serial COM port's baud rate The c '11 I
. 2 T . . rerore, we WI exp ore
opuon . here IS a software way to double the baud rate of the 8051 whi Ie the
crystal frequency IS fixed. This is done with the register called PC ON (power eon-
trol). The PCON register IS an 8-bit register Of the 8 bit d
. I s, same are unused, an
thorne are used for the power control capability of the 8051 Tile bit th t . d f
e scna. I eommul1leatlOn
". IS 07 the SMOO .(s . I . . I a IS usc or
powered up, 07 (SMOD bi;) of;hc PC .' cnai mode) bit, When the 8051 is
ON register IS zero. We can set it to high by
294
f IOWing
software and thereby double the bau d rate. Thee ',01 . sequence of ..mstrucuons
must be used to set high 07 of PCON' , since It
.. IS not a biIt-a d dressable register:
.

MOV A,PCON ;place a copy of PCON in ACC


SETB ACC.7 ;make D7=1
MOV PCON,A ;now SMOD=l without
I

;changing any other bits

To see how the baud rate is doubled with this method, we show the role of
the SMOO bit (07 bit of the peON register), which can be 0 or I. We discuss each
case.
Baud rates for SMOD =0
When SMOO = 0, the 8051 divides 1/12 of the crystal frequency by 32 and
uses that frequency for Timer I to set the baud rate. In the case ofXTAL = 11.0592
MHz we have:

Machine cycle freq. = 11.0592 MHz / 12 = 921.6 kHz


and
921.6 kHz / 32 = 28,800 Hz since SMOD = 0

This is the frequency used by Timer I to set the baud rate. This has been
the basis of all the examples so far since it is the default when the 8051 is powered
up. The baud rate for SMOO = 0 was listed in Table 10-4.
Baud rates for SMOD =1
With the fixed crystal frequency, we can double the baud rate by making
SMOO = I. When the SMOO bit (07 of the PCON register) is set to I, 1/12 of
XTAL is divided by 16 (instead of32) and that is the frequency used by Timer 1
to set the baud rate. In the case of XTAL = 11.0592 MHz, we have:

Machine cycle freq. = 11.0592 MHz / 12 = 921.6 kHz


and
921.6 kHz / 16 = 57,600 Hz since SMOD = 1

This is the frequency used by Timer I to set the baud rate,


Table 10-5: Baud Rate Comparison for SMOD = 0 and SMOD = 1
THI ( Decimal) (Hex) SMOD =0 SMOD = I
-3 FO 9,600 19,200
6 FA 4,800 9,600
12 F4 2,400 4,800
-24 E8 1,200 2,400
Note: XTAL = 11.0592 MHz.
h values loaded into TH I are the same for both
Tablc 1O - 5 sows t h a t thee doubled when MOD = I. Look at the follow-
cases' however, t h e b au d t es ar
.' if ra
h d t given in Table 10-5. See also E'xamples 10-6
mg examples 10 clan y tea a
through 10- 10.
MMI G I 295
CHAPTER 10: 8051 SERIAL PORT PROGRA
Example 10-6 .
. Hz for the following program, state (a) what this pro-
Assuming that XTAL - 11.0592 M d by Timer I to set the baud rate, and (c) find
gram does, (b) compute the frequency use
the baud rate of the data transfer.

MOV A, PCON ;A = PCON


SET8 ACC.7 ;make D7 = 1
MOV PCON,A 'SMOD = 1, double baud rate
:with same XTAL freg.
MOV TMOD,#20H :Timer 1, mode 2 (auto-reload)
MOV TH1,-3 ,:19200 (57,600 / 3 = 19200 baud rate
;since SMOD=l)
MOV SCON,#50H ;s-bit data,l stop bit, RI enabled
SETB TR1 ;start Timer 1
MOV A,#IIBII ;transfer letter B
AI: CLR TI ;make sure TI=O
MOV SBUF,A ;transfer it
H 1: JNB TI H 1 ;stay here until the last bit is gone
SJMP A 1 ;keep sending "B" again and again

Solution:

(a) This program transfers ASCII letter B (010000 10 binary) continuously.


(b) With XTAL = 11.0592 MHz and SMOD = 1 in the above program, we have:

I].0592 MHz / 12 = 92].6 kHz machine cycle frequency


921.6 kHz / 16 = 57,600 Hz frequency used by Timer 1 to set the baud rate
57,600 Hz / 3 = 19,200 baud rate

Example 10-7

Find the TH 1 value (in both decimal and hex) to set the baud rate to each of the following.
(a) 9600 (b) 4800 if SMOD = 1 Assume that XTAL = I] .0592 MHz.

Solution:

With XTAL = 11.0592 MHz and SMOD = I, we have Timer I frequency = 57,600 Hz.
(a) 57,600/9600 = 6; therefore, TH I = -6 or TH I = FAH.
(b) 57,600/4800 = ]2; therefore, THI = -12 or THI = F4H.

j 1.0592 MHz SMOD = I

XTAL
oscillator -
G +12
Machine cyele freq
921.6 kHz
'.
rl + 16 157,600 Hz

J ~ 128,800
-~L . 32 I
SMOD = 0
Hz
To
__ Timer I
to set
baud
rate

296
-c
Example 10-8
Find the baud rate ifTHI = -2, SMOD = I, and XTAL = 11.0592 MHz. Is this baud
rate supported by IBM/compatible PCs?

Solution:
With XTAL = 11.0592 MHz and SMOD = 1, we have Timer 1 frequency = 57,600Hz.
The baud rate is 57,600/2 = 28,800. This baud rate is not supported by the BIOS of
the PCs; however, the PC can be programmed to do data transfer at such a speed. Also,
HyperTerminal in Windows supports this and other baud rates.

Example 10-9
Assume a switch is connected to pin Pl.7. Write a program to monitor its status and
send two messages to serial port continuously as follows:
SW=O send "NO"
SW=I send "YES"
Assume XTAL = 11.0592 MHz, 9600 baud, 8-bit data, and 1 stop bit.

Solution:
SW1 EQU Pl.?
ORG OH ;starting position
MAIN: MOV TMOD,#20H
MOV TH1,#-3 ;9600 baud rate
MOV SCON,#50H
SETB TR1 ;start timer
SETB SW1 ;make swan input
Sl: JB P2.1,NEXT ; check SW status
MOV DPTR,#MESS1 ; if' Sw=o display "NO"
FN: CLR A
MOVC A,@A+DPTR ;read the value
JZ Sl ;check for end of line
ACALL SENDCOM ,.send value to serial port
DPTR ,.move to next value
INC
SJMP FN ;repeat
DPTR,#MESS2 ;if SW= 1 d i sp lay "YES"
NEXT: MOV
LN: CLR A
MOVC A,@A+DPTR ,'read the value ,

JZ Sl ,.check for end of lIne


.send value to serial port
ACALL SEND COM
:move
, to next value
INC DPTR
LN ; repeat
SJMP
j----------- -------
;place value in buffer
SENDCOM: MOV SBUF,A
TI,HERE ,.wait until transmItted
HERE: JNB
iclear
CLR TI
jreturn
RET
; ----------- -------

MESS1: DB II NO ,0
If

MESS2 : DB lIYES",O
END

MING IN ASSEMBLY AND C 297


CHAPTER 10: 8051 SERIAL PORT PROGRAM
Example 10-10 " . 1
a e "The Earth is but One Country to sena port.
Write a program to send the mess ~I 2 Monitor its status and set the baud rate as fol-
Assume a SW IS connected to pm ..
lows:

SW = 0, 4800 baud rate


SW = 1, 9600 baud rate

Assume XTAL = 11.0592 MHz, 8-bit data, and I stop bit.

Solution:

SW BIT PI.2
ORG OH ;Starting position
MAIN:
MOV TMOD,#20H
MOV TH1,#-6 ·4800 baud rate
r (default)
MOV SCON,#50H
SETB TR1
SETB SW ;make SWan input
81: JNB SW,SLOWSP ;check SW status
MOV A,PCON ;read PCON
SETB ACC.7 ;set SMOD High for 9600
MOV PCON,A ;write PCON
SJMP OVER ;send message
SLOWSP: MOV A,PCON ;read PCON
CLR ACC.7 ;make SMOD Low for 4800
MOV PCON,A
OVER: ;write PCON
MOV DPTR,#MESS1
FN: ;load address to message
CLR A
MOVC A,@A+DPTR ;read value
JZ Sl
ACALL SENDCOM ;check for end of line
INC ;send value to the serial port
DPTR
SJMP ;move to next value
FN
;repeat
i----------- __

SENDCOM:
MOV SBUF,A
HERE: JNB ;place value in buffer
TI,HERE
CLR TI ;wait until transmitted
RET ;clear
/'return
i-------- _
MESS1: DB "The Earth l·S b t 0
END u ne Country",o

298
Interrupt-based data transfer
By now you might have noticed that it is a waste of the microcontroller's
time to poll the TI and RI flags. In order to avoid wasting the microcontroller's
time we use interrupts instead of polling. In Chapter II, we will show how to use
interrupts to program the 8051 's serial communication port.

Review Questions
I. Which timer of the 8051 is used to set the baud rate?
2. If XTAL = 11.0592 MHz, what frequency is used by the timer to set the baud
rate?
3. Which mode of the timer is used to set the baud rate?
4. With XTAL = 11.0592 MHz, what value should be loaded into THI to have a
9600 baud rate? Give the answer in both decimal and hex.
5. To transfer a byte of data serially, it must be placed in register _
6. SCON stands for and it is a(n) __ -bit register.
7. Whieh register is used to set the data size and other framing information such
as the stop bit?
8. True or false. SCON is a bit-addressable register.
9. When is TI raised?
10. Whieh register has the SMOD bit, and what is its status when the 8051 is pow-
ered up?

RAMMING IN ASSEMBLY AND C 299


CHAPTER 10: 8051 SERIAL PORT PROG
SECTION 10.4: PROGRAMMING THE SECOND SERIAL PORT
. f the 8051 microcontrollers come with two
Many of the new g:n~ra~~n;9~420/30/40/. ..) and DS80C320 are among
serial ports. The. DS89C x (h amming of the second serial port of the
them. In this section we show t e progr
DS89C4xOchip.

DS89C4xO second serial port


The seeond scna. I port of the DS89C4xO ' uses pins PI.2 and P'. 1.3 for the Rx
.
and Tx /incs, respeetiIV ely. Sec Figure 10-10'. The MDE8051 Trainer (available
.
OM'
,rom www. leroDigitalfid
I .com) uses the DS89C4xO chip and eomes with two .

serial ports already installed. It also uses the MAX232 for the RS232 connection
DB9 The connections for the RS232 to the DS89C4xO of the MDE8051
W . .I
Trainer are shown in Figure 10-11. Notice that the first and seeond sen a ports are
designated as Serial #0 and Serial # I, respectively.
Addresses for all SCON and SBUF registers
All the programs we have seen so far in this chapter assume the use of the
first serial port as the default serial port since every version of the 8051 eomes with
at least one serial port. The SCON, SBUF, and PCON registers of the 8051 are
part of the special function registers. The address for eaeh of the SFRs is shown
in Table 10-6. Notice that SCON has address 98H, SBUF has address 99H, and
finally PCON is assigned the 87H address. The first serial port is supported by all
assemblers and C compilers in the market for the 8051. If you examine the list file
for 8051 Assembly language programs, you will see that these labels are replaced
with their SFR addresses. The second serial port is not implemented by all ver-
sions of the 8051/52 mieroeontroller. Only a few versions of the 8051/52, sueh as
the DS89C4xO,come with the second serial port. As a result, the second serial port
uses some reserved SFR addresses for the SCaN and SBUF registers and there is
no universal agreement among the makers as to which addresses should be used.
In the case of the DS89C4xO, the SFR addresses of COH and C IH are set aside for
SBUF and SCaN, as shown in Table 10-6. The DS89C4xO technical doeumenta-
tion refers to these registers as SeON I and SBUF I since the first ones are desig-
nated as SCONOand SBUFO.

Table 10-6: SFR Byte Addresses for DS89C4xO Serial Ports

First Serial PorI


Second Serial Port
seONO= 98H
SCONI =COH
SBUFO= 99H
SBUFI = CIH
TLI=8BH
THI=8DH
TLI = 8BH
THI=8DH
TeONO = 88H
TCONO = 88H
reo» =87H PCON = 87H
300
DIP

(T2) P10 1
40 Vee
(T2EX) P1, 1 2 39 PO.O(ADO)
(RXD1) P1,2 3
38 PO.1 (AD1)
(TXD1) P1,3 4
OS 37 PO.2 (AD2)
(INT2) P14 5 36 PO.3 (AD3)
(INT3) P1,5 6 89C4xO
35 P04 (AD4)
(INT4) P16 7 (89C420 34 PO.5 (AD5)
(iNT5) P1,7 8 89C430 33 PO.6 (AD6)
RST 9 89C440 32 PO.7(AD7)
(RXDO) P3,0 10
89C450) 31 EANPP·
(TXDO) P3,1 11 30 ALE/PROG
(INTO) P3.2 12 29 PSEN
(lNT1) P3.3 13 28 P2.7 (A15)
(TO) P3.4 14 27 P26(A14)
(T1) P3.5 15 26 P2.5 (A13)
(WR) P3.6 16 25 P24 (A12)
(RD) P3.7 17 24 P2.3 (A11)
XTAL2 18 23 P2.2 (A10)
XTAL1 19 22 P2.1 (A9)
GND 20 21 P2.0 (A8)

t:
Figure 10-10. DS89C4xO Pin Diagram
Notice Pl.2 and PI.3 pins are used by Rx and Tx lines of the 2nd serial

Vee
C3
16 +
+ 2
C1 1
3 MAX232 6 DS89C4xO MAX232
i
+
C2
4
5
I ~4 TxDO(P3.1) 11 11 14 2 5
ro
'C
RxDO(P3.0) 10 12 13 3 0 ~
Ul
T1IN T10UT
11 14
R11N 7 5 it
R10UT 20 ro
12 13 4 10 'C
TxD1(P1.3) 8 3 ~
Ul
T21N T20UT RxD1(P1,2j
3 9
10 7
R20UT R21N
9 8

TTL side 15 RS232 side


.
Figure 10-11. (a) Inside MAX232 and (b) its Connection to the DS89C4xO

- CHAPTER 10: 80511SERIAL PORT PROGRAMMING IN ASSEMBLY AND C 301


· Address
Symbol Name EOH
ACC" Accumulator FOH

SP Stack pointer
DPTR Data pointer 2 bytes
DPL Low byte 82H
DPH High byte 83H
PO" Port 0 80H
PI" Port I 90H
P2" Port 2 OAOH
P3" Port 3 BOH
JP" Interrupt priority control B8H
IE" Interrupt enable control A8H
TMOD Timer/counter mode control 89H
TCON" Timer/counter control 88H
T2CON" Timer/counter 2 control C8H
T2MOD Timer/counter mode control C9H
THO Timer/counter 0 high byte 8CH
TLO Timer/counter 0 low byte 8AH
TH I Timer/counter I high byte
8DH
TL I Timer/countcr I low byte
8BH
TH2 Timer/counter 2 high byte
CDf-/
TL2 Timer/counter 2 low byte
CCH
RCAP2H T/C 2 capture register high byte
CBH
RCAP2L T/C 2 capture register low byte
CAH
SCONO" Serial control first serial ort
98H
SBUFO Serial data buffer first serial art
PCON Power control 99H
87H
SCON I" Serial control (second serial port)
COH
SBUF I Serial data buffer (second serial port)
" Bit-addressable CIH

Programming the second serial port using timer 1


While each serial port has its own SCON and SBUF registers, both ports
can usc Timer I for setting the baud rate, Indeed, upon reset, the DS89C4xO chip
uses Timer 1 for setting the baud rate of both serial ports, Sincc the older 8051
assemblers do not support this new second serial port, we necd to define them as
shown in Examplc 10-11, Notice that in both C and Assembly, SBUF and SCON
refer to the SFR registers of the first serial port, To avoid confusion, in DS89C4xO
programs we use SCONO and SBUFO for the first and SCON I and SBUF I for the
second serial ports, For this reason, the MDE8051 Traincr designates the serial
ports as Serial #0 and Serial # I in order to comply with this designation,
Sec Examples 10-12 through 10-14,

302
SMO I SM] I SM2 I REN I TS8 I RE8 I TI I RJ

Bits Bit Addresses


Serial #0 Serial #1
SMO SCONO.7 ~ 9FH SCON1.7 ~ C7H Serial port mode specifier
SMI SCONO.6 ~ 9EH SCONl.6 ~ C6H Serial port mode specifier
SM2 SCONO.5 ~ 9DH SCON 1.5 ~ C5H Multiprocessor com.
REN SCONOA ~ 9CH SCON IA ~ C4H Enable/disable reception
TB8 SCONOJ ~ 9BH SCON 1.3 ~ C3H Not widely used
RB8 SCONO.2 ~ 9AH SCON 1.2 ~ C2H Not widely used
TI SCONO.l ~99H SCONl.] ~C]H Transmit interrupt flag
RJ SCONO.O ~ 98H SCON 1.0 ~ COH Receive interrupt flag

Note: Make SM2, TB8, and RE8 ~ O.


Figure 10-12. SCONO and SCONI Bit Addresses (Tl and RJ bits must be noted)

Example 10-11
Write a program for the second serial port of the DS89C4xO to continuously transfer the
letter "A" serially at 4800 baud. Use 8-bi! data and 1 stop bit. Use TImer I.

Solution:

SBUFI EQU OCIH ;second serial SBUF addr


SCONI EQU OCOH ;second serial SCON addr
TIl BIT OCIH ;second serial TI bit addr
RIl BIT OCOH ;second serial RI bit addr

ORG OH ;starting position


MAIN:
MOV 'rMOD,#20H ;COM2 uses Timer 1 upon reset
MOV TH1,#-6 ;4800 baud rate
MOV SCON1,#50H ;COM2 has its own SCONI
SETB TRl ;start Timer 1
AGAIN: MOV A,#'A' ;send char 'A'
ACALL SENDCOM2
SJMP AGAIN
-------------
SENDCOM2:
MOV SBUFl,A ;COM2 has its own SBUF
HERE: JNB TII,HERE ;COM2 has its own TI flag
CLR TIl
RET
END

- CHAPTER 10: 8051 SERIAL PORT PROG


RAMMING IN ASSEMBLY AND C 303
1 Example 10-12
Write a program to send the text string
. "Hello" to Serial # 1. Set the baud rate at 9600,
8-bit data, and I stop bit.

Solution:
SCONI EQU OCOH
SBUFI EQU OClH
TIl BIT OClH
ORG OH ;starting position
MOV TMOD,#20H
MOV THl,#-3 ; 9600 baud rate
MOV SCONl,#50H
SETB TRI
MOV DPTR,#MESSI ;display "Hello·
FN: CLR A
MOVC A,@A+DPTR ;read value
JZ SI ,'check for end of line
ACALL SENDCOM2 'send to serial port
INC DPTR ;move to next value
SJMP FN
SI: SJMP SI
SENDCOM2:
MOV SBUFl,A
HEREl: JNB ;place value in buffer
TIl,HERE 1 ;wait until transmitted
CLR TIl ;clear
RET
MESSI : DB "Hellon,o
END

Example 10-13

Program the second serial port of the DS89C4xO to receive bytes of data serially and put
them on PI. Set the baud rate at 4800, 8-bit data, and 1 stop bit.
Solution:
SBUFI EQU OClH
;second serial SBUF addr
SCONI EQU OCOH
;second serial SCON addr
RIl BIT OCOH
ORG OH ;second serial RI bit addr
;starting Position
MOV TMOD,#20H
MOV THl,#-6 ;COM2 uses Timer 1 Upon reset
; 4800 baud rate
MOV SCONl,#50H
SETB TRI ;COM2 has its own SCONI
HERE: ;start Timer 1
JNB RIl,HERE
MOV A,SBUFI ;wait for data to come in
;save data
MOV Pl,A
CLR RIl ;display on PI
SJMP HERE
END

304
Example 10-14
Assume that a switch is connected to pin P2.0.
Write a program to monitor the switch and perform the following:

(a) If SW = 0 send the message "Hello" to the Serial #0 port.


(b) If SW = I send the message "Goodbye" to the Serial #1 port.

Solution:
SCONl EQU DCOH
TIl BIT OC1H
SWl BIT P2.0
ORG OH
MOV ;starting position
TMOD,#20H
MOV TH1, #-3 ;9600 baud rate
MOV SCON,#50H
MOV SCON1,#50H
SETB TR1
SETB SW1 ;make SWl an input
Sl: JB SW1,NEXT ;check SW1 status
MOV DPTR,#MESS1 ;if SW1=0 display "Hello"
FN: CLR A
MOVe A,@A+DPTR ;read value
JZ Sl ;check for end of line
ACALL SEND COM 1 ;send to serial port
INC DPTR ;move to next value
SJMP FN
NEXT: MOV DPTR,#MESS2 ;if SW1=1 display "Goodbye"
LN: CLR A
MOVC A,@A+DPTR ;read value
JZ Sl ;check for end of line
ACALL SENDCOM2 ;send to serial port
INC DPTR ;move to next value
SJMP LN

SENDCOM1:
MOV SBUF,A ;place value in buffer
HERE: JNB TI,HERE iwait until transmitted
CLR TI ;clear
RET

SENDCOM2:
MOV SBUFl,A ;place value in buffer
HEREl: JNB TI1,HEREl ;wait until transmitted
CLR TIl ;clear
RET

MESS1: DB I1Helloll
I 0
MESS2: DB /lGoodbyerr,U
END

- MMING IN ASSEMBLY AND C 305


CHAPTER 10: 8051 .SERIAL PORT PROGRA
Review Questions
(All questions refer to the DS89C4xO chip). . .
I. Upon reset, which timer is used to set the baud rate for Senal #0 and Senal # I?
2. Which pins are used for the second serial ports?
3. With XTAL = 11.0592 MHz, what value should be loaded into TH 1 to have a
28,800 baud rate'? Give the answer in both decimal and hex.
4. To transfer a byte of data via the second serial port, it must be placed in regis-
ter __ -t-

5. SCON I refers to and it is a(n) __ -bit register.


6. Which register is used to set the data size and other framing information such
as the stop bit for the second serial port?

SECTION 10.5: SERIAL PORT PROGRAMMING IN C


This section shows C programming of the serial ports for the 8051/52 and
DS89C4xO chips.

Transmitting and receiving data in 8051 C

As we stated in the last chapter, the SFR registers of the 8051 are accessi-
ble directly in 8051 C compilers by using the reg51.h file. Examples 10-15
through 10-19 show how to program the serial port in 8051 C. Connect your 8051
Trainer to the PC's COM port and usc HyperTerminal to test the operation of these
examples.

Example] O-IS

Write a C program for the 8051 to transfer the letter "A" serially at 4800 baud continu-
ously. Use 8-bIt data and 1 stop bit.

Solution:

#include <regSl.h>
void main(void)
(
TMOD=Ox20;
TH1=OXFA; //use Timer 1,8-BIT auto-reload
SCON=OxSO; //4800 baUd rate
TR1=l;
while(l)
(
SBUF=' A' ;
While (TI==O) ; //place value in buffer
TI=O;

306

You might also like